Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/optimization #482

Merged
merged 8 commits into from
Dec 16, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 12 additions & 19 deletions common/ASC.Common/Security/Cryptography/InstanceCrypto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,11 @@ namespace ASC.Security.Cryptography
[Singletone]
public class InstanceCrypto
{
private MachinePseudoKeys MachinePseudoKeys { get; }
private byte[] EKey { get; }

public InstanceCrypto(MachinePseudoKeys machinePseudoKeys)
{
MachinePseudoKeys = machinePseudoKeys;
EKey = machinePseudoKeys.GetMachineConstant(32);
}

public string Encrypt(string data)
Expand All @@ -50,8 +50,8 @@ public string Encrypt(string data)

public byte[] Encrypt(byte[] data)
{
var hasher = Aes.Create();
hasher.Key = EKey();
using var hasher = Aes.Create();
hasher.Key = EKey;
hasher.IV = new byte[hasher.BlockSize >> 3];

using var ms = new MemoryStream();
Expand All @@ -70,24 +70,17 @@ public string Decrypt(string data)

public string Decrypt(byte[] data)
{
var hasher = Aes.Create();
hasher.Key = EKey();
using var hasher = Aes.Create();
hasher.Key = EKey;
hasher.IV = new byte[hasher.BlockSize >> 3];

using (MemoryStream msDecrypt = new MemoryStream(data))
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, hasher.CreateDecryptor(), CryptoStreamMode.Read))
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
using var msDecrypt = new MemoryStream(data);
using var csDecrypt = new CryptoStream(msDecrypt, hasher.CreateDecryptor(), CryptoStreamMode.Read);
using var srDecrypt = new StreamReader(csDecrypt);

// Read the decrypted bytes from the decrypting stream
// and place them in a string.
return srDecrypt.ReadToEnd();
}
}

private byte[] EKey()
{
return MachinePseudoKeys.GetMachineConstant(32);
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
return srDecrypt.ReadToEnd();
}
}
}
8 changes: 4 additions & 4 deletions common/ASC.Core.Common/Data/DbQuotaService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,12 @@ public void Configure(DbQuotaService options)
[Scope]
class DbQuotaService : IQuotaService
{
private Expression<Func<DbQuota, TenantQuota>> FromDbQuotaToTenantQuota { get; set; }
private Expression<Func<DbQuotaRow, TenantQuotaRow>> FromDbQuotaRowToTenantQuotaRow { get; set; }
private static Expression<Func<DbQuota, TenantQuota>> FromDbQuotaToTenantQuota { get; set; }
private static Expression<Func<DbQuotaRow, TenantQuotaRow>> FromDbQuotaRowToTenantQuotaRow { get; set; }
internal CoreDbContext CoreDbContext { get => LazyCoreDbContext.Value; }
internal Lazy<CoreDbContext> LazyCoreDbContext { get; set; }

public DbQuotaService()
static DbQuotaService()
{
FromDbQuotaToTenantQuota = r => new TenantQuota()
{
Expand All @@ -91,7 +91,7 @@ public DbQuotaService()
};
}

public DbQuotaService(DbContextManager<CoreDbContext> dbContextManager) : this()
public DbQuotaService(DbContextManager<CoreDbContext> dbContextManager)
{
LazyCoreDbContext = new Lazy<CoreDbContext>(() => dbContextManager.Value);
}
Expand Down
2 changes: 1 addition & 1 deletion common/ASC.Core.Common/EF/Context/BaseDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseLoggerFactory(LoggerFactory);
optionsBuilder.EnableSensitiveDataLogging();
Provider = GetProviderByConnectionString();
Provider = GetProviderByConnectionString();
switch (Provider)
{
case Provider.MySql:
Expand Down
4 changes: 3 additions & 1 deletion common/ASC.Core.Common/EF/Context/ConfigureDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,20 @@ namespace ASC.Core.Common.EF
public const string baseName = "default";
private EFLoggerFactory LoggerFactory { get; }
private ConfigurationExtension Configuration { get; }
private string MigrateAssembly { get; }

public ConfigureDbContext(EFLoggerFactory loggerFactory, ConfigurationExtension configuration)
{
LoggerFactory = loggerFactory;
Configuration = configuration;
MigrateAssembly = Configuration["testAssembly"];
}

public void Configure(string name, T context)
{
context.LoggerFactory = LoggerFactory;
context.ConnectionStringSettings = Configuration.GetConnectionStrings(name) ?? Configuration.GetConnectionStrings(baseName);
context.MigrateAssembly = Configuration["testAssembly"];
context.MigrateAssembly = MigrateAssembly;
}

public void Configure(T context)
Expand Down
2 changes: 1 addition & 1 deletion common/ASC.Data.Storage/PathUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ public string ResolveVirtualPath(string virtPath, bool addTrailingSlash = true)
virtPath = "";
}

if (virtPath.StartsWith("~") && !Uri.IsWellFormedUriString(virtPath, UriKind.Absolute))
if (virtPath.StartsWith('~') && !Uri.IsWellFormedUriString(virtPath, UriKind.Absolute))
{
var rootPath = "/";
if (!string.IsNullOrEmpty(WebHostEnvironment?.WebRootPath) && WebHostEnvironment?.WebRootPath.Length > 1)
Expand Down
57 changes: 14 additions & 43 deletions common/ASC.FederatedLogin/OAuth20Token.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,30 +26,37 @@

using System;
using System.Diagnostics;
using System.Globalization;
using System.Text;

using Newtonsoft.Json.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace ASC.FederatedLogin
{
[DebuggerDisplay("{AccessToken} (expired: {IsExpired})")]
public class OAuth20Token
{
[JsonPropertyName("access_token")]
public string AccessToken { get; set; }

[JsonPropertyName("refresh_token")]
public string RefreshToken { get; set; }

[JsonPropertyName("expires_in")]
[JsonNumberHandling(JsonNumberHandling.AllowReadingFromString)]
public long ExpiresIn { get; set; }

[JsonPropertyName("client_id")]
public string ClientID { get; set; }

[JsonPropertyName("client_secret")]
public string ClientSecret { get; set; }

[JsonPropertyName("redirect_uri")]
public string RedirectUri { get; set; }

[JsonPropertyName("timestamp")]
public DateTime Timestamp { get; set; }

[JsonIgnore]
public string OriginJson { get; set; }

public OAuth20Token()
Expand Down Expand Up @@ -92,55 +99,19 @@ public bool IsExpired
public static OAuth20Token FromJson(string json)
{
if (string.IsNullOrEmpty(json)) return null;
var parser = JObject.Parse(json);
if (parser == null) return null;

var accessToken = parser.Value<string>("access_token");

if (string.IsNullOrEmpty(accessToken))
return null;

var token = new OAuth20Token
{
AccessToken = accessToken,
RefreshToken = parser.Value<string>("refresh_token"),
ClientID = parser.Value<string>("client_id"),
ClientSecret = parser.Value<string>("client_secret"),
RedirectUri = parser.Value<string>("redirect_uri"),
OriginJson = json,
};

if (long.TryParse(parser.Value<string>("expires_in"), out var expiresIn))
token.ExpiresIn = expiresIn;

try
{
token.Timestamp =
!string.IsNullOrEmpty(parser.Value<string>("timestamp"))
? parser.Value<DateTime>("timestamp")
: DateTime.UtcNow;
return JsonSerializer.Deserialize<OAuth20Token>(json);
}
catch (Exception)
{
token.Timestamp = DateTime.MinValue;
return null;
}

return token;
}

public string ToJson()
{
var sb = new StringBuilder();
sb.Append("{");
sb.AppendFormat(" \"access_token\": \"{0}\"", AccessToken);
sb.AppendFormat(", \"refresh_token\": \"{0}\"", RefreshToken);
sb.AppendFormat(", \"expires_in\": \"{0}\"", ExpiresIn);
sb.AppendFormat(", \"client_id\": \"{0}\"", ClientID);
sb.AppendFormat(", \"client_secret\": \"{0}\"", ClientSecret);
sb.AppendFormat(", \"redirect_uri\": \"{0}\"", RedirectUri);
sb.AppendFormat(", \"timestamp\": \"{0}\"", Timestamp.ToString("o", new CultureInfo("en-US")));
sb.Append("}");
return sb.ToString();
return JsonSerializer.Serialize(this);
}

public override string ToString()
Expand Down
5 changes: 2 additions & 3 deletions common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@
using ASC.Common;
using ASC.Common.Caching;
using ASC.Common.Logging;
using ASC.Common.Utils;
using ASC.Core;
using ASC.Core.Common.EF;
using ASC.Core.Common.EF.Context;
Expand Down Expand Up @@ -103,14 +102,14 @@ public BaseIndexer(
DbContextManager<WebstudioDbContext> dbContextManager,
TenantManager tenantManager,
BaseIndexerHelper baseIndexerHelper,
ConfigurationExtension configurationExtension,
SettingsHelper settingsHelper,
IServiceProvider serviceProvider)
{
Client = client;
Log = log.CurrentValue;
TenantManager = tenantManager;
BaseIndexerHelper = baseIndexerHelper;
Settings = Settings.GetInstance(configurationExtension);
Settings = settingsHelper.Settings;
ServiceProvider = serviceProvider;
LazyWebstudioDbContext = new Lazy<WebstudioDbContext>(() => dbContextManager.Value);
}
Expand Down
5 changes: 2 additions & 3 deletions common/services/ASC.ElasticSearch/Engine/Client.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@

using ASC.Common;
using ASC.Common.Logging;
using ASC.Common.Utils;
using ASC.Core;
using ASC.Core.Tenants;
using ASC.ElasticSearch.Service;
Expand All @@ -54,11 +53,11 @@ public class Client
private CoreConfiguration CoreConfiguration { get; }
private Settings Settings { get; }

public Client(IOptionsMonitor<ILog> option, CoreConfiguration coreConfiguration, ConfigurationExtension configurationExtension)
public Client(IOptionsMonitor<ILog> option, CoreConfiguration coreConfiguration, SettingsHelper settingsHelper)
{
Log = option.Get("ASC.Indexer");
CoreConfiguration = coreConfiguration;
Settings = Settings.GetInstance(configurationExtension);
Settings = settingsHelper.Settings;
}

public ElasticClient Instance
Expand Down
5 changes: 2 additions & 3 deletions common/services/ASC.ElasticSearch/Service/Launcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@
using ASC.Common;
using ASC.Common.Caching;
using ASC.Common.Logging;
using ASC.Common.Utils;
using ASC.ElasticSearch.Service;

using Microsoft.Extensions.DependencyInjection;
Expand All @@ -58,14 +57,14 @@ public ServiceLauncher(
ICacheNotify<AscCacheItem> notify,
ICacheNotify<IndexAction> indexNotify,
IServiceProvider serviceProvider,
ConfigurationExtension configurationExtension)
SettingsHelper settingsHelper)
{
Log = options.Get("ASC.Indexer");
Notify = notify;
IndexNotify = indexNotify;
ServiceProvider = serviceProvider;
CancellationTokenSource = new CancellationTokenSource();
var settings = Settings.GetInstance(configurationExtension);
var settings = settingsHelper.Settings;
Period = TimeSpan.FromMinutes(settings.Period.Value);
}

Expand Down
34 changes: 20 additions & 14 deletions common/services/ASC.ElasticSearch/Service/Settings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,23 +30,29 @@
namespace ASC.ElasticSearch.Service
{
[Singletone]
public class Settings
{
public static Settings GetInstance(ConfigurationExtension configuration)
public class SettingsHelper
{
public Settings Settings { get; set; }
public SettingsHelper(ConfigurationExtension configuration)
{
var result = new Settings();
var cfg = configuration.GetSetting<Settings>("elastic");
result.Scheme = cfg.Scheme ?? "http";
result.Host = cfg.Host ?? "localhost";
result.Port = cfg.Port ?? 9200;
result.Period = cfg.Period ?? 1;
result.MaxContentLength = cfg.MaxContentLength ?? 100 * 1024 * 1024L;
result.MaxFileSize = cfg.MaxFileSize ?? 10 * 1024 * 1024L;
result.Threads = cfg.Threads ?? 1;
result.HttpCompression = cfg.HttpCompression ?? true;
return result;

Settings = new Settings
{
Scheme = cfg.Scheme ?? "http",
Host = cfg.Host ?? "localhost",
Port = cfg.Port ?? 9200,
Period = cfg.Period ?? 1,
MaxContentLength = cfg.MaxContentLength ?? 100 * 1024 * 1024L,
MaxFileSize = cfg.MaxFileSize ?? 10 * 1024 * 1024L,
Threads = cfg.Threads ?? 1,
HttpCompression = cfg.HttpCompression ?? true
};
}

}

public class Settings
{
public string Host { get; set; }

public int? Port { get; set; }
Expand Down
7 changes: 3 additions & 4 deletions config/nlog.config
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,16 @@

<extensions>
<add assembly="NLog.Web.AspNetCore"/>
<add assembly="ASC.Common"/>
</extensions>

<variable name="dir" value="..\Logs\"/>
<variable name="name" value="web"/>
<conversionPattern value=""/>

<targets async="true">
<default-target-parameters type="SelfCleaning" encoding="utf-8" archiveNumbering="DateAndSequence" archiveEvery="Day" enableArchiveFileCompression="true" archiveAboveSize="52428800" keepFileOpen="true" archiveDateFormat="MM-dd" layout="${date:format=yyyy-MM-dd HH\:mm\:ss,fff} ${level:uppercase=true} [${threadid}] ${logger} - ${message} ${exception:format=ToString}"/>
<target name="web" type="SelfCleaning" fileName="${var:dir}${var:name}.log" />
<target name="sql" type="SelfCleaning" fileName="${var:dir}${var:name}.sql.log" layout="${date:universalTime=true:format=yyyy-MM-dd HH\:mm\:ss,fff}|${threadid}|${event-properties:item=elapsed}|${message}|${replace:inner=${event-properties:item=commandText}:searchFor=\\r\\n|\\s:replaceWith= :regex=true}|${event-properties:item=parameters}"/>
<default-target-parameters type="File" encoding="utf-8" archiveNumbering="DateAndSequence" archiveEvery="Day" enableArchiveFileCompression="true" archiveAboveSize="52428800" keepFileOpen="true" archiveDateFormat="MM-dd" layout="${date:format=yyyy-MM-dd HH\:mm\:ss,fff} ${level:uppercase=true} [${threadid}] ${logger} - ${message} ${exception:format=ToString}"/>
<target name="web" type="File" fileName="${var:dir}${var:name}.log" />
<target name="sql" type="File" fileName="${var:dir}${var:name}.sql.log" layout="${date:universalTime=true:format=yyyy-MM-dd HH\:mm\:ss,fff}|${threadid}|${event-properties:item=elapsed}|${message}|${replace:inner=${event-properties:item=commandText}:searchFor=\\r\\n|\\s:replaceWith= :regex=true}|${event-properties:item=parameters}"/>
<target name="ownFile-web" type="File" fileName="${var:dir}${var:name}.asp.log" layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
</targets>

Expand Down
10 changes: 6 additions & 4 deletions products/ASC.Files/Core/Core/Dao/TeamlabDao/AbstractDao.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ protected AbstractDao(
CoreConfiguration coreConfiguration,
SettingsManager settingsManager,
AuthContext authContext,
IServiceProvider serviceProvider,
IServiceProvider serviceProvider,
ICache cache)
{
this.cache = cache;
Expand Down Expand Up @@ -128,7 +128,7 @@ protected void GetRecalculateFilesCountUpdate(int folderId)
.Join(FilesDbContext.Tree, a => a.FolderId, b => b.FolderId, (file, tree) => new { file, tree })
.Where(r => r.file.TenantId == f.TenantId)
.Where(r => r.tree.ParentId == f.Id)
.Select(r=> r.file.Id)
.Select(r => r.file.Id)
.Distinct()
.Count();

Expand Down Expand Up @@ -191,7 +191,7 @@ protected object MappingID(object id)

internal static IQueryable<T> BuildSearch<T>(IQueryable<T> query, string text, SearhTypeEnum searhTypeEnum) where T : IDbSearch
{
var lowerText = text.ToLower().Trim().Replace("%", "\\%").Replace("_", "\\_");
var lowerText = GetSearchText(text);

return searhTypeEnum switch
{
Expand All @@ -200,7 +200,9 @@ internal static IQueryable<T> BuildSearch<T>(IQueryable<T> query, string text, S
SearhTypeEnum.Any => query.Where(r => r.Title.ToLower().Contains(lowerText)),
_ => query,
};
}
}

internal static string GetSearchText(string text) => (text ?? "").ToLower().Trim().Replace("%", "\\%").Replace("_", "\\_");

internal enum SearhTypeEnum
{
Expand Down
Loading