Merge pull request #30 from ONLYOFFICE/feature/elastic

Feature/elastic
This commit is contained in:
Nikolay Rechkin 2020-02-27 15:52:34 +03:00 committed by GitHub
commit 7d21902c86
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
465 changed files with 59813 additions and 2532 deletions

View File

@ -40,10 +40,14 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ASC.Notify", "common\servic
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ASC.Studio.Notify", "common\services\ASC.Studio.Notify\ASC.Studio.Notify.csproj", "{E3567AB9-0926-444D-A0D0-A369D5890EAA}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ASC.Textile", "common\ASC.Textile\ASC.Textile.csproj", "{C8F410B4-B83B-47B9-9ECD-07590A8750A7}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ASC.Textile", "common\ASC.Textile\ASC.Textile.csproj", "{C8F410B4-B83B-47B9-9ECD-07590A8750A7}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ASC.Notify.Textile", "common\ASC.Notify.Textile\ASC.Notify.Textile.csproj", "{DB50E2EF-B4D8-493A-8568-29CAC0DF9062}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ASC.ElasticSearch", "common\services\ASC.ElasticSearch\ASC.ElasticSearch.csproj", "{AE1A0E06-6CD4-4E1D-8209-22BBBD6D5652}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ASC.Files", "products\ASC.Files\Server\ASC.Files.csproj", "{77BA2F61-6155-4283-BB39-F8E42F46A0B0}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -126,6 +130,14 @@ Global
{DB50E2EF-B4D8-493A-8568-29CAC0DF9062}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DB50E2EF-B4D8-493A-8568-29CAC0DF9062}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DB50E2EF-B4D8-493A-8568-29CAC0DF9062}.Release|Any CPU.Build.0 = Release|Any CPU
{AE1A0E06-6CD4-4E1D-8209-22BBBD6D5652}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AE1A0E06-6CD4-4E1D-8209-22BBBD6D5652}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AE1A0E06-6CD4-4E1D-8209-22BBBD6D5652}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AE1A0E06-6CD4-4E1D-8209-22BBBD6D5652}.Release|Any CPU.Build.0 = Release|Any CPU
{77BA2F61-6155-4283-BB39-F8E42F46A0B0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{77BA2F61-6155-4283-BB39-F8E42F46A0B0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{77BA2F61-6155-4283-BB39-F8E42F46A0B0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{77BA2F61-6155-4283-BB39-F8E42F46A0B0}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -15,6 +15,10 @@
{
"name": "ASC.People.Client"
"path": "./products/ASC.People/Client"
},
{
"name": "ASC.Files.Client"
"path": "./products/ASC.Files/Client"
}
],
"settings": {}

View File

@ -18,6 +18,9 @@ call build\scripts\client.sh
echo "ASC.Web.People.Client"
call build\scripts\people.sh
echo "ASC.Web.Files.Client"
call build\scripts\files.sh
echo "ASC.Web.sln"
call dotnet build ASC.Web.sln /fl1 /flp1:LogFile=build/ASC.Web.log;Verbosity=Normal

View File

@ -29,6 +29,11 @@ call yarn link "asc-web-components" --cwd products/ASC.People/Client
call yarn link "asc-web-common" --cwd products/ASC.People/Client
call yarn install --cwd products/ASC.People/Client > build\ASC.Web.People.Client.log
echo "ASC.Web.Files.Client"
call yarn link "asc-web-components" --cwd products/ASC.Files/Client
call yarn link "asc-web-common" --cwd products/ASC.Files/Client
call yarn install --cwd products/ASC.Files/Client > build\ASC.Web.Files.Client.log
echo "ASC.Web.sln"
call dotnet build ASC.Web.sln /fl1 /flp1:LogFile=build/ASC.Web.log;Verbosity=Normal

2
build/run/FileClient.bat Normal file
View File

@ -0,0 +1,2 @@
echo "RUN ASC.Web.Files"
call set BROWSER=none&&npm start --prefix ../../products/ASC.Files/Client

2
build/run/FileServer.bat Normal file
View File

@ -0,0 +1,2 @@
echo "RUN ASC.Files"
call dotnet run --project ..\..\products\ASC.Files\Server\ASC.Files.csproj --no-build --$STORAGE_ROOT=..\..\..\Data --log__dir=..\..\..\Logs --log__name=files

3
build/scripts/files.sh Normal file
View File

@ -0,0 +1,3 @@
yarn link "asc-web-components" --cwd products/ASC.Files/Client
yarn link "asc-web-common" --cwd products/ASC.Files/Client
yarn install --cwd products/ASC.Files/Client --frozen-lockfile

View File

@ -6,11 +6,12 @@ using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using ASC.Common;
using ASC.Core;
using ASC.Security.Cryptography;
using ASC.Web.Studio.Core;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
@ -109,7 +110,7 @@ namespace ASC.Api.Core.Auth
public static class ConfirmAuthHandlerExtension
{
public static IServiceCollection AddConfirmAuthHandler(this IServiceCollection services)
public static DIHelper AddConfirmAuthHandler(this DIHelper services)
{
return services
.AddSecurityContextService()

View File

@ -2,9 +2,11 @@
using System.Security.Authentication;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using ASC.Common;
using ASC.Core;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
@ -39,7 +41,7 @@ namespace ASC.Api.Core.Auth
public static class CookieAuthHandlerExtension
{
public static IServiceCollection AddCookieAuthHandler(this IServiceCollection services)
public static DIHelper AddCookieAuthHandler(this DIHelper services)
{
return services.AddSecurityContextService();
}

View File

@ -27,11 +27,12 @@
using System;
using System.Linq;
using System.Security.Claims;
using ASC.Common;
using ASC.Core;
using ASC.Core.Tenants;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace ASC.Api.Core
{
@ -270,13 +271,12 @@ namespace ASC.Api.Core
public static class ApiContextConfigExtension
{
public static IServiceCollection AddApiContextService(this IServiceCollection services)
public static DIHelper AddApiContextService(this DIHelper services)
{
services.TryAddScoped<ApiContext>();
return services
.AddTenantManagerService()
.AddHttpContextAccessor()
.AddSecurityContextService();
}
}

View File

@ -28,8 +28,11 @@ using System;
using System.ComponentModel;
using System.Globalization;
using System.Runtime.Serialization;
using ASC.Common;
using ASC.Common.Utils;
using ASC.Core;
using Newtonsoft.Json;
namespace ASC.Api.Core
@ -360,4 +363,29 @@ namespace ASC.Api.Core
return typeof(ApiDateTime).IsAssignableFrom(objectType);
}
}
public class ApiDateTimeHelper
{
public TenantManager TenantManager { get; }
public TimeZoneConverter TimeZoneConverter { get; }
public ApiDateTimeHelper(TenantManager tenantManager, TimeZoneConverter timeZoneConverter)
{
TenantManager = tenantManager;
TimeZoneConverter = timeZoneConverter;
}
public ApiDateTime Get(DateTime? from) => ApiDateTime.FromDate(TenantManager, TimeZoneConverter, from);
}
public static class ApiDateTimeHelperExtension
{
public static DIHelper AddApiDateTimeHelper(this DIHelper services)
{
services.TryAddScoped<ApiDateTimeHelper>();
return services
.AddTenantManagerService();
}
}
}

View File

@ -1,10 +1,12 @@
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using ASC.Common;
using ASC.Core;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace ASC.Api.Core.Middleware
{
@ -50,7 +52,7 @@ namespace ASC.Api.Core.Middleware
return builder.UseMiddleware<CultureMiddleware>();
}
public static IServiceCollection AddCultureMiddleware(this IServiceCollection services)
public static DIHelper AddCultureMiddleware(this DIHelper services)
{
return services
.AddUserManagerService()

View File

@ -1,11 +1,13 @@
using System.Net;
using ASC.Common;
using ASC.Common.Logging;
using ASC.Core;
using ASC.Core.Common.Settings;
using ASC.IPSecurity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace ASC.Api.Core.Middleware
@ -45,7 +47,7 @@ namespace ASC.Api.Core.Middleware
public static class IpSecurityFilterExtension
{
public static IServiceCollection AddIpSecurityFilter(this IServiceCollection services)
public static DIHelper AddIpSecurityFilter(this DIHelper services)
{
return services
.AddSettingsManagerService()

View File

@ -1,13 +1,15 @@
using System.Linq;
using System.Net;
using System.Web;
using ASC.Common;
using ASC.Common.Logging;
using ASC.Web.Api.Routing;
using ASC.Web.Studio.Utility;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace ASC.Api.Core.Middleware
@ -50,7 +52,7 @@ namespace ASC.Api.Core.Middleware
public static class PaymentFilterExtension
{
public static IServiceCollection AddPaymentFilter(this IServiceCollection services)
public static DIHelper AddPaymentFilter(this DIHelper services)
{
return services
.AddTenantExtraService();

View File

@ -2,15 +2,17 @@
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using ASC.Common;
using ASC.Common.Logging;
using ASC.Common.Notify.Engine;
using ASC.Core;
using ASC.Web.Core;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace ASC.Api.Core.Middleware
@ -123,7 +125,7 @@ namespace ASC.Api.Core.Middleware
public static class ProductSecurityFilterExtension
{
public static IServiceCollection AddProductSecurityFilter(this IServiceCollection services)
public static DIHelper AddProductSecurityFilter(this DIHelper services)
{
return services
.AddUserManagerService()

View File

@ -1,10 +1,12 @@
using System.Net;
using ASC.Common;
using ASC.Common.Logging;
using ASC.Core;
using ASC.Core.Tenants;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace ASC.Api.Core.Middleware
@ -46,7 +48,7 @@ namespace ASC.Api.Core.Middleware
public static class TenantStatusFilterExtension
{
public static IServiceCollection AddTenantStatusFilter(this IServiceCollection services)
public static DIHelper AddTenantStatusFilter(this DIHelper services)
{
return services
.AddTenantManagerService();

View File

@ -26,12 +26,13 @@
using System;
using System.Runtime.Serialization;
using ASC.Api.Core;
using ASC.Common;
using ASC.Core;
using ASC.Core.Users;
using ASC.Web.Core.Users;
using ASC.Web.Studio.Utility;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace ASC.Web.Api.Models
{
@ -67,18 +68,24 @@ namespace ASC.Web.Api.Models
public class EmployeeWraperHelper
{
public UserInfo UserInfo { get; set; }
public ApiContext HttpContext { get; }
public DisplayUserSettingsHelper DisplayUserSettingsHelper { get; }
public UserPhotoManager UserPhotoManager { get; }
public CommonLinkUtility CommonLinkUtility { get; }
private ApiContext HttpContext { get; }
private DisplayUserSettingsHelper DisplayUserSettingsHelper { get; }
protected UserPhotoManager UserPhotoManager { get; }
private CommonLinkUtility CommonLinkUtility { get; }
protected UserManager UserManager { get; }
public EmployeeWraperHelper(ApiContext httpContext, DisplayUserSettingsHelper displayUserSettingsHelper, UserPhotoManager userPhotoManager, CommonLinkUtility commonLinkUtility)
public EmployeeWraperHelper(
ApiContext httpContext,
DisplayUserSettingsHelper displayUserSettingsHelper,
UserPhotoManager userPhotoManager,
CommonLinkUtility commonLinkUtility,
UserManager userManager)
{
HttpContext = httpContext;
DisplayUserSettingsHelper = displayUserSettingsHelper;
UserPhotoManager = userPhotoManager;
CommonLinkUtility = commonLinkUtility;
UserManager = userManager;
}
public EmployeeWraper Get(UserInfo userInfo)
@ -86,6 +93,18 @@ namespace ASC.Web.Api.Models
return Init(new EmployeeWraper(), userInfo);
}
public EmployeeWraper Get(Guid userId)
{
try
{
return Get(UserManager.GetUsers(userId));
}
catch (Exception)
{
return Get(Constants.LostUser);
}
}
protected EmployeeWraper Init(EmployeeWraper result, UserInfo userInfo)
{
result.Id = userInfo.ID;
@ -114,7 +133,7 @@ namespace ASC.Web.Api.Models
public static class EmployeeWraperExtension
{
public static IServiceCollection AddEmployeeWraper(this IServiceCollection services)
public static DIHelper AddEmployeeWraper(this DIHelper services)
{
services.TryAddScoped<EmployeeWraperHelper>();

View File

@ -28,15 +28,14 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using ASC.Api.Core;
using ASC.Common.Utils;
using ASC.Common;
using ASC.Core;
using ASC.Core.Users;
using ASC.Web.Core;
using ASC.Web.Core.Users;
using ASC.Web.Studio.Utility;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace ASC.Web.Api.Models
{
@ -160,28 +159,23 @@ namespace ASC.Web.Api.Models
public class EmployeeWraperFullHelper : EmployeeWraperHelper
{
public ApiContext Context { get; }
public UserManager UserManager { get; }
public WebItemSecurity WebItemSecurity { get; }
public TenantManager TenantManager { get; }
public TimeZoneConverter TimeZoneConverter { get; }
private ApiContext Context { get; }
private WebItemSecurity WebItemSecurity { get; }
private ApiDateTimeHelper ApiDateTimeHelper { get; }
public EmployeeWraperFullHelper(
ApiContext context,
UserManager userManager,
UserPhotoManager userPhotoManager,
WebItemSecurity webItemSecurity,
TenantManager tenantManager,
CommonLinkUtility commonLinkUtility,
DisplayUserSettingsHelper displayUserSettingsHelper,
TimeZoneConverter timeZoneConverter)
: base(context, displayUserSettingsHelper, userPhotoManager, commonLinkUtility)
ApiDateTimeHelper apiDateTimeHelper)
: base(context, displayUserSettingsHelper, userPhotoManager, commonLinkUtility, userManager)
{
Context = context;
UserManager = userManager;
WebItemSecurity = webItemSecurity;
TenantManager = tenantManager;
TimeZoneConverter = timeZoneConverter;
ApiDateTimeHelper = apiDateTimeHelper;
}
public EmployeeWraperFull GetFull(UserInfo userInfo)
@ -191,11 +185,11 @@ namespace ASC.Web.Api.Models
UserName = userInfo.UserName,
FirstName = userInfo.FirstName,
LastName = userInfo.LastName,
Birthday = ApiDateTime.FromDate(TenantManager, TimeZoneConverter, userInfo.BirthDate),
Birthday = ApiDateTimeHelper.Get(userInfo.BirthDate),
Status = userInfo.Status,
ActivationStatus = userInfo.ActivationStatus & ~EmployeeActivationStatus.AutoGenerated,
Terminated = ApiDateTime.FromDate(TenantManager, TimeZoneConverter, userInfo.TerminatedDate),
WorkFrom = ApiDateTime.FromDate(TenantManager, TimeZoneConverter, userInfo.WorkFromDate),
Terminated = ApiDateTimeHelper.Get(userInfo.TerminatedDate),
WorkFrom = ApiDateTimeHelper.Get(userInfo.WorkFromDate),
Email = userInfo.Email,
IsVisitor = userInfo.IsVisitor(UserManager),
IsAdmin = userInfo.IsAdmin(UserManager),
@ -303,7 +297,7 @@ namespace ASC.Web.Api.Models
public static class EmployeeWraperFullExtension
{
public static IServiceCollection AddEmployeeWraperFull(this IServiceCollection services)
public static DIHelper AddEmployeeWraperFull(this DIHelper services)
{
services.TryAddScoped<EmployeeWraperFullHelper>();
@ -311,7 +305,8 @@ namespace ASC.Web.Api.Models
.AddTenantManagerService()
.AddWebItemSecurity()
.AddUserManagerService()
.AddEmployeeWraper();
.AddEmployeeWraper()
.AddApiDateTimeHelper();
}
}
}

View File

@ -3,12 +3,17 @@ using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ASC.Common.Logging;
using ASC.Common.Utils;
using Confluent.Kafka;
using Google.Protobuf;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
namespace ASC.Common.Caching
@ -235,4 +240,14 @@ namespace ASC.Common.Caching
return $"{typeof(T).Name}{cacheNotifyAction}";
}
}
public static class KafkaExtention
{
public static DIHelper AddKafkaService(this DIHelper services)
{
services.TryAddSingleton(typeof(ICacheNotify<>), typeof(KafkaCache<>));
return services;
}
}
}

View File

@ -0,0 +1,169 @@
using System;
using System.Collections.Generic;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace ASC.Common
{
public class DIHelper
{
public List<string> Singleton { get; set; }
public List<string> Scoped { get; set; }
public List<string> Transient { get; set; }
public List<string> Configured { get; set; }
public IServiceCollection ServiceCollection { get; }
public DIHelper(IServiceCollection serviceCollection)
{
Singleton = new List<string>();
Scoped = new List<string>();
Transient = new List<string>();
Configured = new List<string>();
ServiceCollection = serviceCollection;
}
public DIHelper TryAddScoped<TService>() where TService : class
{
var serviceName = $"{typeof(TService)}";
if (!Scoped.Contains(serviceName))
{
Scoped.Add(serviceName);
ServiceCollection.TryAddScoped<TService>();
}
return this;
}
public DIHelper TryAddScoped<TService, TImplementation>() where TService : class where TImplementation : class, TService
{
var serviceName = $"{typeof(TService)}{typeof(TImplementation)}";
if (!Scoped.Contains(serviceName))
{
Scoped.Add(serviceName);
ServiceCollection.TryAddScoped<TService, TImplementation>();
}
return this;
}
public DIHelper TryAddScoped<TService, TImplementation>(TService tservice, TImplementation tImplementation) where TService : Type where TImplementation : Type
{
var serviceName = $"{tservice}{tImplementation}";
if (!Scoped.Contains(serviceName))
{
Scoped.Add(serviceName);
ServiceCollection.TryAddScoped(tservice, tImplementation);
}
return this;
}
public DIHelper TryAddSingleton<TService>() where TService : class
{
var serviceName = $"{typeof(TService)}";
if (!Singleton.Contains(serviceName))
{
Singleton.Add(serviceName);
ServiceCollection.TryAddSingleton<TService>();
}
return this;
}
public DIHelper TryAddSingleton<TService>(Func<IServiceProvider, TService> implementationFactory) where TService : class
{
var serviceName = $"{typeof(TService)}";
if (!Singleton.Contains(serviceName))
{
Singleton.Add(serviceName);
ServiceCollection.TryAddSingleton(implementationFactory);
}
return this;
}
public DIHelper TryAddSingleton<TService>(TService t) where TService : class
{
var serviceName = $"{typeof(TService)}";
if (!Singleton.Contains(serviceName))
{
Singleton.Add(serviceName);
ServiceCollection.TryAddSingleton(t);
}
return this;
}
public DIHelper TryAddSingleton<TService, TImplementation>() where TService : class where TImplementation : class, TService
{
var serviceName = $"{typeof(TService)}{typeof(TImplementation)}";
if (!Singleton.Contains(serviceName))
{
Singleton.Add(serviceName);
ServiceCollection.TryAddSingleton<TService, TImplementation>();
}
return this;
}
public DIHelper AddSingleton<TService, TImplementation>() where TService : class where TImplementation : class, TService
{
var serviceName = $"{typeof(TService)}{typeof(TImplementation)}";
if (!Singleton.Contains(serviceName))
{
Singleton.Add(serviceName);
ServiceCollection.AddSingleton<TService, TImplementation>();
}
return this;
}
public DIHelper TryAddSingleton<TService, TImplementation>(TService tservice, TImplementation tImplementation) where TService : Type where TImplementation : Type
{
var serviceName = $"{tservice}{tImplementation}";
if (!Singleton.Contains(serviceName))
{
Singleton.Add(serviceName);
ServiceCollection.TryAddSingleton(tservice, tImplementation);
}
return this;
}
public DIHelper TryAddTransient<TService>() where TService : class
{
var serviceName = $"{typeof(TService)}";
if (!Transient.Contains(serviceName))
{
Transient.Add(serviceName);
ServiceCollection.TryAddTransient<TService>();
}
return this;
}
public DIHelper Configure<TOptions>(Action<TOptions> configureOptions) where TOptions : class
{
var serviceName = $"{typeof(TOptions)}";
if (!Configured.Contains(serviceName))
{
Configured.Add(serviceName);
ServiceCollection.Configure(configureOptions);
}
return this;
}
public DIHelper Configure<TOptions>(string name, Action<TOptions> configureOptions) where TOptions : class
{
var serviceName = $"{typeof(TOptions)}{name}";
if (!Configured.Contains(serviceName))
{
Configured.Add(serviceName);
ServiceCollection.Configure(name, configureOptions);
}
return this;
}
}
}

View File

@ -107,7 +107,9 @@ namespace ASC.Common.DependencyInjection
AssemblyLoadContext.Default.Resolving += (c, n) =>
{
var path = GetFullPath(n.Name);
return c.LoadFromAssemblyPath(Path.Combine(Path.GetDirectoryName(path), $"{n.Name}.dll"));
return path != null ?
c.LoadFromAssemblyPath(Path.Combine(Path.GetDirectoryName(path), $"{n.Name}.dll")) :
null;
};
}
}

View File

@ -119,7 +119,7 @@ namespace ASC.Common.Logging
public static class LoggerExtension
{
public static IServiceCollection AddLoggerService(this IServiceCollection services)
public static DIHelper AddLoggerService(this DIHelper services)
{
services.TryAddScoped<EFLoggerFactory>();
services.TryAddScoped<EFLoggerProvider>();

View File

@ -26,15 +26,18 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using ASC.Common.Utils;
using System.IO;
using System.Reflection;
using ASC.Common.Utils;
using log4net.Config;
using log4net.Core;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using log4net.Core;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using NLog;
namespace ASC.Common.Logging
@ -51,7 +54,7 @@ namespace ASC.Common.Logging
void Trace(object message);
void TraceFormat(string message, object arg0);
void DebugWithProps(string message, params KeyValuePair<string, object>[] props);
void DebugWithProps(string message, params KeyValuePair<string, object>[] props);
void DebugWithProps(string message, KeyValuePair<string, object> prop1, KeyValuePair<string, object> prop2, KeyValuePair<string, object> prop3);
void Debug(object message);
void Debug(object message, Exception exception);
@ -94,7 +97,7 @@ namespace ASC.Common.Logging
void FatalFormat(string format, object arg0, object arg1, object arg2);
void FatalFormat(IFormatProvider provider, string format, params object[] args);
string LogDirectory { get; }
string LogDirectory { get; }
string Name { get; set; }
}
@ -330,74 +333,74 @@ namespace ASC.Common.Logging
public void FatalFormat(IFormatProvider provider, string format, params object[] args)
{
if (IsFatalEnabled) loger.FatalFormat(provider, format, args);
}
public void DebugWithProps(string message, KeyValuePair<string, object> prop1, KeyValuePair<string, object> prop2, KeyValuePair<string, object> prop3)
{
if (!IsDebugEnabled) return;
AddProp(prop1);
AddProp(prop2);
AddProp(prop3);
loger.Debug(message);
static void AddProp(KeyValuePair<string, object> p)
{
log4net.ThreadContext.Properties[p.Key] = p.Value;
}
}
}
public void DebugWithProps(string message, KeyValuePair<string, object> prop1, KeyValuePair<string, object> prop2, KeyValuePair<string, object> prop3)
{
if (!IsDebugEnabled) return;
AddProp(prop1);
AddProp(prop2);
AddProp(prop3);
loger.Debug(message);
static void AddProp(KeyValuePair<string, object> p)
{
log4net.ThreadContext.Properties[p.Key] = p.Value;
}
}
public string LogDirectory
{
get
{
return log4net.GlobalContext.Properties["LogDirectory"].ToString();
}
}
public string Name
{
get;
set;
}
}
public string Name
{
get;
set;
}
}
public class NLogSettings
{
public string Name { get; set; }
public string Dir { get; set; }
}
public class ConfigureLogNLog : IConfigureOptions<LogNLog>
{
public ConfigureLogNLog(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void Configure(LogNLog options)
{
LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(Path.Combine(Configuration["pathToConf"], "nlog.config"), true);
var settings = Configuration.GetSetting<NLogSettings>("log");
if (!string.IsNullOrEmpty(settings.Name))
{
LogManager.Configuration.Variables["name"] = settings.Name;
}
if (!string.IsNullOrEmpty(settings.Dir))
{
LogManager.Configuration.Variables["dir"] = settings.Dir.TrimEnd('/').TrimEnd('\\') + Path.DirectorySeparatorChar;
public class NLogSettings
{
public string Name { get; set; }
public string Dir { get; set; }
}
public class ConfigureLogNLog : IConfigureOptions<LogNLog>
{
public ConfigureLogNLog(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void Configure(LogNLog options)
{
LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(Path.Combine(Configuration["pathToConf"], "nlog.config"), true);
var settings = Configuration.GetSetting<NLogSettings>("log");
if (!string.IsNullOrEmpty(settings.Name))
{
LogManager.Configuration.Variables["name"] = settings.Name;
}
NLog.Targets.Target.Register<SelfCleaningTarget>("SelfCleaning");
}
}
if (!string.IsNullOrEmpty(settings.Dir))
{
LogManager.Configuration.Variables["dir"] = settings.Dir.TrimEnd('/').TrimEnd('\\') + Path.DirectorySeparatorChar;
}
NLog.Targets.Target.Register<SelfCleaningTarget>("SelfCleaning");
}
}
public class LogNLog : ILog
{
private NLog.ILogger loger;
@ -429,7 +432,7 @@ namespace ASC.Common.Logging
public bool IsFatalEnabled { get; private set; }
public bool IsTraceEnabled { get; private set; }
public bool IsTraceEnabled { get; private set; }
public void Trace(object message)
{
@ -493,23 +496,23 @@ namespace ASC.Common.Logging
{
if (!IsDebugEnabled) return;
var theEvent = new LogEventInfo
{
Message = message,
LoggerName = Name,
Level = LogLevel.Debug
var theEvent = new LogEventInfo
{
Message = message,
LoggerName = Name,
Level = LogLevel.Debug
};
AddProp(prop1);
AddProp(prop2);
AddProp(prop3);
Loger.Log(theEvent);
void AddProp(KeyValuePair<string, object> p)
{
theEvent.Properties[p.Key] = p.Value;
AddProp(prop1);
AddProp(prop2);
AddProp(prop3);
Loger.Log(theEvent);
void AddProp(KeyValuePair<string, object> p)
{
theEvent.Properties[p.Key] = p.Value;
}
}
@ -670,7 +673,7 @@ namespace ASC.Common.Logging
name = value;
Loger = NLog.LogManager.GetLogger(name);
}
}
}
}
public class NullLog : ILog
@ -832,60 +835,60 @@ namespace ASC.Common.Logging
public void FatalFormat(IFormatProvider provider, string format, params object[] args)
{
}
public void DebugWithProps(string message, KeyValuePair<string, object> prop1, KeyValuePair<string, object> prop2, KeyValuePair<string, object> prop3)
{
}
}
public void DebugWithProps(string message, KeyValuePair<string, object> prop1, KeyValuePair<string, object> prop2, KeyValuePair<string, object> prop3)
{
}
public string LogDirectory { get { return ""; } }
public string Name { get; set; }
}
public class LogManager<T> : OptionsMonitor<T> where T : class, ILog, new()
{
public LogManager(IOptionsFactory<T> factory, IEnumerable<IOptionsChangeTokenSource<T>> sources, IOptionsMonitorCache<T> cache) : base(factory, sources, cache)
{
}
public override T Get(string name)
{
var log = base.Get(name);
if (string.IsNullOrEmpty(log?.Name))
{
log = CurrentValue;
}
return log;
}
}
public class LogManager<T> : OptionsMonitor<T> where T : class, ILog, new()
{
public LogManager(IOptionsFactory<T> factory, IEnumerable<IOptionsChangeTokenSource<T>> sources, IOptionsMonitorCache<T> cache) : base(factory, sources, cache)
{
}
public override T Get(string name)
{
var log = base.Get(name);
if (string.IsNullOrEmpty(log?.Name))
{
log = CurrentValue;
}
return log;
}
}
public static class StudioNotifyHelperExtension
{
public static IServiceCollection AddLogManager<T>(this IServiceCollection services, params string[] additionalLoggers) where T : class, ILog, new()
{
const string baseName = "ASC";
var baseSqlName = $"{baseName}.SQL";
services.Configure<T>(r => r.Name = baseName);
services.Configure<T>(baseName, r => r.Name = baseName);
services.Configure<T>(baseSqlName, r => r.Name = baseSqlName);
foreach (var l in additionalLoggers)
{
services.Configure<T>(l, r => r.Name = l);
}
services.TryAddSingleton(typeof(IOptionsMonitor<ILog>), typeof(LogManager<T>));
return services;
}
public static IServiceCollection AddNLogManager(this IServiceCollection services, params string[] additionalLoggers)
{
services.TryAddSingleton<IConfigureOptions<LogNLog>, ConfigureLogNLog>();
return services.AddLogManager<LogNLog>(additionalLoggers);
}
}
public static DIHelper AddLogManager<T>(this DIHelper services, params string[] additionalLoggers) where T : class, ILog, new()
{
const string baseName = "ASC";
var baseSqlName = $"{baseName}.SQL";
services.Configure<T>(r => r.Name = baseName);
services.Configure<T>(baseName, r => r.Name = baseName);
services.Configure<T>(baseSqlName, r => r.Name = baseSqlName);
foreach (var l in additionalLoggers)
{
services.Configure<T>(l, r => r.Name = l);
}
services.TryAddSingleton(typeof(IOptionsMonitor<ILog>), typeof(LogManager<T>));
return services;
}
public static DIHelper AddNLogManager(this DIHelper services, params string[] additionalLoggers)
{
services.TryAddSingleton<IConfigureOptions<LogNLog>, ConfigureLogNLog>();
return services.AddLogManager<LogNLog>(additionalLoggers);
}
}
}

View File

@ -29,8 +29,7 @@ using System.IO;
using System.Security.Cryptography;
using System.Text;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using ASC.Common;
namespace ASC.Security.Cryptography
{
@ -89,7 +88,7 @@ namespace ASC.Security.Cryptography
}
public static class InstanceCryptoExtension
{
public static IServiceCollection AddInstanceCryptoService(this IServiceCollection services)
public static DIHelper AddInstanceCryptoService(this DIHelper services)
{
services.TryAddSingleton<InstanceCrypto>();

View File

@ -28,10 +28,11 @@ using System;
using System.IO;
using System.Linq;
using System.Text;
using ASC.Common;
using ASC.Common.Security;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace ASC.Security.Cryptography
{
@ -41,14 +42,14 @@ namespace ASC.Security.Cryptography
public MachinePseudoKeys(IConfiguration configuration)
{
var key = configuration["core:machinekey"];
if (string.IsNullOrEmpty(key))
{
key = configuration["asc:common.machinekey"];
}
if (!string.IsNullOrEmpty(key))
{
confkey = Encoding.UTF8.GetBytes(key);
var key = configuration["core:machinekey"];
if (string.IsNullOrEmpty(key))
{
key = configuration["asc:common.machinekey"];
}
if (!string.IsNullOrEmpty(key))
{
confkey = Encoding.UTF8.GetBytes(key);
}
}
@ -77,7 +78,7 @@ namespace ASC.Security.Cryptography
}
public static class MachinePseudoKeysExtension
{
public static IServiceCollection AddMachinePseudoKeysService(this IServiceCollection services)
public static DIHelper AddMachinePseudoKeysService(this DIHelper services)
{
services.TryAddSingleton<MachinePseudoKeys>();

View File

@ -30,6 +30,7 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using ASC.Common.Caching;
namespace ASC.Common.Threading
@ -174,8 +175,23 @@ namespace ASC.Common.Threading
task.Publication = GetPublication();
}
return task;
}
public void SetTask(DistributedTask task)
{
DistributedTaskCacheNotify.SetTask(task);
}
public void RemoveTask(string id)
{
DistributedTaskCacheNotify.RemoveTask(id, key);
}
public void CancelTask(string id)
{
DistributedTaskCacheNotify.CancelTask(id);
}
private void OnCompleted(Task task, string id)
{
var distributedTask = GetTask(id);

View File

@ -101,7 +101,7 @@ namespace ASC.Common.Utils
public static class SignatureExtension
{
public static IServiceCollection AddSignatureService(this IServiceCollection services)
public static DIHelper AddSignatureService(this DIHelper services)
{
services.TryAddSingleton<Signature>();
return services.AddMachinePseudoKeysService();

View File

@ -28,12 +28,14 @@ using System;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using ASC.Common;
using ASC.Common.Logging;
using ASC.Common.Web;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using HttpContext = Microsoft.AspNetCore.Http.HttpContext;
namespace ASC.Core.Common
@ -235,9 +237,9 @@ namespace ASC.Core.Common
public static class BaseCommonLinkUtilityExtension
{
public static IServiceCollection AddBaseCommonLinkUtilityService(this IServiceCollection services)
public static DIHelper AddBaseCommonLinkUtilityService(this DIHelper services)
{
services.TryAddScoped<BaseCommonLinkUtility>(); ;
services.TryAddScoped<BaseCommonLinkUtility>();
return services
.AddCoreBaseSettingsService()

View File

@ -29,14 +29,14 @@ using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using ASC.Common;
using ASC.Common.Logging;
using ASC.Core.Tenants;
using ASC.Core.Users;
using ASC.Core.Users;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
namespace ASC.Core.Billing
@ -339,7 +339,7 @@ namespace ASC.Core.Billing
public static class LicenseReaderExtension
{
public static IServiceCollection AddLicenseReaderService(this IServiceCollection services)
public static DIHelper AddLicenseReaderService(this DIHelper services)
{
services.TryAddScoped<LicenseReader>();

View File

@ -30,16 +30,15 @@ using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using ASC.Common;
using ASC.Common.Caching;
using ASC.Common.Logging;
using ASC.Core.Caching;
using ASC.Core.Common.EF;
using ASC.Core.Tenants;
using ASC.Core.Tenants;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
namespace ASC.Core.Billing
@ -75,8 +74,8 @@ namespace ASC.Core.Billing
log.Error(err);
}*/
}
}
}
class ConfigureTariffService : IConfigureNamedOptions<TariffService>
{
public ConfigureTariffService(
@ -142,8 +141,8 @@ namespace ASC.Core.Billing
private static readonly TimeSpan DEFAULT_CACHE_EXPIRATION = TimeSpan.FromMinutes(5);
private static readonly TimeSpan STANDALONE_CACHE_EXPIRATION = TimeSpan.FromMinutes(15);
private readonly static bool billingConfigured = false;
private readonly static bool billingConfigured = false;
internal ICache Cache { get; set; }
internal ICacheNotify<TariffCacheItem> Notify { get; set; }
internal ILog Log { get; set; }
@ -156,43 +155,43 @@ namespace ASC.Core.Billing
public CoreBaseSettings CoreBaseSettings { get; set; }
public CoreSettings CoreSettings { get; set; }
public IConfiguration Configuration { get; set; }
public CoreDbContext CoreDbContext { get; set; }
public CoreDbContext CoreDbContext { get; set; }
public TariffServiceStorage TariffServiceStorage { get; set; }
public IOptionsMonitor<ILog> Options { get; set; }
public TariffService()
{
CacheExpiration = DEFAULT_CACHE_EXPIRATION;
}
public TariffService(
IQuotaService quotaService,
ITenantService tenantService,
CoreBaseSettings coreBaseSettings,
CoreSettings coreSettings,
IConfiguration configuration,
IQuotaService quotaService,
ITenantService tenantService,
CoreBaseSettings coreBaseSettings,
CoreSettings coreSettings,
IConfiguration configuration,
DbContextManager<CoreDbContext> coreDbContextManager,
TariffServiceStorage tariffServiceStorage,
IOptionsMonitor<ILog> options)
TariffServiceStorage tariffServiceStorage,
IOptionsMonitor<ILog> options)
: this()
{
{
Log = options.CurrentValue;
QuotaService = quotaService;
TenantService = tenantService;
CoreSettings = coreSettings;
Configuration = configuration;
TariffServiceStorage = tariffServiceStorage;
Options = options;
CoreBaseSettings = coreBaseSettings;
CoreSettings = coreSettings;
Configuration = configuration;
TariffServiceStorage = tariffServiceStorage;
Options = options;
CoreBaseSettings = coreBaseSettings;
Test = configuration["core:payment:test"] == "true";
int.TryParse(configuration["core:payment:delay"], out var paymentDelay);
PaymentDelay = paymentDelay;
Cache = TariffServiceStorage.Cache;
Notify = TariffServiceStorage.Notify;
CoreDbContext = coreDbContextManager.Value;
CoreDbContext = coreDbContextManager.Value;
}
public Tariff GetTariff(int tenantId, bool withRequestToPaymentSystem = true)
@ -356,9 +355,9 @@ namespace ASC.Core.Billing
.Select(q => q.AvangateId)
.ToArray();
using var client = GetBillingClient();
urls = tenant.HasValue ?
client.GetPaymentUrls(GetPortalId(tenant.Value), products, GetAffiliateId(tenant.Value), GetCampaign(tenant.Value), "__Currency__", "__Language__", "__CustomerID__") :
using var client = GetBillingClient();
urls = tenant.HasValue ?
client.GetPaymentUrls(GetPortalId(tenant.Value), products, GetAffiliateId(tenant.Value), GetCampaign(tenant.Value), "__Currency__", "__Language__", "__CustomerID__") :
client.GetPaymentUrls(null, products, !string.IsNullOrEmpty(affiliateId) ? affiliateId : null, null, "__Currency__", "__Language__", "__CustomerID__");
}
catch (Exception error)
@ -440,34 +439,34 @@ namespace ASC.Core.Billing
public string GetButton(int tariffId, string partnerId)
{
return CoreDbContext.Buttons
.Where(r => r.TariffId == tariffId && r.PartnerId == partnerId)
.Select(r => r.ButtonUrl)
{
return CoreDbContext.Buttons
.Where(r => r.TariffId == tariffId && r.PartnerId == partnerId)
.Select(r => r.ButtonUrl)
.SingleOrDefault();
}
public void SaveButton(int tariffId, string partnerId, string buttonUrl)
{
var efButton = new DbButton()
{
TariffId = tariffId,
PartnerId = partnerId,
ButtonUrl = buttonUrl
};
CoreDbContext.AddOrUpdate(r => r.Buttons, efButton);
{
var efButton = new DbButton()
{
TariffId = tariffId,
PartnerId = partnerId,
ButtonUrl = buttonUrl
};
CoreDbContext.AddOrUpdate(r => r.Buttons, efButton);
CoreDbContext.SaveChanges();
}
private Tuple<int, DateTime> GetBillingInfo(int tenant)
{
var r = CoreDbContext.Tariffs
.Where(r => r.Tenant == tenant)
.OrderByDescending(r => r.Id)
.SingleOrDefault();
{
var r = CoreDbContext.Tariffs
.Where(r => r.Tenant == tenant)
.OrderByDescending(r => r.Id)
.SingleOrDefault();
return r != null ? Tuple.Create(r.Tariff, r.Stamp.Year < 9999 ? r.Stamp : DateTime.MaxValue) : null;
}
@ -476,23 +475,23 @@ namespace ASC.Core.Billing
var inserted = false;
if (!Equals(bi, GetBillingInfo(tenant)))
{
using var tx = CoreDbContext.Database.BeginTransaction();
// last record is not the same
var count = CoreDbContext.Tariffs
.Count(r => r.Tenant == tenant && r.Tariff == bi.Item1 && r.Stamp == bi.Item2);
using var tx = CoreDbContext.Database.BeginTransaction();
// last record is not the same
var count = CoreDbContext.Tariffs
.Count(r => r.Tenant == tenant && r.Tariff == bi.Item1 && r.Stamp == bi.Item2);
if (bi.Item2 == DateTime.MaxValue || renewal || count == 0)
{
var efTariff = new DbTariff
{
Tenant = tenant,
Tariff = bi.Item1,
Stamp = bi.Item2
};
CoreDbContext.Tariffs.Add(efTariff);
CoreDbContext.SaveChanges();
{
var efTariff = new DbTariff
{
Tenant = tenant,
Tariff = bi.Item1,
Stamp = bi.Item2
};
CoreDbContext.Tariffs.Add(efTariff);
CoreDbContext.SaveChanges();
Cache.Remove(GetTariffCacheKey(tenant));
inserted = true;
@ -514,15 +513,15 @@ namespace ASC.Core.Billing
public void DeleteDefaultBillingInfo()
{
const int tenant = Tenant.DEFAULT_TENANT;
var tariffs = CoreDbContext.Tariffs.Where(r => r.Tenant == tenant).ToList();
foreach (var t in tariffs)
{
t.Tenant = -2;
}
const int tenant = Tenant.DEFAULT_TENANT;
var tariffs = CoreDbContext.Tariffs.Where(r => r.Tenant == tenant).ToList();
foreach (var t in tariffs)
{
t.Tenant = -2;
}
CoreDbContext.SaveChanges();
ClearCache(tenant);
@ -637,12 +636,12 @@ namespace ASC.Core.Billing
private string GetAffiliateId(int tenant)
{
return CoreSettings.GetAffiliateId(tenant);
}
private string GetCampaign(int tenant)
{
return CoreSettings.GetCampaign(tenant);
}
}
private string GetCampaign(int tenant)
{
return CoreSettings.GetCampaign(tenant);
}
private TimeSpan GetCacheExpiration()
{
@ -687,13 +686,13 @@ namespace ASC.Core.Billing
public static class TariffConfigExtension
{
public static IServiceCollection AddTariffService(this IServiceCollection services)
{
services.AddCoreDbContextService();
public static DIHelper AddTariffService(this DIHelper services)
{
services.AddCoreDbContextService();
services.TryAddSingleton<TariffServiceStorage>();
services.TryAddSingleton<TariffServiceStorage>();
services.TryAddScoped<ITariffService, TariffService>();
services.TryAddScoped<ITariffService, TariffService>();
services.TryAddScoped<IConfigureOptions<TariffService>, ConfigureTariffService>();
return services;

View File

@ -25,29 +25,29 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using ASC.Common;
using ASC.Common.Caching;
using ASC.Core.Common.EF;
using ASC.Core.Data;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using ASC.Core.Common.EF;
using ASC.Core.Data;
namespace ASC.Core.Caching
{
class AzServiceCache
{
internal ICache Cache { get; }
internal ICacheNotify<AzRecordCache> CacheNotify { get; }
public AzServiceCache(ICacheNotify<AzRecordCache> cacheNotify)
{
CacheNotify = cacheNotify;
Cache = AscCache.Memory;
cacheNotify.Subscribe((r) => UpdateCache(r, true), CacheNotifyAction.Remove);
cacheNotify.Subscribe((r) => UpdateCache(r, false), CacheNotifyAction.InsertOrUpdate);
}
{
class AzServiceCache
{
internal ICache Cache { get; }
internal ICacheNotify<AzRecordCache> CacheNotify { get; }
public AzServiceCache(ICacheNotify<AzRecordCache> cacheNotify)
{
CacheNotify = cacheNotify;
Cache = AscCache.Memory;
cacheNotify.Subscribe((r) => UpdateCache(r, true), CacheNotifyAction.Remove);
cacheNotify.Subscribe((r) => UpdateCache(r, false), CacheNotifyAction.InsertOrUpdate);
}
private void UpdateCache(AzRecord r, bool remove)
{
var aces = Cache.Get<AzRecordStore>(GetKey(r.Tenant));
@ -65,29 +65,29 @@ namespace ASC.Core.Caching
}
}
}
}
}
public static string GetKey(int tenant)
{
return "acl" + tenant.ToString();
}
}
}
}
class CachedAzService : IAzService
{
private readonly IAzService service;
private readonly ICacheNotify<AzRecordCache> cacheNotify;
private ICache Cache { get; }
private TimeSpan CacheExpiration { get; set; }
public CachedAzService(DbAzService service, AzServiceCache azServiceCache)
{
{
this.service = service ?? throw new ArgumentNullException("service");
Cache = azServiceCache.Cache;
Cache = azServiceCache.Cache;
cacheNotify = azServiceCache.CacheNotify;
CacheExpiration = TimeSpan.FromMinutes(10);
}
@ -117,20 +117,20 @@ namespace ASC.Core.Caching
service.RemoveAce(tenant, r);
cacheNotify.Publish(r, CacheNotifyAction.Remove);
}
}
public static class AzConfigExtension
{
public static IServiceCollection AddAzService(this IServiceCollection services)
{
services.AddCoreDbContextService();
services.TryAddScoped<DbAzService>();
services.TryAddScoped<IAzService, CachedAzService>();
services.TryAddSingleton<AzServiceCache>();
services.TryAddSingleton(typeof(ICacheNotify<>), typeof(KafkaCache<>));
return services;
}
}
}
public static class AzConfigExtension
{
public static DIHelper AddAzService(this DIHelper services)
{
services.AddCoreDbContextService();
services.TryAddScoped<DbAzService>();
services.TryAddScoped<IAzService, CachedAzService>();
services.TryAddSingleton<AzServiceCache>();
services.TryAddSingleton(typeof(ICacheNotify<>), typeof(KafkaCache<>));
return services;
}
}
}

View File

@ -26,46 +26,46 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq;
using ASC.Common;
using ASC.Common.Caching;
using ASC.Core.Common.EF;
using ASC.Core.Data;
using ASC.Core.Tenants;
using ASC.Core.Common.EF;
using ASC.Core.Data;
using ASC.Core.Tenants;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
namespace ASC.Core.Caching
{
class QuotaServiceCache
{
{
class QuotaServiceCache
{
internal const string KEY_QUOTA = "quota";
internal const string KEY_QUOTA_ROWS = "quotarows";
internal TrustInterval Interval { get; set; }
internal ICache Cache { get; }
internal ICacheNotify<QuotaCacheItem> CacheNotify { get; }
internal bool QuotaCacheEnabled { get; }
public QuotaServiceCache(IConfiguration Configuration, ICacheNotify<QuotaCacheItem> cacheNotify)
{
if (Configuration["core:enable-quota-cache"] == null)
{
QuotaCacheEnabled = true;
}
else
{
QuotaCacheEnabled = !bool.TryParse(Configuration["core:enable-quota-cache"], out var enabled) || enabled;
}
CacheNotify = cacheNotify;
Cache = AscCache.Memory;
Interval = new TrustInterval();
internal const string KEY_QUOTA_ROWS = "quotarows";
internal TrustInterval Interval { get; set; }
internal ICache Cache { get; }
internal ICacheNotify<QuotaCacheItem> CacheNotify { get; }
internal bool QuotaCacheEnabled { get; }
public QuotaServiceCache(IConfiguration Configuration, ICacheNotify<QuotaCacheItem> cacheNotify)
{
if (Configuration["core:enable-quota-cache"] == null)
{
QuotaCacheEnabled = true;
}
else
{
QuotaCacheEnabled = !bool.TryParse(Configuration["core:enable-quota-cache"], out var enabled) || enabled;
}
CacheNotify = cacheNotify;
Cache = AscCache.Memory;
Interval = new TrustInterval();
cacheNotify.Subscribe((i) =>
{
if (i.Key == KEY_QUOTA_ROWS)
@ -76,10 +76,10 @@ namespace ASC.Core.Caching
{
Cache.Remove(KEY_QUOTA);
}
}, CacheNotifyAction.Any);
}
}
}, CacheNotifyAction.Any);
}
}
class ConfigureCachedQuotaService : IConfigureNamedOptions<CachedQuotaService>
{
public IOptionsSnapshot<DbQuotaService> Service { get; }
@ -122,8 +122,8 @@ namespace ASC.Core.Caching
{
Interval = new TrustInterval();
CacheExpiration = TimeSpan.FromMinutes(10);
}
}
public CachedQuotaService(DbQuotaService service, QuotaServiceCache quotaServiceCache) : this()
{
Service = service ?? throw new ArgumentNullException("service");
@ -136,10 +136,10 @@ namespace ASC.Core.Caching
{
var quotas = Cache.Get<IEnumerable<TenantQuota>>(QuotaServiceCache.KEY_QUOTA);
if (quotas == null)
{
{
quotas = Service.GetTenantQuotas();
if (QuotaServiceCache.QuotaCacheEnabled)
{
if (QuotaServiceCache.QuotaCacheEnabled)
{
Cache.Insert(QuotaServiceCache.KEY_QUOTA, quotas, DateTime.UtcNow.Add(CacheExpiration));
}
}
@ -211,9 +211,9 @@ namespace ASC.Core.Caching
}
}
}
if (QuotaServiceCache.QuotaCacheEnabled)
{
if (QuotaServiceCache.QuotaCacheEnabled)
{
Cache.Insert(QuotaServiceCache.KEY_QUOTA_ROWS, rows, DateTime.UtcNow.Add(CacheExpiration));
}
}
@ -237,24 +237,24 @@ namespace ASC.Core.Caching
return list.ToList();
}
}
}
public static class QuotaConfigExtension
{
public static IServiceCollection AddQuotaService(this IServiceCollection services)
{
services.AddCoreDbContextService();
services.TryAddSingleton(typeof(ICacheNotify<>), typeof(KafkaCache<>));
services.TryAddSingleton<QuotaServiceCache>();
services.TryAddScoped<DbQuotaService>();
services.TryAddScoped<IQuotaService, CachedQuotaService>();
}
public static class QuotaConfigExtension
{
public static DIHelper AddQuotaService(this DIHelper services)
{
services.AddCoreDbContextService();
services.TryAddSingleton(typeof(ICacheNotify<>), typeof(KafkaCache<>));
services.TryAddSingleton<QuotaServiceCache>();
services.TryAddScoped<DbQuotaService>();
services.TryAddScoped<IQuotaService, CachedQuotaService>();
services.TryAddScoped<IConfigureOptions<DbQuotaService>, ConfigureDbQuotaService>();
services.TryAddScoped<IConfigureOptions<CachedQuotaService>, ConfigureCachedQuotaService>();
return services;
}
return services;
}
}
}

View File

@ -27,11 +27,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using ASC.Common;
using ASC.Common.Caching;
using ASC.Core.Common.EF;
using ASC.Core.Data;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace ASC.Core.Caching
{
@ -288,7 +288,7 @@ namespace ASC.Core.Caching
public static class SubscriptionConfigExtension
{
public static IServiceCollection AddSubscriptionService(this IServiceCollection services)
public static DIHelper AddSubscriptionService(this DIHelper services)
{
services.TryAddSingleton(typeof(ICacheNotify<>), typeof(KafkaCache<>));

View File

@ -27,46 +27,46 @@
using System;
using System.Collections.Generic;
using ASC.Common;
using ASC.Common.Caching;
using ASC.Common.Utils;
using ASC.Core.Common.EF.Context;
using ASC.Core.Data;
using ASC.Core.Tenants;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using ASC.Common.Utils;
using ASC.Core.Common.EF.Context;
using ASC.Core.Data;
using ASC.Core.Tenants;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
namespace ASC.Core.Caching
{
class TenantServiceCache
{
private const string KEY = "tenants";
private TimeSpan CacheExpiration { get; set; }
internal ICache Cache { get; }
internal ICacheNotify<TenantCacheItem> CacheNotifyItem { get; }
internal ICacheNotify<TenantSetting> CacheNotifySettings { get; }
public TenantServiceCache(CoreBaseSettings coreBaseSettings, ICacheNotify<TenantCacheItem> cacheNotifyItem, ICacheNotify<TenantSetting> cacheNotifySettings)
{
CacheNotifyItem = cacheNotifyItem;
CacheNotifySettings = cacheNotifySettings;
Cache = AscCache.Memory;
CacheExpiration = TimeSpan.FromMinutes(2);
{
class TenantServiceCache
{
private const string KEY = "tenants";
private TimeSpan CacheExpiration { get; set; }
internal ICache Cache { get; }
internal ICacheNotify<TenantCacheItem> CacheNotifyItem { get; }
internal ICacheNotify<TenantSetting> CacheNotifySettings { get; }
public TenantServiceCache(CoreBaseSettings coreBaseSettings, ICacheNotify<TenantCacheItem> cacheNotifyItem, ICacheNotify<TenantSetting> cacheNotifySettings)
{
CacheNotifyItem = cacheNotifyItem;
CacheNotifySettings = cacheNotifySettings;
Cache = AscCache.Memory;
CacheExpiration = TimeSpan.FromMinutes(2);
cacheNotifyItem.Subscribe((t) =>
{
var tenants = GetTenantStore();
tenants.Remove(t.TenantId);
tenants.Clear(coreBaseSettings);
}, CacheNotifyAction.InsertOrUpdate);
}, CacheNotifyAction.InsertOrUpdate);
cacheNotifySettings.Subscribe((s) =>
{
Cache.Remove(s.Key);
}, CacheNotifyAction.Remove);
}
}, CacheNotifyAction.Remove);
}
internal TenantStore GetTenantStore()
{
var store = Cache.Get<TenantStore>(KEY);
@ -150,7 +150,7 @@ namespace ASC.Core.Caching
byDomain.Clear();
}
}
}
}
}
class ConfigureCachedTenantService : IConfigureNamedOptions<CachedTenantService>
@ -185,23 +185,23 @@ namespace ASC.Core.Caching
{
internal ITenantService Service { get; set; }
private readonly ICache cache;
private readonly ICache cache;
internal ICacheNotify<TenantSetting> CacheNotifySettings { get; set; }
internal ICacheNotify<TenantCacheItem> CacheNotifyItem { get; set; }
private TimeSpan SettingsExpiration { get; set; }
private TimeSpan SettingsExpiration { get; set; }
internal TenantServiceCache TenantServiceCache { get; set; }
public CachedTenantService()
{
{
cache = AscCache.Memory;
SettingsExpiration = TimeSpan.FromMinutes(2);
}
public CachedTenantService(DbTenantService service, TenantServiceCache tenantServiceCache) : this()
{
Service = service ?? throw new ArgumentNullException("service");
TenantServiceCache = tenantServiceCache;
TenantServiceCache = tenantServiceCache;
CacheNotifyItem = tenantServiceCache.CacheNotifyItem;
CacheNotifySettings = tenantServiceCache.CacheNotifySettings;
}
@ -302,26 +302,26 @@ namespace ASC.Core.Caching
var cacheKey = string.Format("settings/{0}/{1}", tenant, key);
CacheNotifySettings.Publish(new TenantSetting { Key = cacheKey }, CacheNotifyAction.Remove);
}
}
public static class TenantConfigExtension
{
public static IServiceCollection AddTenantService(this IServiceCollection services)
{
services.TryAddSingleton(typeof(ICacheNotify<>), typeof(KafkaCache<>));
services.TryAddSingleton<TenantDomainValidator>();
services.TryAddSingleton<TimeZoneConverter>();
services.TryAddSingleton<TenantServiceCache>();
services.TryAddScoped<DbTenantService>();
services.TryAddScoped<ITenantService, CachedTenantService>();
}
public static class TenantConfigExtension
{
public static DIHelper AddTenantService(this DIHelper services)
{
services.TryAddSingleton(typeof(ICacheNotify<>), typeof(KafkaCache<>));
services.TryAddSingleton<TenantDomainValidator>();
services.TryAddSingleton<TimeZoneConverter>();
services.TryAddSingleton<TenantServiceCache>();
services.TryAddScoped<DbTenantService>();
services.TryAddScoped<ITenantService, CachedTenantService>();
services.TryAddScoped<IConfigureOptions<DbTenantService>, ConfigureDbTenantService>();
services.TryAddScoped<IConfigureOptions<CachedTenantService>, ConfigureCachedTenantService>();
return services
.AddCoreBaseSettingsService()
.AddTenantDbContextService();
}
return services
.AddCoreBaseSettingsService()
.AddTenantDbContextService();
}
}
}

View File

@ -27,19 +27,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading;
using ASC.Common;
using ASC.Common.Caching;
using ASC.Common.Logging;
using ASC.Core.Common.EF;
using ASC.Common.Logging;
using ASC.Core.Common.EF;
using ASC.Core.Data;
using ASC.Core.Tenants;
using ASC.Core.Users;
using ASC.Core.Users;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
namespace ASC.Core.Caching
{
public class UserServiceCache
@ -135,14 +135,14 @@ namespace ASC.Core.Caching
{
return tenant.ToString() + USERS + userId;
}
}
}
class ConfigureCachedUserService : IConfigureNamedOptions<CachedUserService>
{
{
public IOptionsSnapshot<EFUserService> Service { get; }
public UserServiceCache UserServiceCache { get; }
public CoreBaseSettings CoreBaseSettings { get; }
public ConfigureCachedUserService(
IOptionsSnapshot<EFUserService> service,
UserServiceCache userServiceCache,
@ -198,22 +198,22 @@ namespace ASC.Core.Caching
PhotoExpiration = TimeSpan.FromMinutes(10);
}
public CachedUserService(
EFUserService service,
CoreBaseSettings coreBaseSettings,
UserServiceCache userServiceCache
public CachedUserService(
EFUserService service,
CoreBaseSettings coreBaseSettings,
UserServiceCache userServiceCache
) : this()
{
{
Service = service ?? throw new ArgumentNullException("service");
CoreBaseSettings = coreBaseSettings;
UserServiceCache = userServiceCache;
CoreBaseSettings = coreBaseSettings;
UserServiceCache = userServiceCache;
Cache = userServiceCache.Cache;
CacheUserInfoItem = userServiceCache.CacheUserInfoItem;
CacheUserPhotoItem = userServiceCache.CacheUserPhotoItem;
CacheGroupCacheItem = userServiceCache.CacheGroupCacheItem;
CacheUserGroupRefItem = userServiceCache.CacheUserGroupRefItem;
CacheUserInfoItem = userServiceCache.CacheUserInfoItem;
CacheUserPhotoItem = userServiceCache.CacheUserPhotoItem;
CacheGroupCacheItem = userServiceCache.CacheGroupCacheItem;
CacheUserGroupRefItem = userServiceCache.CacheUserGroupRefItem;
TrustInterval = userServiceCache.TrustInterval;
}
}
public IDictionary<Guid, UserInfo> GetUsers(int tenant, DateTime from)
{
@ -224,19 +224,19 @@ namespace ASC.Core.Caching
}
}
public IQueryable<UserInfo> GetUsers(
int tenant,
bool isAdmin,
EmployeeStatus? employeeStatus,
List<List<Guid>> includeGroups,
List<Guid> excludeGroups,
EmployeeActivationStatus? activationStatus,
string text,
string sortBy,
bool sortOrderAsc,
long limit,
long offset,
out int total,
public IQueryable<UserInfo> GetUsers(
int tenant,
bool isAdmin,
EmployeeStatus? employeeStatus,
List<List<Guid>> includeGroups,
List<Guid> excludeGroups,
EmployeeActivationStatus? activationStatus,
string text,
string sortBy,
bool sortOrderAsc,
long limit,
long offset,
out int total,
out int count)
{
return Service.GetUsers(tenant, isAdmin, employeeStatus, includeGroups, excludeGroups, activationStatus, text, sortBy, sortOrderAsc, limit, offset, out total, out count);
@ -515,22 +515,22 @@ namespace ASC.Core.Caching
}
public static class UserConfigExtension
{
public static IServiceCollection AddUserService(this IServiceCollection services)
{
services.TryAddSingleton(typeof(ICacheNotify<>), typeof(KafkaCache<>));
services
.AddCoreSettingsService()
.AddLoggerService()
.AddUserDbContextService();
services.TryAddScoped<EFUserService>();
services.TryAddScoped<IUserService, CachedUserService>();
public static DIHelper AddUserService(this DIHelper services)
{
services.TryAddSingleton(typeof(ICacheNotify<>), typeof(KafkaCache<>));
services
.AddCoreSettingsService()
.AddLoggerService()
.AddUserDbContextService();
services.TryAddScoped<EFUserService>();
services.TryAddScoped<IUserService, CachedUserService>();
services.TryAddScoped<IConfigureOptions<EFUserService>, ConfigureEFUserService>();
services.TryAddScoped<IConfigureOptions<CachedUserService>, ConfigureCachedUserService>();
services.TryAddSingleton<UserServiceCache>();
services.TryAddSingleton<UserServiceCache>();
return services;
}
}

View File

@ -27,17 +27,16 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq;
using ASC.Common;
using ASC.Common.Caching;
using ASC.Core.Tenants;
using Autofac;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using ASC.Core.Tenants;
using Autofac;
using Microsoft.Extensions.Configuration;
namespace ASC.Core.Common.Configuration
{
public class Consumer : IDictionary<string, string>
@ -79,57 +78,57 @@ namespace ASC.Core.Common.Configuration
}
private readonly bool OnlyDefault;
public TenantManager TenantManager { get; set; }
public CoreBaseSettings CoreBaseSettings { get; set; }
public CoreSettings CoreSettings { get; set; }
public ConsumerFactory ConsumerFactory { get; }
public IConfiguration Configuration { get; }
public ICacheNotify<ConsumerCacheItem> Cache { get; }
public TenantManager TenantManager { get; set; }
public CoreBaseSettings CoreBaseSettings { get; set; }
public CoreSettings CoreSettings { get; set; }
public ConsumerFactory ConsumerFactory { get; }
public IConfiguration Configuration { get; }
public ICacheNotify<ConsumerCacheItem> Cache { get; }
public bool IsSet
{
get { return Props.Any() && !Props.All(r => string.IsNullOrEmpty(this[r.Key])); }
}
static Consumer()
{
{
}
public Consumer()
{
{
Props = new Dictionary<string, string>();
Additional = new Dictionary<string, string>();
}
public Consumer(
TenantManager tenantManager,
CoreBaseSettings coreBaseSettings,
CoreSettings coreSettings,
ConsumerFactory consumerFactory,
IConfiguration configuration,
}
public Consumer(
TenantManager tenantManager,
CoreBaseSettings coreBaseSettings,
CoreSettings coreSettings,
ConsumerFactory consumerFactory,
IConfiguration configuration,
ICacheNotify<ConsumerCacheItem> cache) : this()
{
TenantManager = tenantManager;
CoreBaseSettings = coreBaseSettings;
CoreSettings = coreSettings;
ConsumerFactory = consumerFactory;
Configuration = configuration;
Cache = cache;
{
TenantManager = tenantManager;
CoreBaseSettings = coreBaseSettings;
CoreSettings = coreSettings;
ConsumerFactory = consumerFactory;
Configuration = configuration;
Cache = cache;
OnlyDefault = configuration["core:default-consumers"] == "true";
Name = "";
Order = int.MaxValue;
}
public Consumer(
TenantManager tenantManager,
CoreBaseSettings coreBaseSettings,
CoreSettings coreSettings,
ConsumerFactory consumerFactory,
IConfiguration configuration,
ICacheNotify<ConsumerCacheItem> cache,
string name, int order, Dictionary<string, string> additional)
public Consumer(
TenantManager tenantManager,
CoreBaseSettings coreBaseSettings,
CoreSettings coreSettings,
ConsumerFactory consumerFactory,
IConfiguration configuration,
ICacheNotify<ConsumerCacheItem> cache,
string name, int order, Dictionary<string, string> additional)
: this(tenantManager, coreBaseSettings, coreSettings, consumerFactory, configuration, cache)
{
Name = name;
@ -138,14 +137,14 @@ namespace ASC.Core.Common.Configuration
Additional = additional;
}
public Consumer(
TenantManager tenantManager,
CoreBaseSettings coreBaseSettings,
CoreSettings coreSettings,
ConsumerFactory consumerFactory,
IConfiguration configuration,
ICacheNotify<ConsumerCacheItem> cache,
string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional)
public Consumer(
TenantManager tenantManager,
CoreBaseSettings coreBaseSettings,
CoreSettings coreSettings,
ConsumerFactory consumerFactory,
IConfiguration configuration,
ICacheNotify<ConsumerCacheItem> cache,
string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional)
: this(tenantManager, coreBaseSettings, coreSettings, consumerFactory, configuration, cache)
{
Name = name;
@ -294,45 +293,45 @@ namespace ASC.Core.Common.Configuration
public const string HandlerTypeKey = "handlerType";
public const string CdnKey = "cdn";
public DataStoreConsumer() : base()
{
}
public DataStoreConsumer(
TenantManager tenantManager,
CoreBaseSettings coreBaseSettings,
CoreSettings coreSettings,
ConsumerFactory consumerFactory,
IConfiguration configuration,
ICacheNotify<ConsumerCacheItem> cache)
: base(tenantManager, coreBaseSettings, coreSettings, consumerFactory, configuration, cache)
{
public DataStoreConsumer() : base()
{
}
public DataStoreConsumer(
TenantManager tenantManager,
CoreBaseSettings coreBaseSettings,
CoreSettings coreSettings,
ConsumerFactory consumerFactory,
IConfiguration configuration,
ICacheNotify<ConsumerCacheItem> cache,
string name, int order, Dictionary<string, string> additional)
public DataStoreConsumer(
TenantManager tenantManager,
CoreBaseSettings coreBaseSettings,
CoreSettings coreSettings,
ConsumerFactory consumerFactory,
IConfiguration configuration,
ICacheNotify<ConsumerCacheItem> cache)
: base(tenantManager, coreBaseSettings, coreSettings, consumerFactory, configuration, cache)
{
}
public DataStoreConsumer(
TenantManager tenantManager,
CoreBaseSettings coreBaseSettings,
CoreSettings coreSettings,
ConsumerFactory consumerFactory,
IConfiguration configuration,
ICacheNotify<ConsumerCacheItem> cache,
string name, int order, Dictionary<string, string> additional)
: base(tenantManager, coreBaseSettings, coreSettings, consumerFactory, configuration, cache, name, order, additional)
{
Init(additional);
}
public DataStoreConsumer(
TenantManager tenantManager,
CoreBaseSettings coreBaseSettings,
CoreSettings coreSettings,
ConsumerFactory consumerFactory,
IConfiguration configuration,
ICacheNotify<ConsumerCacheItem> cache,
string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional)
public DataStoreConsumer(
TenantManager tenantManager,
CoreBaseSettings coreBaseSettings,
CoreSettings coreSettings,
ConsumerFactory consumerFactory,
IConfiguration configuration,
ICacheNotify<ConsumerCacheItem> cache,
string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional)
: base(tenantManager, coreBaseSettings, coreSettings, consumerFactory, configuration, cache, name, order, props, additional)
{
Init(additional);
@ -380,14 +379,14 @@ namespace ASC.Core.Common.Configuration
public class ConsumerFactory
{
public ILifetimeScope Builder { get; set; }
public ILifetimeScope Builder { get; set; }
public ConsumerFactory(IContainer builder)
{
Builder = builder;
}
}
public ConsumerFactory(ILifetimeScope builder)
{
Builder = builder;
@ -427,14 +426,14 @@ namespace ASC.Core.Common.Configuration
{
return Builder.Resolve<IEnumerable<T>>();
}
}
public static class ConsumerFactoryExtension
{
public static IServiceCollection AddConsumerFactoryService(this IServiceCollection services)
{
services.TryAddScoped<ConsumerFactory>();
return services;
}
}
}
public static class ConsumerFactoryExtension
{
public static DIHelper AddConsumerFactoryService(this DIHelper services)
{
services.TryAddScoped<ConsumerFactory>();
return services;
}
}
}

View File

@ -25,31 +25,29 @@
using System;
using System.Linq;
using System.Linq;
using ASC.Common;
using ASC.Common.Security.Authentication;
using ASC.Core.Caching;
using ASC.Core.Caching;
using ASC.Core.Security.Authentication;
using ASC.Core.Tenants;
using ASC.Core.Users;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using ASC.Core.Tenants;
using ASC.Core.Users;
namespace ASC.Core
{
public class AuthManager
{
private readonly IUserService userService;
public UserManager UserManager { get; }
public UserFormatter UserFormatter { get; }
private readonly IUserService userService;
public UserManager UserManager { get; }
public UserFormatter UserFormatter { get; }
public AuthManager(IUserService service, UserManager userManager, UserFormatter userFormatter)
{
userService = service;
UserManager = userManager;
UserFormatter = userFormatter;
userService = service;
UserManager = userManager;
UserFormatter = userFormatter;
}
@ -71,8 +69,8 @@ namespace ASC.Core
public IAccount GetAccountByID(int tenantId, Guid id)
{
var s = ASC.Core.Configuration.Constants.SystemAccounts.FirstOrDefault(a => a.ID == id);
if (s != null) return s;
if (s != null) return s;
var u = UserManager.GetUsers(id);
return !Constants.LostUser.Equals(u) && u.Status == EmployeeStatus.Active ? (IAccount)ToAccount(tenantId, u) : ASC.Core.Configuration.Constants.Guest;
}
@ -82,16 +80,16 @@ namespace ASC.Core
{
return new UserAccount(u, tenantId, UserFormatter);
}
}
public static class AuthManagerExtension
{
public static IServiceCollection AddAuthManager(this IServiceCollection services)
{
services.TryAddScoped<AuthManager>();
return services
.AddUserService()
.AddUserFormatter()
.AddUserManagerService();
}
}
}
public static class AuthManagerExtension
{
public static DIHelper AddAuthManager(this DIHelper services)
{
services.TryAddScoped<AuthManager>();
return services
.AddUserService()
.AddUserFormatter()
.AddUserManagerService();
}
}
}

View File

@ -26,25 +26,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq;
using ASC.Common;
using ASC.Common.Security;
using ASC.Common.Security.Authorizing;
using ASC.Core.Caching;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using ASC.Core.Caching;
namespace ASC.Core
{
public class AuthorizationManager
{
private readonly IAzService service;
private TenantManager TenantManager { get; }
private readonly IAzService service;
private TenantManager TenantManager { get; }
public AuthorizationManager(IAzService service, TenantManager tenantManager)
{
this.service = service;
TenantManager = tenantManager;
this.service = service;
TenantManager = tenantManager;
}
@ -127,16 +127,16 @@ namespace ASC.Core
store.Get(objId).Where(a => (a.SubjectId == subjectId || subjectId == Guid.Empty) && (a.ActionId == actionId || actionId == Guid.Empty)) :
aces.Where(a => (a.SubjectId == subjectId || subjectId == Guid.Empty) && (a.ActionId == actionId || actionId == Guid.Empty) && a.ObjectId == objId);
}
}
public static class AuthorizationManagerConfigExtension
{
public static IServiceCollection AddAuthorizationManagerService(this IServiceCollection services)
{
services.TryAddScoped<AuthorizationManager>();
return services
.AddAzService()
.AddTenantManagerService();
}
}
public static class AuthorizationManagerConfigExtension
{
public static DIHelper AddAuthorizationManagerService(this DIHelper services)
{
services.TryAddScoped<AuthorizationManager>();
return services
.AddAzService()
.AddTenantManagerService();
}
}
}

View File

@ -25,18 +25,17 @@
using System;
using System.Text;
using System.Text;
using ASC.Common;
using ASC.Core.Caching;
using ASC.Core.Common.Settings;
using ASC.Core.Common.Settings;
using ASC.Core.Configuration;
using ASC.Core.Tenants;
using ASC.Core.Tenants;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
namespace ASC.Core
@ -61,10 +60,10 @@ namespace ASC.Core
public bool Personal
{
get
{
//TODO:if (CustomMode && HttpContext.Current != null && HttpContext.Current.Request.SailfishApp()) return true;
return personal ?? (bool)(personal = Configuration["core.personal"] == "true");
get
{
//TODO:if (CustomMode && HttpContext.Current != null && HttpContext.Current.Request.SailfishApp()) return true;
return personal ?? (bool)(personal = Configuration["core.personal"] == "true");
}
}
@ -72,8 +71,8 @@ namespace ASC.Core
{
get { return customMode ?? (bool)(customMode = Configuration["core.custom-mode"] == "true"); }
}
}
}
class ConfigureCoreSettings : IConfigureNamedOptions<CoreSettings>
{
public IOptionsSnapshot<CachedTenantService> TenantService { get; }
@ -143,7 +142,7 @@ namespace ASC.Core
internal IConfiguration Configuration { get; set; }
public CoreSettings()
{
{
}
@ -232,15 +231,15 @@ namespace ASC.Core
return t.AffiliateId;
return null;
}
public string GetCampaign(int tenant)
{
var t = TenantService.GetTenant(tenant);
if (t != null && !string.IsNullOrWhiteSpace(t.Campaign))
return t.Campaign;
return null;
}
public string GetCampaign(int tenant)
{
var t = TenantService.GetTenant(tenant);
if (t != null && !string.IsNullOrWhiteSpace(t.Campaign))
return t.Campaign;
return null;
}
}
@ -371,26 +370,26 @@ namespace ASC.Core
public static class CoreSettingsConfigExtension
{
public static IServiceCollection AddCoreBaseSettingsService(this IServiceCollection services)
public static DIHelper AddCoreBaseSettingsService(this DIHelper services)
{
services.TryAddSingleton<CoreBaseSettings>();
services.TryAddSingleton<CoreBaseSettings>();
return services;
}
public static IServiceCollection AddCoreSettingsService(this IServiceCollection services)
{
services.TryAddScoped<CoreSettings>();
services.TryAddScoped<CoreConfiguration>();
public static DIHelper AddCoreSettingsService(this DIHelper services)
{
services.TryAddScoped<CoreSettings>();
services.TryAddScoped<CoreConfiguration>();
services.TryAddScoped<IConfigureOptions<CoreSettings>, ConfigureCoreSettings>();
return services
.AddCoreBaseSettingsService()
return services
.AddCoreBaseSettingsService()
.AddTenantService();
}
public static IServiceCollection AddCoreConfigurationService(this IServiceCollection services)
public static DIHelper AddCoreConfigurationService(this DIHelper services)
{
services.TryAddScoped<CoreConfiguration>();
return services
services.TryAddScoped<CoreConfiguration>();
return services
.AddCoreSettingsService();
}
}

View File

@ -34,14 +34,13 @@ using System.Text;
using System.Threading;
using System.Web;
using ASC.Common;
using ASC.Core.Billing;
using ASC.Core.Caching;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using ASC.Core.Caching;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
@ -51,16 +50,16 @@ namespace ASC.Core
{
private readonly ITariffService tariffService;
private readonly string partnerUrl;
private readonly string partnerKey;
public TenantManager TenantManager { get; }
public IConfiguration Configuration { get; }
private readonly string partnerKey;
public TenantManager TenantManager { get; }
public IConfiguration Configuration { get; }
public PaymentManager(TenantManager tenantManager, ITariffService tariffService, IConfiguration configuration)
{
{
TenantManager = tenantManager;
this.tariffService = tariffService;
Configuration = configuration;
this.tariffService = tariffService;
Configuration = configuration;
partnerUrl = (Configuration["core:payment:partners"] ?? "https://partners.onlyoffice.com/api").TrimEnd('/');
partnerKey = (Configuration["core:machinekey"] ?? "C5C1F4E85A3A43F5B3202C24D97351DF");
}
@ -120,38 +119,38 @@ namespace ASC.Core
var now = DateTime.UtcNow;
var actionUrl = "/partnerapi/ActivateKey?code=" + HttpUtility.UrlEncode(key) + "&portal=" + HttpUtility.UrlEncode(TenantManager.GetCurrentTenant().TenantAlias);
using var webClient = new WebClient();
webClient.Headers.Add("Authorization", GetPartnerAuthHeader(actionUrl));
try
{
webClient.DownloadData(partnerUrl + actionUrl);
}
catch (WebException we)
{
var error = GetException(we);
if (error != null)
{
throw error;
}
throw;
}
tariffService.ClearCache(TenantManager.GetCurrentTenant().TenantId);
var timeout = DateTime.UtcNow - now - TimeSpan.FromSeconds(5);
if (TimeSpan.Zero < timeout)
{
// clear tenant cache
Thread.Sleep(timeout);
}
using var webClient = new WebClient();
webClient.Headers.Add("Authorization", GetPartnerAuthHeader(actionUrl));
try
{
webClient.DownloadData(partnerUrl + actionUrl);
}
catch (WebException we)
{
var error = GetException(we);
if (error != null)
{
throw error;
}
throw;
}
tariffService.ClearCache(TenantManager.GetCurrentTenant().TenantId);
var timeout = DateTime.UtcNow - now - TimeSpan.FromSeconds(5);
if (TimeSpan.Zero < timeout)
{
// clear tenant cache
Thread.Sleep(timeout);
}
TenantManager.GetTenant(TenantManager.GetCurrentTenant().TenantId);
}
private string GetPartnerAuthHeader(string url)
{
using var hasher = new HMACSHA1(Encoding.UTF8.GetBytes(partnerKey));
var now = DateTime.UtcNow.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture);
var data = string.Join("\n", now, "/api/" + url.TrimStart('/')); //data: UTC DateTime (yyyy:MM:dd HH:mm:ss) + \n + url
var hash = WebEncoders.Base64UrlEncode(hasher.ComputeHash(Encoding.UTF8.GetBytes(data)));
using var hasher = new HMACSHA1(Encoding.UTF8.GetBytes(partnerKey));
var now = DateTime.UtcNow.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture);
var data = string.Join("\n", now, "/api/" + url.TrimStart('/')); //data: UTC DateTime (yyyy:MM:dd HH:mm:ss) + \n + url
var hash = WebEncoders.Base64UrlEncode(hasher.ComputeHash(Encoding.UTF8.GetBytes(data)));
return string.Format("ASC :{0}:{1}", now, hash);
}
@ -160,10 +159,10 @@ namespace ASC.Core
var response = (HttpWebResponse)we.Response;
if (response.StatusCode == HttpStatusCode.InternalServerError)
{
using var stream = response.GetResponseStream();
using var reader = new StreamReader(stream, Encoding.UTF8);
var result = reader.ReadToEnd();
var excInfo = JsonConvert.DeserializeObject<ExceptionJson>(result);
using var stream = response.GetResponseStream();
using var reader = new StreamReader(stream, Encoding.UTF8);
var result = reader.ReadToEnd();
var excInfo = JsonConvert.DeserializeObject<ExceptionJson>(result);
return (Exception)Activator.CreateInstance(Type.GetType(excInfo.exceptionType, true), excInfo.exceptionMessage);
}
return null;
@ -177,18 +176,18 @@ namespace ASC.Core
public string exceptionType = null;
public string stackTrace = null;
}
}
public static class PaymentManagerExtension
{
public static IServiceCollection AddPaymentManagerService(this IServiceCollection services)
{
services.TryAddScoped<PaymentManager>();
return services
.AddTenantManagerService()
.AddQuotaService()
.AddTariffService();
}
}
public static class PaymentManagerExtension
{
public static DIHelper AddPaymentManagerService(this DIHelper services)
{
services.TryAddScoped<PaymentManager>();
return services
.AddTenantManagerService()
.AddQuotaService()
.AddTariffService();
}
}
}

View File

@ -25,11 +25,11 @@
using System;
using System.Linq;
using ASC.Core.Caching;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System.Linq;
using ASC.Common;
using ASC.Core.Caching;
namespace ASC.Core
{
public class SubscriptionManager
@ -151,8 +151,8 @@ namespace ASC.Core
public static class SubscriptionConfigExtension
{
public static IServiceCollection AddSubscriptionManagerService(this IServiceCollection services)
{
public static DIHelper AddSubscriptionManagerService(this DIHelper services)
{
services.TryAddScoped<SubscriptionManager>();
return services
.AddSubscriptionService()

View File

@ -31,19 +31,17 @@ using System.Net;
using System.Threading;
using System.Web;
using ASC.Common;
using ASC.Common.Notify.Engine;
using ASC.Core.Billing;
using ASC.Core.Caching;
using ASC.Core.Tenants;
using ASC.Core.Caching;
using ASC.Core.Tenants;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
namespace ASC.Core
{
{
class ConfigureTenantManager : IConfigureNamedOptions<TenantManager>
{
public IOptionsSnapshot<CachedTenantService> TenantService { get; }
@ -98,14 +96,14 @@ namespace ASC.Core
internal IQuotaService QuotaService { get; set; }
internal ITariffService TariffService { get; set; }
private static List<string> thisCompAddresses = new List<string>();
private static List<string> thisCompAddresses = new List<string>();
internal HttpContext HttpContext { get; set; }
internal CoreBaseSettings CoreBaseSettings { get; set; }
internal CoreSettings CoreSettings { get; set; }
static TenantManager()
{
static TenantManager()
{
thisCompAddresses.Add("localhost");
thisCompAddresses.Add(Dns.GetHostName().ToLowerInvariant());
thisCompAddresses.AddRange(Dns.GetHostAddresses("localhost").Select(a => a.ToString()));
@ -116,27 +114,27 @@ namespace ASC.Core
catch
{
// ignore
}
}
}
public TenantManager()
{
}
public TenantManager(
ITenantService tenantService,
IQuotaService quotaService,
ITariffService tariffService,
IHttpContextAccessor httpContextAccessor,
CoreBaseSettings coreBaseSettings,
public TenantManager(
ITenantService tenantService,
IQuotaService quotaService,
ITariffService tariffService,
IHttpContextAccessor httpContextAccessor,
CoreBaseSettings coreBaseSettings,
CoreSettings coreSettings)
{
TenantService = tenantService;
QuotaService = quotaService;
TariffService = tariffService;
CoreBaseSettings = coreBaseSettings;
CoreSettings = coreSettings;
CoreBaseSettings = coreBaseSettings;
CoreSettings = coreSettings;
HttpContext = httpContextAccessor?.HttpContext;
}
@ -235,8 +233,8 @@ namespace ASC.Core
throw new Exception("Could not resolve current tenant :-(.");
}
return tenant;
}
}
public Tenant GetCurrentTenant()
{
return GetCurrentTenant(true);
@ -262,16 +260,16 @@ namespace ASC.Core
}
public Tenant SetCurrentTenant(int tenantId)
{
{
var result = GetTenant(tenantId);
SetCurrentTenant(result);
SetCurrentTenant(result);
return result;
}
public Tenant SetCurrentTenant(string domain)
{
{
var result = GetTenant(domain);
SetCurrentTenant(result);
SetCurrentTenant(result);
return result;
}
@ -336,21 +334,21 @@ namespace ASC.Core
{
return QuotaService.FindTenantQuotaRows(query).ToList();
}
}
public static class TenantManagerConfigExtension
{
public static IServiceCollection AddTenantManagerService(this IServiceCollection services)
{
services.TryAddScoped<TenantManager>();
}
public static class TenantManagerConfigExtension
{
public static DIHelper AddTenantManagerService(this DIHelper services)
{
services.TryAddScoped<TenantManager>();
services.TryAddScoped<IConfigureOptions<TenantManager>, ConfigureTenantManager>();
return services
.AddTenantService()
.AddQuotaService()
.AddTariffService()
.AddCoreBaseSettingsService()
.AddCoreSettingsService();
}
}
return services
.AddTenantService()
.AddQuotaService()
.AddTariffService()
.AddCoreBaseSettingsService()
.AddCoreSettingsService();
}
}
}

View File

@ -26,17 +26,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq;
using ASC.Collections;
using ASC.Common;
using ASC.Core.Caching;
using ASC.Core.Tenants;
using ASC.Core.Users;
using ASC.Core.Users;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace ASC.Core
{
public class UserManagerConstants
@ -68,6 +67,11 @@ namespace ASC.Core
private Tenant tenant;
private Tenant Tenant { get { return tenant ?? (tenant = TenantManager.GetCurrentTenant()); } }
public UserManager()
{
}
public UserManager(
IUserService service,
IHttpContextAccessor httpContextAccessor,
@ -120,18 +124,18 @@ namespace ASC.Core
return users.ToArray();
}
public IQueryable<UserInfo> GetUsers(
bool isAdmin,
EmployeeStatus? employeeStatus,
List<List<Guid>> includeGroups,
List<Guid> excludeGroups,
EmployeeActivationStatus? activationStatus,
string text,
string sortBy,
bool sortOrderAsc,
long limit,
long offset,
out int total,
public IQueryable<UserInfo> GetUsers(
bool isAdmin,
EmployeeStatus? employeeStatus,
List<List<Guid>> includeGroups,
List<Guid> excludeGroups,
EmployeeActivationStatus? activationStatus,
string text,
string sortBy,
bool sortOrderAsc,
long limit,
long offset,
out int total,
out int count)
{
return UserService.GetUsers(Tenant.TenantId, isAdmin, employeeStatus, includeGroups, excludeGroups, activationStatus, text, sortBy, sortOrderAsc, limit, offset, out total, out count);
@ -266,12 +270,12 @@ namespace ASC.Core
{
throw new TenantQuotaException(string.Format("Exceeds the maximum active users ({0})", q.ActiveUsers));
}
}
if (u.Status == EmployeeStatus.Terminated && u.ID == TenantManager.GetCurrentTenant().OwnerId)
{
throw new InvalidOperationException("Can not disable tenant owner.");
}
}
if (u.Status == EmployeeStatus.Terminated && u.ID == TenantManager.GetCurrentTenant().OwnerId)
{
throw new InvalidOperationException("Can not disable tenant owner.");
}
var newUser = UserService.SaveUser(Tenant.TenantId, u);
@ -634,10 +638,10 @@ namespace ASC.Core
public static class UserManagerConfigExtension
{
public static IServiceCollection AddUserManagerService(this IServiceCollection services)
{
public static DIHelper AddUserManagerService(this DIHelper services)
{
services.TryAddSingleton<UserManagerConstants>();
services.TryAddScoped<UserManager>();
services.TryAddScoped<UserManager>();
return services
.AddUserService()

View File

@ -33,6 +33,7 @@ using System.Security.Claims;
using System.Threading;
using System.Web;
using ASC.Common;
using ASC.Common.Logging;
using ASC.Common.Security;
using ASC.Common.Security.Authentication;
@ -46,8 +47,6 @@ using ASC.Core.Users;
using ASC.Security.Cryptography;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
namespace ASC.Core
@ -265,7 +264,7 @@ namespace ASC.Core
public void Logout()
{
AuthContext.Principal = null;
AuthContext.Logout();
}
public void SetUserPassword(Guid userID, string password)
@ -320,6 +319,11 @@ namespace ASC.Core
{
private IHttpContextAccessor HttpContextAccessor { get; }
public AuthContext()
{
}
public AuthContext(IHttpContextAccessor httpContextAccessor)
{
HttpContextAccessor = httpContextAccessor;
@ -335,6 +339,11 @@ namespace ASC.Core
get { return CurrentAccount.IsAuthenticated; }
}
public void Logout()
{
Principal = null;
}
internal ClaimsPrincipal Principal
{
get => Thread.CurrentPrincipal as ClaimsPrincipal ?? HttpContextAccessor?.HttpContext?.User;
@ -348,7 +357,7 @@ namespace ASC.Core
public static class AuthContextConfigExtension
{
public static IServiceCollection AddSecurityContextService(this IServiceCollection services)
public static DIHelper AddSecurityContextService(this DIHelper services)
{
services.TryAddScoped<SecurityContext>();
@ -361,13 +370,13 @@ namespace ASC.Core
.AddUserManagerService()
.AddTenantManagerService();
}
public static IServiceCollection AddAuthContextService(this IServiceCollection services)
public static DIHelper AddAuthContextService(this DIHelper services)
{
services.TryAddScoped<AuthContext>();
return services;
}
public static IServiceCollection AddPermissionContextService(this IServiceCollection services)
public static DIHelper AddPermissionContextService(this DIHelper services)
{
services.TryAddScoped<PermissionContext>();

View File

@ -34,17 +34,16 @@ using System.Reflection;
using System.Resources;
using System.Runtime.Caching;
using System.Text.RegularExpressions;
using System.Web;
using System.Web;
using ASC.Common;
using ASC.Common.Logging;
using ASC.Core;
using ASC.Core.Common.EF;
using ASC.Core.Common.EF.Context;
using ASC.Core;
using ASC.Core.Common.EF;
using ASC.Core.Common.EF.Context;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
namespace TMResourceData
@ -57,19 +56,19 @@ namespace TMResourceData
public DBResourceManager(string filename, Assembly assembly)
: base(filename, assembly)
{
}
}
public DBResourceManager(
IConfiguration configuration,
IOptionsMonitor<ILog> option,
DbContextManager<ResourceDbContext> dbContext,
string filename,
public DBResourceManager(
IConfiguration configuration,
IOptionsMonitor<ILog> option,
DbContextManager<ResourceDbContext> dbContext,
string filename,
Assembly assembly)
: base(filename, assembly)
{
Configuration = configuration;
Option = option;
DbContext = dbContext;
Option = option;
DbContext = dbContext;
}
@ -136,9 +135,9 @@ namespace TMResourceData
}
public IConfiguration Configuration { get; }
public IOptionsMonitor<ILog> Option { get; }
public DbContextManager<ResourceDbContext> DbContext { get; }
public IOptionsMonitor<ILog> Option { get; }
public DbContextManager<ResourceDbContext> DbContext { get; }
protected override ResourceSet InternalGetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents)
{
resourceSets.TryGetValue(culture.Name, out var set);
@ -165,15 +164,15 @@ namespace TMResourceData
private readonly ILog log;
public IConfiguration Configuration { get; }
public IOptionsMonitor<ILog> Option { get; }
public DbContextManager<ResourceDbContext> DbContext { get; }
public DBResourceSet(
IConfiguration configuration,
IOptionsMonitor<ILog> option,
DbContextManager<ResourceDbContext> dbContext,
ResourceSet invariant,
CultureInfo culture,
public IOptionsMonitor<ILog> Option { get; }
public DbContextManager<ResourceDbContext> DbContext { get; }
public DBResourceSet(
IConfiguration configuration,
IOptionsMonitor<ILog> option,
DbContextManager<ResourceDbContext> dbContext,
ResourceSet invariant,
CultureInfo culture,
string filename)
{
if (culture == null)
@ -186,8 +185,8 @@ namespace TMResourceData
}
Configuration = configuration;
Option = option;
DbContext = dbContext;
Option = option;
DbContext = dbContext;
log = option.CurrentValue;
try
@ -271,12 +270,12 @@ namespace TMResourceData
}
private Dictionary<string, string> LoadResourceSet(string filename, string culture)
{
{
using var context = DbContext.Get("tmresource");
var q = context.ResData
.Where(r => r.CultureTitle == culture)
.Join(context.ResFiles, r => r.FileId, a => a.Id, (d, f) => new { data = d, files = f })
.Where(r => r.files.ResName == filename);
var q = context.ResData
.Where(r => r.CultureTitle == culture)
.Join(context.ResFiles, r => r.FileId, a => a.Id, (d, f) => new { data = d, files = f })
.Where(r => r.files.ResName == filename);
return q
.ToDictionary(r => r.data.Title, r => r.data.TextValue, StringComparer.InvariantCultureIgnoreCase);
@ -375,7 +374,7 @@ namespace TMResourceData
public static class WhiteLabelHelperExtension
{
public static IServiceCollection AddWhiteLabelHelperService(this IServiceCollection services)
public static DIHelper AddWhiteLabelHelperService(this DIHelper services)
{
services.TryAddSingleton<WhiteLabelHelper>();
return services;

View File

@ -31,38 +31,37 @@ using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using ASC.Common;
using ASC.Common.Caching;
using ASC.Common.Logging;
using ASC.Core.Common.EF;
using ASC.Core.Common.EF.Context;
using ASC.Core.Common.EF.Model;
using ASC.Core.Common.Settings;
using ASC.Core.Tenants;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using ASC.Core.Common.EF;
using ASC.Core.Common.EF.Context;
using ASC.Core.Common.EF.Model;
using ASC.Core.Common.Settings;
using ASC.Core.Tenants;
using Microsoft.Extensions.Options;
namespace ASC.Core.Data
{
public class DbSettingsManagerCache
{
{
public class DbSettingsManagerCache
{
public ICache Cache { get; }
public ICacheNotify<SettingsCacheItem> Notify { get; }
public ICacheNotify<SettingsCacheItem> Notify { get; }
public DbSettingsManagerCache(ICacheNotify<SettingsCacheItem> notify)
{
Cache = AscCache.Memory;
{
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 void Remove(string key)
{
Notify.Publish(new SettingsCacheItem { Key = key }, CacheNotifyAction.Remove);
}
}
class ConfigureDbSettingsManager : IConfigureNamedOptions<DbSettingsManager>
{
private IServiceProvider ServiceProvider { get; }
@ -112,8 +111,8 @@ namespace ASC.Core.Data
public class DbSettingsManager
{
private readonly TimeSpan expirationTimeout = TimeSpan.FromMinutes(5);
private readonly IDictionary<Type, DataContractJsonSerializer> jsonSerializers = new Dictionary<Type, DataContractJsonSerializer>();
private readonly IDictionary<Type, DataContractJsonSerializer> jsonSerializers = new Dictionary<Type, DataContractJsonSerializer>();
internal ILog Log { get; set; }
internal ICache Cache { get; set; }
internal IServiceProvider ServiceProvider { get; set; }
@ -121,29 +120,29 @@ namespace ASC.Core.Data
internal AuthContext AuthContext { get; set; }
internal TenantManager TenantManager { get; set; }
internal WebstudioDbContext WebstudioDbContext { get; set; }
public DbSettingsManager()
{
}
public DbSettingsManager(
IServiceProvider serviceProvider,
DbSettingsManagerCache dbSettingsManagerCache,
IOptionsMonitor<ILog> option,
AuthContext authContext,
TenantManager tenantManager,
public DbSettingsManager(
IServiceProvider serviceProvider,
DbSettingsManagerCache dbSettingsManagerCache,
IOptionsMonitor<ILog> option,
AuthContext authContext,
TenantManager tenantManager,
DbContextManager<WebstudioDbContext> dbContextManager)
{
ServiceProvider = serviceProvider;
DbSettingsManagerCache = dbSettingsManagerCache;
AuthContext = authContext;
TenantManager = tenantManager;
Cache = dbSettingsManagerCache.Cache;
{
ServiceProvider = serviceProvider;
DbSettingsManagerCache = dbSettingsManagerCache;
AuthContext = authContext;
TenantManager = tenantManager;
Cache = dbSettingsManagerCache.Cache;
Log = option.CurrentValue;
WebstudioDbContext = dbContextManager.Value;
}
WebstudioDbContext = dbContextManager.Value;
}
private int TenantID
{
get { return TenantManager.GetCurrentTenant().TenantId; }
@ -152,7 +151,7 @@ namespace ASC.Core.Data
private Guid CurrentUserID
{
get { return AuthContext.CurrentAccount.ID; }
}
}
public bool SaveSettings<T>(T settings, int tenantId) where T : ISettings
{
@ -167,7 +166,7 @@ namespace ASC.Core.Data
public void ClearCache<T>(int tenantId) where T : class, ISettings
{
var settings = LoadSettings<T>(tenantId);
var key = settings.ID.ToString() + tenantId + Guid.Empty;
var key = settings.ID.ToString() + tenantId + Guid.Empty;
DbSettingsManagerCache.Remove(key);
}
@ -179,43 +178,43 @@ namespace ASC.Core.Data
{
var key = settings.ID.ToString() + tenantId + userId;
var data = Serialize(settings);
var def = (T)settings.GetDefault(ServiceProvider);
var def = (T)settings.GetDefault(ServiceProvider);
var defaultData = Serialize(def);
var tr = WebstudioDbContext.Database.BeginTransaction();
var tr = WebstudioDbContext.Database.BeginTransaction();
if (data.SequenceEqual(defaultData))
{
// remove default settings
var s = WebstudioDbContext.WebstudioSettings
.Where(r => r.Id == settings.ID)
.Where(r => r.TenantId == tenantId)
.Where(r => r.UserId == userId)
.FirstOrDefault();
if (s != null)
{
WebstudioDbContext.WebstudioSettings.Remove(s);
{
// remove default settings
var s = WebstudioDbContext.WebstudioSettings
.Where(r => r.Id == settings.ID)
.Where(r => r.TenantId == tenantId)
.Where(r => r.UserId == userId)
.FirstOrDefault();
if (s != null)
{
WebstudioDbContext.WebstudioSettings.Remove(s);
}
}
else
{
var s = new DbWebstudioSettings
{
Id = settings.ID,
UserId = userId,
TenantId = tenantId,
Data = data
};
{
var s = new DbWebstudioSettings
{
Id = settings.ID,
UserId = userId,
TenantId = tenantId,
Data = data
};
WebstudioDbContext.AddOrUpdate(r => r.WebstudioSettings, s);
}
WebstudioDbContext.SaveChanges();
tr.Commit();
}
WebstudioDbContext.SaveChanges();
tr.Commit();
DbSettingsManagerCache.Remove(key);
Cache.Insert(key, settings, expirationTimeout);
@ -232,19 +231,19 @@ namespace ASC.Core.Data
{
var settingsInstance = Activator.CreateInstance<T>();
var key = settingsInstance.ID.ToString() + tenantId + userId;
var def = (T)settingsInstance.GetDefault(ServiceProvider);
var def = (T)settingsInstance.GetDefault(ServiceProvider);
try
{
var settings = Cache.Get<T>(key);
if (settings != null) return settings;
var result = WebstudioDbContext.WebstudioSettings
.Where(r => r.Id == settingsInstance.ID)
.Where(r => r.TenantId == tenantId)
.Where(r => r.UserId == userId)
.Select(r => r.Data)
.FirstOrDefault();
if (settings != null) return settings;
var result = WebstudioDbContext.WebstudioSettings
.Where(r => r.Id == settingsInstance.ID)
.Where(r => r.TenantId == tenantId)
.Where(r => r.UserId == userId)
.Select(r => r.Data)
.FirstOrDefault();
if (result != null)
{
@ -253,7 +252,7 @@ namespace ASC.Core.Data
else
{
settings = def;
}
}
Cache.Insert(key, settings, expirationTimeout);
return settings;
@ -264,7 +263,7 @@ namespace ASC.Core.Data
}
return def;
}
public T Load<T>() where T : class, ISettings
{
return LoadSettings<T>(TenantID);
@ -318,19 +317,19 @@ namespace ASC.Core.Data
public void ClearCache<T>() where T : class, ISettings
{
ClearCache<T>(TenantID);
}
}
private T Deserialize<T>(string data)
{
using var stream = new MemoryStream(Encoding.UTF8.GetBytes(data));
var settings = GetJsonSerializer(typeof(T)).ReadObject(stream);
using var stream = new MemoryStream(Encoding.UTF8.GetBytes(data));
var settings = GetJsonSerializer(typeof(T)).ReadObject(stream);
return (T)settings;
}
private string Serialize(ISettings settings)
{
using var stream = new MemoryStream();
GetJsonSerializer(settings.GetType()).WriteObject(stream, settings);
using var stream = new MemoryStream();
GetJsonSerializer(settings.GetType()).WriteObject(stream, settings);
return Encoding.UTF8.GetString(stream.ToArray());
}
@ -345,14 +344,14 @@ namespace ASC.Core.Data
return jsonSerializers[type];
}
}
}
}
public static class DbSettingsManagerExtension
{
public static IServiceCollection AddDbSettingsManagerService(this IServiceCollection services)
{
services.TryAddSingleton<DbSettingsManagerCache>();
services.TryAddScoped<DbSettingsManager>();
public static DIHelper AddDbSettingsManagerService(this DIHelper services)
{
services.TryAddSingleton<DbSettingsManagerCache>();
services.TryAddScoped<DbSettingsManager>();
services.TryAddScoped<IConfigureOptions<DbSettingsManager>, ConfigureDbSettingsManager>();
return services.AddWebstudioDbContextService();

View File

@ -1,7 +1,7 @@
using ASC.Core.Common.EF.Model;
using ASC.Common;
using ASC.Core.Common.EF.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace ASC.Core.Common.EF.Context
{
@ -17,7 +17,7 @@ namespace ASC.Core.Common.EF.Context
public static class AccountLinkContextExtension
{
public static IServiceCollection AddAccountLinkContextService(this IServiceCollection services)
public static DIHelper AddAccountLinkContextService(this DIHelper services)
{
return services.AddDbContextManagerService<AccountLinkContext>();
}

View File

@ -1,6 +1,7 @@

using ASC.Common;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace ASC.Core.Common.EF
{
@ -30,7 +31,7 @@ namespace ASC.Core.Common.EF
public static class CoreDbExtension
{
public static IServiceCollection AddCoreDbContextService(this IServiceCollection services)
public static DIHelper AddCoreDbContextService(this DIHelper services)
{
return services.AddDbContextManagerService<CoreDbContext>();
}

View File

@ -1,7 +1,7 @@
using ASC.Core.Common.EF.Model;
using ASC.Common;
using ASC.Core.Common.EF.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace ASC.Core.Common.EF.Context
{
@ -27,7 +27,7 @@ namespace ASC.Core.Common.EF.Context
public static class DbContextExtension
{
public static IServiceCollection AddDbContextService(this IServiceCollection services)
public static DIHelper AddDbContextService(this DIHelper services)
{
return services.AddDbContextManagerService<DbContext>();
}

View File

@ -1,7 +1,8 @@
using System;
using System.Collections.Generic;
using Microsoft.Extensions.DependencyInjection;
using ASC.Common;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
@ -70,7 +71,7 @@ namespace ASC.Core.Common.EF
public static class DbContextManagerExtension
{
public static IServiceCollection AddDbContextManagerService<T>(this IServiceCollection services) where T : BaseDbContext, new()
public static DIHelper AddDbContextManagerService<T>(this DIHelper services) where T : BaseDbContext, new()
{
services.TryAddScoped<DbContextManager<T>>();
services.TryAddScoped<MultiRegionalDbContextManager<T>>();

View File

@ -1,7 +1,7 @@
using ASC.Core.Common.EF.Model;
using ASC.Common;
using ASC.Core.Common.EF.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace ASC.Core.Common.EF.Context
{
@ -22,7 +22,7 @@ namespace ASC.Core.Common.EF.Context
public static class FeedDbExtension
{
public static IServiceCollection AddFeedDbService(this IServiceCollection services)
public static DIHelper AddFeedDbService(this DIHelper services)
{
return services.AddDbContextManagerService<FeedDbContext>();
}

View File

@ -1,7 +1,7 @@
using ASC.Core.Common.EF.Model;
using ASC.Common;
using ASC.Core.Common.EF.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace ASC.Core.Common.EF.Context
{
@ -17,7 +17,7 @@ namespace ASC.Core.Common.EF.Context
public static class FilesDbExtension
{
public static IServiceCollection AddFilesDbContextService(this IServiceCollection services)
public static DIHelper AddFilesDbContextService(this DIHelper services)
{
return services.AddDbContextManagerService<FilesDbContext>();
}

View File

@ -1,7 +1,7 @@
using ASC.Core.Common.EF.Model.Mail;
using ASC.Common;
using ASC.Core.Common.EF.Model.Mail;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace ASC.Core.Common.EF.Context
{
@ -22,7 +22,7 @@ namespace ASC.Core.Common.EF.Context
}
public static class MailDbExtension
{
public static IServiceCollection AddMailDbContextService(this IServiceCollection services)
public static DIHelper AddMailDbContextService(this DIHelper services)
{
return services.AddDbContextManagerService<MailDbContext>();
}

View File

@ -1,8 +1,8 @@

using ASC.Common;
using ASC.Core.Common.EF.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace ASC.Core.Common.EF.Context
{
@ -22,7 +22,7 @@ namespace ASC.Core.Common.EF.Context
public static class MessagesContextExtension
{
public static IServiceCollection AddMessagesContextService(this IServiceCollection services)
public static DIHelper AddMessagesContextService(this DIHelper services)
{
return services.AddDbContextManagerService<MessagesContext>();
}

View File

@ -1,7 +1,7 @@
using ASC.Core.Common.EF.Model;
using ASC.Common;
using ASC.Core.Common.EF.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace ASC.Core.Common.EF.Context
{
@ -13,7 +13,7 @@ namespace ASC.Core.Common.EF.Context
public static class NotifyDbExtension
{
public static IServiceCollection AddNotifyDbContext(this IServiceCollection services)
public static DIHelper AddNotifyDbContext(this DIHelper services)
{
return services.AddDbContextManagerService<NotifyDbContext>();
}

View File

@ -1,7 +1,7 @@
using ASC.Core.Common.EF.Model.Resource;
using ASC.Common;
using ASC.Core.Common.EF.Model.Resource;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace ASC.Core.Common.EF.Context
{
@ -25,7 +25,7 @@ namespace ASC.Core.Common.EF.Context
public static class ResourceDbExtension
{
public static IServiceCollection AddResourceDbService(this IServiceCollection services)
public static DIHelper AddResourceDbService(this DIHelper services)
{
return services.AddDbContextManagerService<ResourceDbContext>();
}

View File

@ -1,7 +1,7 @@
using ASC.Core.Common.EF.Model;
using ASC.Common;
using ASC.Core.Common.EF.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace ASC.Core.Common.EF.Context
{
@ -38,7 +38,7 @@ namespace ASC.Core.Common.EF.Context
public static class TenantDbExtension
{
public static IServiceCollection AddTenantDbContextService(this IServiceCollection services)
public static DIHelper AddTenantDbContextService(this DIHelper services)
{
return services.AddDbContextManagerService<TenantDbContext>();
}

View File

@ -1,5 +1,6 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using ASC.Common;
using Microsoft.EntityFrameworkCore;
namespace ASC.Core.Common.EF
{
@ -32,7 +33,7 @@ namespace ASC.Core.Common.EF
public static class UserDbExtension
{
public static IServiceCollection AddUserDbContextService(this IServiceCollection services)
public static DIHelper AddUserDbContextService(this DIHelper services)
{
return services.AddDbContextManagerService<UserDbContext>();
}

View File

@ -1,7 +1,7 @@
using ASC.Core.Common.EF.Model;
using ASC.Common;
using ASC.Core.Common.EF.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace ASC.Core.Common.EF.Context
{
@ -14,7 +14,7 @@ namespace ASC.Core.Common.EF.Context
public static class VoipDbExtension
{
public static IServiceCollection AddVoipDbContextService(this IServiceCollection services)
public static DIHelper AddVoipDbContextService(this DIHelper services)
{
return services.AddDbContextManagerService<VoipDbContext>();
}

View File

@ -1,7 +1,7 @@
using ASC.Core.Common.EF.Model;
using ASC.Common;
using ASC.Core.Common.EF.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace ASC.Core.Common.EF.Context
{
@ -9,6 +9,7 @@ namespace ASC.Core.Common.EF.Context
{
public DbSet<DbWebstudioSettings> WebstudioSettings { get; set; }
public DbSet<DbWebstudioUserVisit> WebstudioUserVisit { get; set; }
public DbSet<DbWebstudioIndex> WebstudioIndex { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
@ -20,7 +21,7 @@ namespace ASC.Core.Common.EF.Context
public static class WebstudioDbExtension
{
public static IServiceCollection AddWebstudioDbContextService(this IServiceCollection services)
public static DIHelper AddWebstudioDbContextService(this DIHelper services)
{
return services.AddDbContextManagerService<WebstudioDbContext>();
}

View File

@ -0,0 +1,17 @@
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ASC.Core.Common.EF.Model
{
[Table("webstudio_index")]
public class DbWebstudioIndex
{
[Key]
[Column("index_name")]
public string IndexName { get; set; }
[Column("last_modified")]
public DateTime LastModified { get; set; }
}
}

View File

@ -29,6 +29,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Security;
using ASC.Common;
using ASC.Core.Billing;
using ASC.Core.Caching;
using ASC.Core.Data;
@ -37,7 +38,6 @@ using ASC.Core.Tenants;
using ASC.Core.Users;
using ASC.Security.Cryptography;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace ASC.Core
@ -295,9 +295,9 @@ namespace ASC.Core
public static class HostedSolutionExtension
{
public static IServiceCollection AddHostedSolutionService(this IServiceCollection services)
public static DIHelper AddHostedSolutionService(this DIHelper services)
{
services.AddScoped<IConfigureOptions<HostedSolution>, ConfigureHostedSolution>();
services.TryAddScoped<IConfigureOptions<HostedSolution>, ConfigureHostedSolution>();
return services
.AddUserFormatter()

View File

@ -26,29 +26,29 @@
using System;
using System.Collections.Generic;
using System.ServiceModel;
using ASC.Core.Common.Notify.Jabber;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System.ServiceModel;
using ASC.Common;
using ASC.Core.Common.Notify.Jabber;
namespace ASC.Core.Notify.Jabber
{
public class JabberServiceClient
{
private static readonly TimeSpan Timeout = TimeSpan.FromMinutes(2);
private static DateTime lastErrorTime = default;
public UserManager UserManager { get; }
public AuthContext AuthContext { get; }
public TenantManager TenantManager { get; }
public JabberServiceClient(UserManager userManager, AuthContext authContext, TenantManager tenantManager)
{
UserManager = userManager;
AuthContext = authContext;
TenantManager = tenantManager;
}
private static DateTime lastErrorTime = default;
public UserManager UserManager { get; }
public AuthContext AuthContext { get; }
public TenantManager TenantManager { get; }
public JabberServiceClient(UserManager userManager, AuthContext authContext, TenantManager tenantManager)
{
UserManager = userManager;
AuthContext = authContext;
TenantManager = tenantManager;
}
private static bool IsServiceProbablyNotAvailable()
{
@ -100,15 +100,15 @@ namespace ASC.Core.Notify.Jabber
byte result = 4;
if (IsServiceProbablyNotAvailable()) throw new Exception();
using var service = GetService();
try
{
result = service.AddXmppConnection(connectionId, GetCurrentUserName(), state, GetCurrentTenantId());
}
catch (Exception error)
{
ProcessError(error);
}
using var service = GetService();
try
{
result = service.AddXmppConnection(connectionId, GetCurrentUserName(), state, GetCurrentTenantId());
}
catch (Exception error)
{
ProcessError(error);
}
return result;
}
@ -139,7 +139,7 @@ namespace ASC.Core.Notify.Jabber
try
{
if (IsServiceProbablyNotAvailable()) return defaultState;
using var service = GetService();
using var service = GetService();
return service.GetState(GetCurrentTenantId(), userName);
}
catch (Exception error)
@ -155,7 +155,7 @@ namespace ASC.Core.Notify.Jabber
try
{
if (IsServiceProbablyNotAvailable()) throw new Exception();
using var service = GetService();
using var service = GetService();
return service.SendState(GetCurrentTenantId(), GetCurrentUserName(), state);
}
catch (Exception error)
@ -171,7 +171,7 @@ namespace ASC.Core.Notify.Jabber
try
{
if (IsServiceProbablyNotAvailable()) throw new Exception();
using var service = GetService();
using var service = GetService();
states = service.GetAllStates(GetCurrentTenantId(), GetCurrentUserName());
}
catch (Exception error)
@ -187,7 +187,7 @@ namespace ASC.Core.Notify.Jabber
try
{
if (IsServiceProbablyNotAvailable()) throw new Exception();
using var service = GetService();
using var service = GetService();
messages = service.GetRecentMessages(GetCurrentTenantId(), GetCurrentUserName(), to, id);
}
catch (Exception error)
@ -202,7 +202,7 @@ namespace ASC.Core.Notify.Jabber
try
{
if (IsServiceProbablyNotAvailable()) throw new Exception();
using var service = GetService();
using var service = GetService();
service.Ping(AuthContext.CurrentAccount.ID.ToString(), GetCurrentTenantId(), GetCurrentUserName(), state);
}
catch (Exception error)
@ -238,17 +238,17 @@ namespace ASC.Core.Notify.Jabber
{
return new JabberServiceClientWcf();
}
}
public static class JabberServiceClientExtension
{
public static IServiceCollection AddJabberServiceClient(this IServiceCollection services)
{
services.TryAddScoped<JabberServiceClient>();
return services
.AddUserManagerService()
.AddAuthContextService()
.AddTenantManagerService();
}
}
}
public static class JabberServiceClientExtension
{
public static DIHelper AddJabberServiceClient(this DIHelper services)
{
services.TryAddScoped<JabberServiceClient>();
return services
.AddUserManagerService()
.AddAuthContextService()
.AddTenantManagerService();
}
}
}

View File

@ -26,19 +26,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using ASC.Core.Users;
using ASC.Notify.Recipients;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System.Linq;
using ASC.Common;
using ASC.Core.Users;
using ASC.Notify.Recipients;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace ASC.Core.Notify
{
public class RecipientProviderImpl : IRecipientProvider
{
public UserManager UserManager { get; }
public RecipientProviderImpl(UserManager userManager) =>
{
public UserManager UserManager { get; }
public RecipientProviderImpl(UserManager userManager) =>
(UserManager) = (userManager);
public virtual IRecipient GetRecipient(string id)
{
@ -156,13 +158,13 @@ namespace ASC.Core.Notify
}
return false;
}
}
}
public static class RecipientProviderImplExtension
{
public static IServiceCollection AddRecipientProviderImplService(this IServiceCollection services)
{
services.TryAddScoped(typeof(IRecipientProvider), typeof(RecipientProviderImpl));
public static DIHelper AddRecipientProviderImplService(this DIHelper services)
{
services.TryAddScoped(typeof(IRecipientProvider), typeof(RecipientProviderImpl));
return services
.AddUserManagerService();

View File

@ -29,16 +29,19 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Amazon;
using Amazon.Runtime;
using Amazon.SimpleEmail;
using Amazon.SimpleEmail.Model;
using ASC.Common;
using ASC.Common.Logging;
using ASC.Common.Utils;
using ASC.Notify.Messages;
using ASC.Notify.Patterns;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
namespace ASC.Core.Notify.Senders
@ -230,7 +233,7 @@ namespace ASC.Core.Notify.Senders
public static class AWSSenderExtension
{
public static IServiceCollection AddAWSSenderService(this IServiceCollection services)
public static DIHelper AddAWSSenderService(this DIHelper services)
{
services.TryAddSingleton<AWSSender>();
return services

View File

@ -26,12 +26,14 @@
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Text.RegularExpressions;
using ASC.Common;
using ASC.Common.Logging;
using ASC.Core.Notify.Jabber;
using ASC.Notify.Messages;
using ASC.Notify.Messages;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
namespace ASC.Core.Notify.Senders
@ -77,7 +79,7 @@ namespace ASC.Core.Notify.Senders
public static class JabberSenderExtension
{
public static IServiceCollection AddJabberSenderService(this IServiceCollection services)
public static DIHelper AddJabberSenderService(this DIHelper services)
{
services.TryAddSingleton<JabberSender>();
return services.AddJabberServiceClient();

View File

@ -28,16 +28,20 @@ using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using ASC.Common;
using ASC.Common.Logging;
using ASC.Common.Utils;
using ASC.Notify.Messages;
using ASC.Notify.Patterns;
using MailKit;
using MailKit.Security;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using MimeKit;
namespace ASC.Core.Notify.Senders
@ -320,7 +324,7 @@ namespace ASC.Core.Notify.Senders
public static class SmtpSenderExtension
{
public static IServiceCollection AddSmtpSenderService(this IServiceCollection services)
public static DIHelper AddSmtpSenderService(this DIHelper services)
{
services.TryAddSingleton<SmtpSender>();
return services

View File

@ -30,59 +30,60 @@ using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.ServiceModel;
using System.Text;
using System.Text;
using ASC.Common;
using ASC.Common.Logging;
using ASC.Core.Common.Notify.Jabber;
using ASC.Core.Common.Notify.Jabber;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
namespace ASC.Core.Notify.Signalr
{
public class SignalrServiceClient
public class ConfigureSignalrServiceClient : IConfigureNamedOptions<SignalrServiceClient>
{
private static readonly TimeSpan Timeout;
private readonly ILog Log;
private static DateTime lastErrorTime;
public readonly bool EnableSignalr;
private readonly string CoreMachineKey;
private readonly string Url;
private readonly bool JabberReplaceDomain;
private readonly string JabberReplaceFromDomain;
private readonly string JabberReplaceToDomain;
private readonly string hub;
public TenantManager TenantManager { get; }
public CoreSettings CoreSettings { get; }
public IConfiguration Configuration { get; }
public IOptionsMonitor<ILog> Options { get; }
static SignalrServiceClient()
public ConfigureSignalrServiceClient(
TenantManager tenantManager,
CoreSettings coreSettings,
IConfiguration configuration,
IOptionsMonitor<ILog> options)
{
Timeout = TimeSpan.FromSeconds(1);
}
public SignalrServiceClient(string hub, TenantManager tenantManager, CoreSettings coreSettings, IConfiguration configuration, IOptionsMonitor<ILog> options)
{
Log = options.CurrentValue;
this.hub = hub.Trim('/');
TenantManager = tenantManager;
CoreSettings = coreSettings;
CoreMachineKey = configuration["core:machinekey"];
Url = configuration["web:hub:internal"];
EnableSignalr = !string.IsNullOrEmpty(Url);
Configuration = configuration;
Options = options;
}
public void Configure(string name, SignalrServiceClient options)
{
options.Log = Options.CurrentValue;
options.hub = name.Trim('/');
options.TenantManager = TenantManager;
options.CoreSettings = CoreSettings;
options.CoreMachineKey = Configuration["core:machinekey"];
options.Url = Configuration["web:hub:internal"];
options.EnableSignalr = !string.IsNullOrEmpty(options.Url);
try
{
var replaceSetting = configuration["jabber:replace-domain"];
var replaceSetting = Configuration["jabber:replace-domain"];
if (!string.IsNullOrEmpty(replaceSetting))
{
JabberReplaceDomain = true;
options.JabberReplaceDomain = true;
var q =
replaceSetting.Split(new[] { "->" }, StringSplitOptions.RemoveEmptyEntries)
.Select(s => s.Trim().ToLowerInvariant())
.ToList();
JabberReplaceFromDomain = q.ElementAt(0);
JabberReplaceToDomain = q.ElementAt(1);
options.JabberReplaceFromDomain = q.ElementAt(0);
options.JabberReplaceToDomain = q.ElementAt(1);
}
}
catch (Exception)
@ -90,6 +91,40 @@ namespace ASC.Core.Notify.Signalr
}
}
public void Configure(SignalrServiceClient options)
{
Configure("default", options);
}
}
public class SignalrServiceClient
{
private static readonly TimeSpan Timeout;
internal ILog Log;
private static DateTime lastErrorTime;
public bool EnableSignalr;
internal string CoreMachineKey;
internal string Url;
internal bool JabberReplaceDomain;
internal string JabberReplaceFromDomain;
internal string JabberReplaceToDomain;
internal string hub;
public TenantManager TenantManager { get; internal set; }
public CoreSettings CoreSettings { get; internal set; }
static SignalrServiceClient()
{
Timeout = TimeSpan.FromSeconds(1);
}
public SignalrServiceClient()
{
}
public void SendMessage(string callerUserName, string calleeUserName, string messageText, int tenantId,
string domain)
{
@ -355,4 +390,17 @@ namespace ASC.Core.Notify.Signalr
return string.Format("ASC {0}:{1}:{2}", pkey, now, hash);
}
}
public static class SignalrServiceClientExtension
{
public static DIHelper AddSignalrServiceClient(this DIHelper services)
{
services.TryAddScoped<SignalrServiceClient>();
services.TryAddScoped<IConfigureOptions<SignalrServiceClient>, ConfigureSignalrServiceClient>();
return services
.AddTenantManagerService()
.AddCoreSettingsService();
}
}
}

View File

@ -28,13 +28,12 @@ using System;
using System.Globalization;
using System.Web;
using ASC.Common;
using ASC.Common.Logging;
using ASC.Core.Tenants;
using ASC.Security.Cryptography;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
namespace ASC.Core.Security.Authentication
@ -141,7 +140,7 @@ namespace ASC.Core.Security.Authentication
public static class CookieStorageExtension
{
public static IServiceCollection AddCookieStorageService(this IServiceCollection services)
public static DIHelper AddCookieStorageService(this DIHelper services)
{
services.TryAddScoped<CookieStorage>();

View File

@ -25,11 +25,11 @@
using System;
using System.Collections.Generic;
using ASC.Core.Security.Authorizing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System.Collections.Generic;
using ASC.Core.Security.Authorizing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace ASC.Common.Security.Authorizing
{
public class AzManager
@ -44,7 +44,7 @@ namespace ASC.Common.Security.Authorizing
public AzManager(IRoleProvider roleProvider, IPermissionProvider permissionProvider)
: this()
{
{
this.roleProvider = roleProvider ?? throw new ArgumentNullException("roleProvider");
this.permissionProvider = permissionProvider ?? throw new ArgumentNullException("permissionProvider");
}
@ -103,9 +103,9 @@ namespace ASC.Common.Security.Authorizing
internal IEnumerable<ISubject> GetSubjects(ISubject subject, ISecurityObjectId objectId, ISecurityObjectProvider securityObjProvider)
{
var subjects = new List<ISubject>
{
subject
var subjects = new List<ISubject>
{
subject
};
subjects.AddRange(
roleProvider.GetRoles(subject)
@ -146,17 +146,17 @@ namespace ASC.Common.Security.Authorizing
}
#endregion
}
public static class AzManagerConfigExtension
{
public static IServiceCollection AddAzManagerService(this IServiceCollection services)
{
services.TryAddScoped<AzManager>();
return services
.AddPermissionProviderService()
.AddRoleProviderService();
}
}
}
public static class AzManagerConfigExtension
{
public static DIHelper AddAzManagerService(this DIHelper services)
{
services.TryAddScoped<AzManager>();
return services
.AddPermissionProviderService()
.AddRoleProviderService();
}
}
}

View File

@ -26,23 +26,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using ASC.Common.Security;
using ASC.Common.Security.Authorizing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System.Linq;
using ASC.Common;
using ASC.Common.Security;
using ASC.Common.Security.Authorizing;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace ASC.Core.Security.Authorizing
{
class PermissionProvider : IPermissionProvider
{
private AuthorizationManager AuthorizationManager { get; }
public PermissionProvider(AuthorizationManager authorizationManager)
{
AuthorizationManager = authorizationManager;
}
{
private AuthorizationManager AuthorizationManager { get; }
public PermissionProvider(AuthorizationManager authorizationManager)
{
AuthorizationManager = authorizationManager;
}
public IEnumerable<Ace> GetAcl(ISubject subject, IAction action, ISecurityObjectId objectId, ISecurityObjectProvider secObjProvider)
{
if (subject == null) throw new ArgumentNullException("subject");
@ -52,14 +54,14 @@ namespace ASC.Core.Security.Authorizing
.GetAcesWithInherits(subject.ID, action.ID, objectId, secObjProvider)
.Select(r => new Ace(r.ActionId, r.Reaction));
}
}
public static class PermissionProviderConfigExtension
{
public static IServiceCollection AddPermissionProviderService(this IServiceCollection services)
{
services.TryAddScoped(typeof(IPermissionProvider), typeof(PermissionProvider));
return services.AddAuthorizationManagerService();
}
}
}
public static class PermissionProviderConfigExtension
{
public static DIHelper AddPermissionProviderService(this DIHelper services)
{
services.TryAddScoped(typeof(IPermissionProvider), typeof(PermissionProvider));
return services.AddAuthorizationManagerService();
}
}
}

View File

@ -26,12 +26,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq;
using ASC.Common;
using ASC.Common.Security;
using ASC.Common.Security.Authentication;
using ASC.Common.Security.Authorizing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using ASC.Common.Security.Authorizing;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Constants = ASC.Core.Configuration.Constants;
namespace ASC.Core.Security.Authorizing
@ -121,14 +124,14 @@ namespace ASC.Core.Security.Authorizing
DenyAction = denyAction;
}
}
}
public static class PermissionResolverConfigExtention
{
public static IServiceCollection AddPermissionResolverService(this IServiceCollection services)
{
services.TryAddScoped(typeof(IPermissionResolver), typeof(PermissionResolver));
return services.AddAzManagerService();
}
}
public static class PermissionResolverConfigExtention
{
public static DIHelper AddPermissionResolverService(this DIHelper services)
{
services.TryAddScoped(typeof(IPermissionResolver), typeof(PermissionResolver));
return services.AddAzManagerService();
}
}
}

View File

@ -26,14 +26,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq;
using ASC.Common;
using ASC.Common.Security;
using ASC.Common.Security.Authentication;
using ASC.Common.Security.Authorizing;
using ASC.Core.Users;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using ASC.Core.Users;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace ASC.Core.Security.Authorizing
{
class RoleProvider : IRoleProvider
@ -86,9 +89,9 @@ namespace ASC.Core.Security.Authorizing
public static class RoleProviderConfigExtention
{
public static IServiceCollection AddRoleProviderService(this IServiceCollection services)
public static DIHelper AddRoleProviderService(this DIHelper services)
{
services.TryAddScoped(typeof(IRoleProvider), typeof(RoleProvider));
services.TryAddScoped(typeof(IRoleProvider), typeof(RoleProvider));
return services;
}
}

View File

@ -25,20 +25,19 @@
using System;
using System.Text;
using System.Text;
using ASC.Common;
using ASC.Common.Logging;
using ASC.Core;
using ASC.Core.Users;
using ASC.Web.Studio.Utility;
using ASC.Web.Studio.Utility;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Options;
using static ASC.Security.Cryptography.EmailValidationKeyProvider;
namespace ASC.Security.Cryptography
@ -171,7 +170,7 @@ namespace ASC.Security.Cryptography
case ConfirmType.LinkInvite:
checkKeyResult = provider.ValidateEmailKey(Type.ToString() + (int)EmplType, Key, provider.ValidInterval);
break;
case ConfirmType.PortalOwnerChange:
case ConfirmType.PortalOwnerChange:
checkKeyResult = provider.ValidateEmailKey(Email + Type + UiD.HasValue, Key, provider.ValidInterval);
break;
case ConfirmType.EmailChange:
@ -251,7 +250,7 @@ namespace ASC.Security.Cryptography
public static class EmailValidationKeyProviderExtension
{
public static IServiceCollection AddEmailValidationKeyProviderService(this IServiceCollection services)
public static DIHelper AddEmailValidationKeyProviderService(this DIHelper services)
{
services.TryAddScoped<EmailValidationKeyProvider>();

View File

@ -24,13 +24,14 @@
*/
using System;
using System;
using ASC.Common;
using ASC.Common.Logging;
using ASC.Core.Common.EF;
using ASC.Core.Common.EF.Context;
using ASC.Core.Data;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using ASC.Core.Common.EF;
using ASC.Core.Common.EF.Context;
using ASC.Core.Data;
using Microsoft.Extensions.Options;
namespace ASC.Core.Common.Settings
@ -40,9 +41,9 @@ namespace ASC.Core.Common.Settings
public SettingsManager(
IServiceProvider serviceProvider,
DbSettingsManagerCache dbSettingsManagerCache,
IOptionsMonitor<ILog> option,
AuthContext authContext,
TenantManager tenantManager,
IOptionsMonitor<ILog> option,
AuthContext authContext,
TenantManager tenantManager,
DbContextManager<WebstudioDbContext> dbContextManager)
: base(serviceProvider, dbSettingsManagerCache, option, authContext, tenantManager, dbContextManager)
{
@ -52,7 +53,7 @@ namespace ASC.Core.Common.Settings
public static class SettingsManagerExtention
{
public static IServiceCollection AddSettingsManagerService(this IServiceCollection services)
public static DIHelper AddSettingsManagerService(this DIHelper services)
{
services.TryAddScoped<SettingsManager>();

View File

@ -27,10 +27,11 @@
using System;
using System.Linq;
using System.Runtime.Serialization;
using ASC.Common;
using ASC.Core.Common.Settings;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace ASC.Core.Tenants
{
@ -126,7 +127,7 @@ namespace ASC.Core.Tenants
public static class TenantCookieSettingsExtention
{
public static IServiceCollection AddTenantCookieSettingsService(this IServiceCollection services)
public static DIHelper AddTenantCookieSettingsService(this DIHelper services)
{
services.TryAddScoped<TenantCookieSettingsHelper>();
return services.AddSettingsManagerService();

View File

@ -24,21 +24,19 @@
*/
using System;
using ASC.Common.Utils;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System;
using ASC.Common;
using ASC.Common.Utils;
using Microsoft.Extensions.Options;
namespace ASC.Core.Tenants
{
{
class ConfigureTenantUtil : IConfigureNamedOptions<TenantUtil>
{
{
public IOptionsSnapshot<TenantManager> TenantManager { get; }
public TimeZoneConverter TimeZoneConverter { get; }
public TimeZoneConverter TimeZoneConverter { get; }
public ConfigureTenantUtil(
IOptionsSnapshot<TenantManager> tenantManager,
TimeZoneConverter timeZoneConverter
@ -70,10 +68,10 @@ namespace ASC.Core.Tenants
{
}
public TenantUtil(TenantManager tenantManager, TimeZoneConverter timeZoneConverter)
{
TenantManager = tenantManager;
TimeZoneConverter = timeZoneConverter;
public TenantUtil(TenantManager tenantManager, TimeZoneConverter timeZoneConverter)
{
TenantManager = tenantManager;
TimeZoneConverter = timeZoneConverter;
}
@ -82,11 +80,11 @@ namespace ASC.Core.Tenants
return DateTimeFromUtc(TimeZoneConverter.GetTimeZone(TenantManager.GetCurrentTenant().TimeZone), utc);
}
public DateTime DateTimeFromUtc(string timeZone, DateTime utc)
{
return DateTimeFromUtc(TimeZoneConverter.GetTimeZone(timeZone), utc);
}
public DateTime DateTimeFromUtc(string timeZone, DateTime utc)
{
return DateTimeFromUtc(TimeZoneConverter.GetTimeZone(timeZone), utc);
}
public static DateTime DateTimeFromUtc(TimeZoneInfo timeZone, DateTime utc)
{
if (utc.Kind != DateTimeKind.Utc)
@ -139,16 +137,16 @@ namespace ASC.Core.Tenants
{
return DateTimeNow(TimeZoneConverter.GetTimeZone(timeZone));
}
}
public static class TenantUtilExtention
{
public static IServiceCollection AddTenantUtilService(this IServiceCollection services)
{
services.TryAddScoped<TenantUtil>();
}
public static class TenantUtilExtention
{
public static DIHelper AddTenantUtilService(this DIHelper services)
{
services.TryAddScoped<TenantUtil>();
services.TryAddScoped<IConfigureOptions<TenantUtil>, ConfigureTenantUtil>();
return services.AddTenantManagerService();
}
return services.AddTenantManagerService();
}
}
}

View File

@ -24,10 +24,12 @@
*/
using System;
using System;
using ASC.Common;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Action = ASC.Common.Security.Authorizing.Action;
using AuthConst = ASC.Common.Security.Authorizing.Constants;
@ -145,8 +147,8 @@ namespace ASC.Core.Users
public static class ConstantsConfigFactory
{
public static IServiceCollection AddConstantsService(this IServiceCollection services)
{
public static DIHelper AddConstantsService(this DIHelper services)
{
services.TryAddSingleton<Constants>();
return services;
}

View File

@ -27,11 +27,11 @@
using System;
using System.Runtime.Serialization;
using System.Web;
using ASC.Common;
using ASC.Core;
using ASC.Core.Common.Settings;
using ASC.Core.Users;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace ASC.Web.Core.Users
{
@ -98,7 +98,7 @@ namespace ASC.Web.Core.Users
public static class DisplayUserSettingsExtention
{
public static IServiceCollection AddDisplayUserSettingsService(this IServiceCollection services)
public static DIHelper AddDisplayUserSettingsService(this DIHelper services)
{
services.TryAddScoped<DisplayUserSettingsHelper>();

View File

@ -27,12 +27,12 @@
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using ASC.Common;
using Microsoft.Extensions.Configuration;
namespace ASC.Core.Users
{
public class UserFormatter : IComparer<UserInfo>
@ -40,12 +40,12 @@ namespace ASC.Core.Users
private readonly DisplayUserNameFormat format;
private static bool forceFormatChecked;
private static string forceFormat;
public UserFormatter(IConfiguration configuration)
{
Configuration = configuration;
UserNameRegex = new Regex(Configuration["core:username:regex"] ?? "");
}
public UserFormatter(IConfiguration configuration)
{
Configuration = configuration;
UserNameRegex = new Regex(Configuration["core:username:regex"] ?? "");
}
public string GetUserName(UserInfo userInfo, DisplayUserNameFormat format)
{
@ -79,10 +79,10 @@ namespace ASC.Core.Users
{
if (x == null && y == null) return 0;
if (x == null && y != null) return -1;
if (x != null && y == null) return +1;
if (x != null && y == null) return +1;
if (format == DisplayUserNameFormat.Default) format = GetUserDisplayDefaultOrder();
int result;
int result;
if (format == DisplayUserNameFormat.FirstLast)
{
result = string.Compare(x.FirstName, y.FirstName, true);
@ -136,23 +136,23 @@ namespace ASC.Core.Users
}
var format = formats[DisplayUserNameFormat.Default];
return format.IndexOf("{0}") < format.IndexOf("{1}") ? DisplayUserNameFormat.FirstLast : DisplayUserNameFormat.LastFirst;
}
public Regex UserNameRegex;
public IConfiguration Configuration { get; }
public bool IsValidUserName(string firstName, string lastName)
{
return UserNameRegex.IsMatch(firstName + lastName);
}
}
public static class UserFormatterExtension
{
public static IServiceCollection AddUserFormatter(this IServiceCollection services)
{
services.TryAddSingleton<UserFormatter>();
return services;
}
public Regex UserNameRegex;
public IConfiguration Configuration { get; }
public bool IsValidUserName(string firstName, string lastName)
{
return UserNameRegex.IsMatch(firstName + lastName);
}
}
public static class UserFormatterExtension
{
public static DIHelper AddUserFormatter(this DIHelper services)
{
services.TryAddSingleton<UserFormatter>();
return services;
}
}
}

View File

@ -25,13 +25,15 @@
using System;
using System.Runtime.Serialization;
using ASC.Core.Common;
using ASC.Core.Common.Settings;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System.Runtime.Serialization;
using ASC.Common;
using ASC.Core.Common;
using ASC.Core.Common.Settings;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace ASC.Web.Core.WhiteLabel
{
[Serializable]
@ -62,59 +64,59 @@ namespace ASC.Web.Core.WhiteLabel
public Guid ID
{
get { return new Guid("{C3602052-5BA2-452A-BD2A-ADD0FAF8EB88}"); }
}
public ISettings GetDefault(IConfiguration configuration)
{
var mailWhiteLabelSettingsHelper = new MailWhiteLabelSettingsHelper(configuration);
}
return new MailWhiteLabelSettings
{
FooterEnabled = true,
FooterSocialEnabled = true,
SupportUrl = mailWhiteLabelSettingsHelper.DefaultMailSupportUrl,
SupportEmail = mailWhiteLabelSettingsHelper.DefaultMailSupportEmail,
SalesEmail = mailWhiteLabelSettingsHelper.DefaultMailSalesEmail,
DemotUrl = mailWhiteLabelSettingsHelper.DefaultMailDemotUrl,
SiteUrl = mailWhiteLabelSettingsHelper.DefaultMailSiteUrl
public ISettings GetDefault(IConfiguration configuration)
{
var mailWhiteLabelSettingsHelper = new MailWhiteLabelSettingsHelper(configuration);
return new MailWhiteLabelSettings
{
FooterEnabled = true,
FooterSocialEnabled = true,
SupportUrl = mailWhiteLabelSettingsHelper.DefaultMailSupportUrl,
SupportEmail = mailWhiteLabelSettingsHelper.DefaultMailSupportEmail,
SalesEmail = mailWhiteLabelSettingsHelper.DefaultMailSalesEmail,
DemotUrl = mailWhiteLabelSettingsHelper.DefaultMailDemotUrl,
SiteUrl = mailWhiteLabelSettingsHelper.DefaultMailSiteUrl
};
}
public bool IsDefault(IConfiguration configuration)
{
if (!(GetDefault(configuration) is MailWhiteLabelSettings defaultSettings)) return false;
return FooterEnabled == defaultSettings.FooterEnabled &&
FooterSocialEnabled == defaultSettings.FooterSocialEnabled &&
SupportUrl == defaultSettings.SupportUrl &&
SupportEmail == defaultSettings.SupportEmail &&
SalesEmail == defaultSettings.SalesEmail &&
DemotUrl == defaultSettings.DemotUrl &&
SiteUrl == defaultSettings.SiteUrl;
}
}
public bool IsDefault(IConfiguration configuration)
{
if (!(GetDefault(configuration) is MailWhiteLabelSettings defaultSettings)) return false;
return FooterEnabled == defaultSettings.FooterEnabled &&
FooterSocialEnabled == defaultSettings.FooterSocialEnabled &&
SupportUrl == defaultSettings.SupportUrl &&
SupportEmail == defaultSettings.SupportEmail &&
SalesEmail == defaultSettings.SalesEmail &&
DemotUrl == defaultSettings.DemotUrl &&
SiteUrl == defaultSettings.SiteUrl;
}
public static MailWhiteLabelSettings Instance(SettingsManager settingsManager)
{
return settingsManager.LoadForDefaultTenant<MailWhiteLabelSettings>();
}
public static bool IsDefault(SettingsManager settingsManager, IConfiguration configuration)
{
return Instance(settingsManager).IsDefault(configuration);
}
public ISettings GetDefault(IServiceProvider serviceProvider)
{
return GetDefault(serviceProvider.GetService<IConfiguration>());
}
}
public class MailWhiteLabelSettingsHelper
{
public MailWhiteLabelSettingsHelper(IConfiguration configuration)
{
Configuration = configuration;
}
}
public static bool IsDefault(SettingsManager settingsManager, IConfiguration configuration)
{
return Instance(settingsManager).IsDefault(configuration);
}
public ISettings GetDefault(IServiceProvider serviceProvider)
{
return GetDefault(serviceProvider.GetService<IConfiguration>());
}
}
public class MailWhiteLabelSettingsHelper
{
public MailWhiteLabelSettingsHelper(IConfiguration configuration)
{
Configuration = configuration;
}
public string DefaultMailSupportUrl
{
get
@ -158,15 +160,15 @@ namespace ASC.Web.Core.WhiteLabel
var url = Configuration["web:teamlab-site"];
return !string.IsNullOrEmpty(url) ? url : "http://www.onlyoffice.com";
}
}
public IConfiguration Configuration { get; }
}
}
public IConfiguration Configuration { get; }
}
public static class MailWhiteLabelSettingsExtention
{
public static IServiceCollection AddMailWhiteLabelSettingsService(this IServiceCollection services)
{
public static DIHelper AddMailWhiteLabelSettingsService(this DIHelper services)
{
services.TryAddSingleton<MailWhiteLabelSettingsHelper>();
return services.AddSettingsManagerService();
}

View File

@ -1,52 +1,52 @@
/*
*
* (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;
/*
*
* (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.Linq;
using ASC.Common.Threading.Progress;
using ASC.Common;
using ASC.Common.Threading.Progress;
using ASC.Core.Users;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
namespace ASC.Data.Reassigns
namespace ASC.Data.Reassigns
{
public class QueueWorker
{
public static Dictionary<string, string> GetHttpHeaders(HttpRequest httpRequest)
{
return httpRequest?.Headers.Keys.ToDictionary(key => key, key => httpRequest.Headers[key].ToString());
public static Dictionary<string, string> GetHttpHeaders(HttpRequest httpRequest)
{
return httpRequest?.Headers.Keys.ToDictionary(key => key, key => httpRequest.Headers[key].ToString());
}
}
public class QueueWorker<T> where T : class, IProgressItem
{
}
public class QueueWorker<T> where T : class, IProgressItem
{
protected readonly ProgressQueue<T> Queue;
public IHttpContextAccessor HttpContextAccessor { get; }
@ -62,49 +62,49 @@ namespace ASC.Data.Reassigns
Queue = optionsQueue.Value;
}
public string GetProgressItemId(int tenantId, Guid userId)
{
return string.Format("{0}_{1}_{2}", tenantId, userId, typeof(T).Name);
}
public T GetProgressItemStatus(int tenantId, Guid userId)
{
var id = GetProgressItemId(tenantId, userId);
return Queue.GetStatus(id) as T;
}
public void Terminate(int tenantId, Guid userId)
{
var item = GetProgressItemStatus(tenantId, userId);
if (item != null)
Queue.Remove(item);
public string GetProgressItemId(int tenantId, Guid userId)
{
return string.Format("{0}_{1}_{2}", tenantId, userId, typeof(T).Name);
}
public T GetProgressItemStatus(int tenantId, Guid userId)
{
var id = GetProgressItemId(tenantId, userId);
return Queue.GetStatus(id) as T;
}
public void Terminate(int tenantId, Guid userId)
{
var item = GetProgressItemStatus(tenantId, userId);
if (item != null)
Queue.Remove(item);
}
protected IProgressItem Start(int tenantId, Guid userId, Func<T> constructor)
{
lock (Queue.SynchRoot)
{
var task = GetProgressItemStatus(tenantId, userId);
if (task != null && task.IsCompleted)
{
Queue.Remove(task);
task = null;
}
if (task == null)
{
task = constructor();
Queue.Add(task);
}
if (!Queue.IsStarted)
Queue.Start(x => x.RunJob());
return task;
lock (Queue.SynchRoot)
{
var task = GetProgressItemStatus(tenantId, userId);
if (task != null && task.IsCompleted)
{
Queue.Remove(task);
task = null;
}
if (task == null)
{
task = constructor();
Queue.Add(task);
}
if (!Queue.IsStarted)
Queue.Start(x => x.RunJob());
return task;
}
}
}
}
public class QueueWorkerReassign : QueueWorker<ReassignProgressItem>
@ -120,9 +120,9 @@ namespace ASC.Data.Reassigns
QueueWorkerRemove = queueWorkerRemove;
}
public ReassignProgressItem Start(int tenantId, Guid fromUserId, Guid toUserId, Guid currentUserId, bool deleteProfile)
public ReassignProgressItem Start(int tenantId, Guid fromUserId, Guid toUserId, Guid currentUserId, bool deleteProfile)
{
return Start(tenantId, fromUserId, () => new ReassignProgressItem(ServiceProvider, HttpContextAccessor.HttpContext, this, QueueWorkerRemove, tenantId, fromUserId, toUserId, currentUserId, deleteProfile)) as ReassignProgressItem;
return Start(tenantId, fromUserId, () => new ReassignProgressItem(ServiceProvider, HttpContextAccessor.HttpContext, this, QueueWorkerRemove, tenantId, fromUserId, toUserId, currentUserId, deleteProfile)) as ReassignProgressItem;
}
}
public class QueueWorkerRemove : QueueWorker<RemoveProgressItem>
@ -135,15 +135,15 @@ namespace ASC.Data.Reassigns
{
}
public RemoveProgressItem Start(int tenantId, UserInfo user, Guid currentUserId, bool notify)
public RemoveProgressItem Start(int tenantId, UserInfo user, Guid currentUserId, bool notify)
{
return Start(tenantId, user.ID, () => new RemoveProgressItem(ServiceProvider, HttpContextAccessor.HttpContext, this, tenantId, user, currentUserId, notify)) as RemoveProgressItem;
return Start(tenantId, user.ID, () => new RemoveProgressItem(ServiceProvider, HttpContextAccessor.HttpContext, this, tenantId, user, currentUserId, notify)) as RemoveProgressItem;
}
}
public static class QueueExtension
{
public static IServiceCollection AddQueueWorkerRemoveService(this IServiceCollection services)
public static DIHelper AddQueueWorkerRemoveService(this DIHelper services)
{
services.TryAddSingleton<ProgressQueueOptionsManager<RemoveProgressItem>>();
services.TryAddSingleton<ProgressQueue<RemoveProgressItem>>();
@ -152,7 +152,7 @@ namespace ASC.Data.Reassigns
return services;
}
public static IServiceCollection AddQueueWorkerReassignService(this IServiceCollection services)
public static DIHelper AddQueueWorkerReassignService(this DIHelper services)
{
services.TryAddSingleton<ProgressQueueOptionsManager<ReassignProgressItem>>();
services.TryAddSingleton<ProgressQueue<ReassignProgressItem>>();
@ -162,5 +162,5 @@ namespace ASC.Data.Reassigns
return services
.AddQueueWorkerRemoveService();
}
}
}
}
}

View File

@ -25,7 +25,9 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using ASC.Common;
using ASC.Common.Logging;
//using System.Web;
using ASC.Common.Threading.Progress;
@ -41,7 +43,6 @@ using ASC.Web.Studio.Core.Notify;
//using CrmDaoFactory = ASC.CRM.Core.Dao.DaoFactory;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
namespace ASC.Data.Reassigns
@ -218,7 +219,7 @@ namespace ASC.Data.Reassigns
public static class ReassignProgressItemExtension
{
public static IServiceCollection AddReassignProgressItemService(this IServiceCollection services)
public static DIHelper AddReassignProgressItemService(this DIHelper services)
{
services.TryAddSingleton<ProgressQueueOptionsManager<ReassignProgressItem>>();
services.TryAddSingleton<ProgressQueue<ReassignProgressItem>>();

View File

@ -28,7 +28,9 @@ using System;
using System.Collections.Generic;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Text;
using ASC.Common;
using ASC.Common.Logging;
using ASC.Common.Threading.Progress;
using ASC.Core;
@ -43,7 +45,6 @@ using ASC.Web.Studio.Core.Notify;
//using CrmDaoFactory = ASC.CRM.Core.Dao.DaoFactory;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
namespace ASC.Data.Reassigns
@ -254,7 +255,7 @@ namespace ASC.Data.Reassigns
public static class RemoveProgressItemExtension
{
public static IServiceCollection AddRemoveProgressItemService(this IServiceCollection services)
public static DIHelper AddRemoveProgressItemService(this DIHelper services)
{
services.TryAddSingleton<ProgressQueueOptionsManager<RemoveProgressItem>>();

View File

@ -1,7 +1,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
using ASC.Common;
using ASC.Common.Utils;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
@ -10,7 +13,7 @@ namespace ASC.Data.Storage.Configuration
{
public static class StorageConfigExtension
{
public static IServiceCollection AddStorage(this IServiceCollection services)
public static DIHelper AddStorage(this DIHelper services)
{
services.TryAddSingleton(r => r.GetService<IConfiguration>().GetSetting<Storage>("Storage"));
return services;

View File

@ -28,6 +28,7 @@ using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using ASC.Common;
using ASC.Common.Caching;
using ASC.Common.Logging;
using ASC.Core;
@ -37,7 +38,6 @@ using ASC.Security.Cryptography;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
namespace ASC.Data.Storage.Configuration
@ -206,7 +206,7 @@ namespace ASC.Data.Storage.Configuration
public static class StorageSettingsExtension
{
public static IServiceCollection AddBaseStorageSettingsService(this IServiceCollection services)
public static DIHelper AddBaseStorageSettingsService(this DIHelper services)
{
services.TryAddSingleton(typeof(ICacheNotify<>), typeof(KafkaCache<>));
services.TryAddSingleton<BaseStorageSettingsListener>();
@ -217,7 +217,7 @@ namespace ASC.Data.Storage.Configuration
.AddEmailValidationKeyProviderService();
}
public static IServiceCollection AddCdnStorageSettingsService(this IServiceCollection services)
public static DIHelper AddCdnStorageSettingsService(this DIHelper services)
{
services.TryAddScoped<StorageSettingsHelper>();
@ -227,7 +227,7 @@ namespace ASC.Data.Storage.Configuration
.AddConsumerFactoryService();
}
public static IServiceCollection AddStorageSettingsService(this IServiceCollection services)
public static DIHelper AddStorageSettingsService(this DIHelper services)
{
services.TryAddScoped<StorageSettingsHelper>();

View File

@ -25,6 +25,7 @@
using System.Collections.Generic;
using ASC.Data.Storage.Configuration;
namespace ASC.Data.Storage
@ -34,9 +35,16 @@ namespace ASC.Data.Storage
public DataList(Module config)
{
Add(string.Empty, config.Data);
foreach (var domain in config.Domain)
if (config.Domain != null)
{
Add(domain.Name, domain.Data);
foreach (var domain in config.Domain)
{
Add(domain.Name, domain.Data);
}
}
else
{
config.Domain = new List<Module>();
}
}

View File

@ -27,10 +27,11 @@
using System;
using System.Collections.Generic;
using System.IO;
using ASC.Common;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
namespace ASC.Data.Storage
@ -119,7 +120,7 @@ namespace ASC.Data.Storage
public static class PathUtilsExtension
{
public static IServiceCollection AddPathUtilsService(this IServiceCollection services)
public static DIHelper AddPathUtilsService(this DIHelper services)
{
services.TryAddSingleton<PathUtils>();

View File

@ -30,17 +30,19 @@ using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks;
using ASC.Common;
using ASC.Common.Caching;
using ASC.Common.Logging;
using ASC.Common.Threading;
using ASC.Common.Threading.Progress;
using ASC.Core;
using ASC.Core.Common.Settings;
using ASC.Core.Common.Settings;
using ASC.Core.Tenants;
using ASC.Data.Storage.Configuration;
using ASC.Data.Storage.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
namespace ASC.Data.Storage
@ -54,10 +56,10 @@ namespace ASC.Data.Storage
private static readonly object Locker;
public IServiceProvider ServiceProvider { get; }
public TenantManager TenantManager { get; }
public SettingsManager SettingsManager { get; }
public StorageSettingsHelper StorageSettingsHelper { get; }
public TenantManager TenantManager { get; }
public SettingsManager SettingsManager { get; }
public StorageSettingsHelper StorageSettingsHelper { get; }
static StaticUploader()
{
Scheduler = new LimitedConcurrencyLevelTaskScheduler(4);
@ -66,16 +68,16 @@ namespace ASC.Data.Storage
TokenSource = new CancellationTokenSource();
}
public StaticUploader(
IServiceProvider serviceProvider,
TenantManager tenantManager,
SettingsManager settingsManager,
public StaticUploader(
IServiceProvider serviceProvider,
TenantManager tenantManager,
SettingsManager settingsManager,
StorageSettingsHelper storageSettingsHelper)
{
ServiceProvider = serviceProvider;
TenantManager = tenantManager;
SettingsManager = settingsManager;
StorageSettingsHelper = storageSettingsHelper;
TenantManager = tenantManager;
SettingsManager = settingsManager;
StorageSettingsHelper = storageSettingsHelper;
}
public string UploadFile(string relativePath, string mappedPath, Action<string> onComplete = null)
@ -212,8 +214,8 @@ namespace ASC.Data.Storage
var tenant = tenantManager.GetTenant(tenantId);
tenantManager.SetCurrentTenant(tenant);
var SecurityContext = scope.ServiceProvider.GetService<SecurityContext>();
var SettingsManager = scope.ServiceProvider.GetService<SettingsManager>();
var SecurityContext = scope.ServiceProvider.GetService<SecurityContext>();
var SettingsManager = scope.ServiceProvider.GetService<SettingsManager>();
var StorageSettingsHelper = scope.ServiceProvider.GetService<StorageSettingsHelper>();
SecurityContext.AuthenticateMe(tenant.OwnerId);
@ -290,7 +292,7 @@ namespace ASC.Data.Storage
public static class StaticUploaderExtension
{
public static IServiceCollection AddStaticUploaderService(this IServiceCollection services)
public static DIHelper AddStaticUploaderService(this DIHelper services)
{
services.TryAddScoped<StaticUploader>();

View File

@ -28,6 +28,7 @@ using System;
using System.Collections.Generic;
using System.Linq;
using ASC.Common;
using ASC.Common.Caching;
using ASC.Common.Logging;
using ASC.Core;
@ -40,7 +41,6 @@ using ASC.Security.Cryptography;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
namespace ASC.Data.Storage
@ -232,20 +232,20 @@ namespace ASC.Data.Storage
//Make tennant path
tenant = TenantPath.CreatePath(tenant);
var store = DataStoreCache.Get(tenant, module);
if (store == null)
//remove cache
//var store = DataStoreCache.Get(tenant, module);
//if (store == null)
//{
var section = StorageFactoryConfig.Section;
if (section == null)
{
var section = StorageFactoryConfig.Section;
if (section == null)
{
throw new InvalidOperationException("config section not found");
}
var settings = SettingsManager.LoadForTenant<StorageSettings>(tenantId);
store = GetStoreAndCache(tenant, module, StorageSettingsHelper.DataStoreConsumer(settings), controller);
throw new InvalidOperationException("config section not found");
}
return store;
var settings = SettingsManager.LoadForTenant<StorageSettings>(tenantId);
//}
return GetDataStore(tenant, module, StorageSettingsHelper.DataStoreConsumer(settings), controller);
}
public IDataStore GetStorageFromConsumer(string configpath, string tenant, string module, DataStoreConsumer consumer)
@ -311,14 +311,14 @@ namespace ASC.Data.Storage
public static class StorageFactoryExtension
{
public static IServiceCollection AddStorageFactoryConfigService(this IServiceCollection services)
public static DIHelper AddStorageFactoryConfigService(this DIHelper services)
{
services.TryAddSingleton<StorageFactoryConfig>();
return services;
}
public static IServiceCollection AddStorageFactoryService(this IServiceCollection services)
public static DIHelper AddStorageFactoryService(this DIHelper services)
{
services.TryAddScoped<StorageFactory>();
services.TryAddSingleton<StorageFactoryListener>();

View File

@ -25,23 +25,24 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using System.Threading.Tasks;
using System.Web;
using ASC.Common.Web;
using ASC.Common;
using ASC.Common.Web;
using ASC.Core;
using ASC.Security.Cryptography;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using ASC.Security.Cryptography;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
namespace ASC.Data.Storage.DiscStorage
{
public class StorageHandler
@ -52,23 +53,23 @@ namespace ASC.Data.Storage.DiscStorage
private readonly bool _checkAuth;
public StorageHandler(IServiceProvider serviceProvider, string path, string module, string domain, bool checkAuth = true)
{
ServiceProvider = serviceProvider;
{
ServiceProvider = serviceProvider;
_path = path;
_module = module;
_domain = domain;
_checkAuth = checkAuth;
}
public IServiceProvider ServiceProvider { get; }
}
public IServiceProvider ServiceProvider { get; }
public async Task Invoke(HttpContext context)
{
using var scope = ServiceProvider.CreateScope();
var tenantManager = scope.ServiceProvider.GetService<TenantManager>();
var securityContext = scope.ServiceProvider.GetService<SecurityContext>();
var storageFactory = scope.ServiceProvider.GetService<StorageFactory>();
var emailValidationKeyProvider = scope.ServiceProvider.GetService<EmailValidationKeyProvider>();
{
using var scope = ServiceProvider.CreateScope();
var tenantManager = scope.ServiceProvider.GetService<TenantManager>();
var securityContext = scope.ServiceProvider.GetService<SecurityContext>();
var storageFactory = scope.ServiceProvider.GetService<StorageFactory>();
var emailValidationKeyProvider = scope.ServiceProvider.GetService<EmailValidationKeyProvider>();
if (_checkAuth && !securityContext.IsAuthenticated)
{
@ -108,7 +109,7 @@ namespace ASC.Data.Storage.DiscStorage
if (storage.IsSupportInternalUri && bigSize < storage.GetFileSize(_domain, path))
{
var uri = storage.GetInternalUri(_domain, path, TimeSpan.FromMinutes(15), headers);
//TODO
//context.Response.Cache.SetAllowResponseInBrowserHistory(false);
//context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
@ -126,59 +127,59 @@ namespace ASC.Data.Storage.DiscStorage
using (var stream = storage.GetReadStream(_domain, path))
{
await stream.StreamCopyToAsync(context.Response.Body);
}
var headersToCopy = new List<string> { "Content-Disposition", "Cache-Control", "Content-Encoding", "Content-Language", "Content-Type", "Expires" };
foreach (var h in headers)
{
var toCopy = headersToCopy.Find(x => h.StartsWith(x));
if (string.IsNullOrEmpty(toCopy)) continue;
context.Response.Headers[toCopy] = h.Substring(toCopy.Length + 1);
}
var headersToCopy = new List<string> { "Content-Disposition", "Cache-Control", "Content-Encoding", "Content-Language", "Content-Type", "Expires" };
foreach (var h in headers)
{
var toCopy = headersToCopy.Find(x => h.StartsWith(x));
if (string.IsNullOrEmpty(toCopy)) continue;
context.Response.Headers[toCopy] = h.Substring(toCopy.Length + 1);
}
context.Response.ContentType = MimeMapping.GetMimeMapping(path);
if (encoding != null)
context.Response.Headers["Content-Encoding"] = encoding;
string GetRouteValue(string name)
{
return (context.GetRouteValue(name) ?? "").ToString();
context.Response.Headers["Content-Encoding"] = encoding;
string GetRouteValue(string name)
{
return (context.GetRouteValue(name) ?? "").ToString();
}
}
}
public static class StorageHandlerExtensions
{
}
public static class StorageHandlerExtensions
{
public static IEndpointRouteBuilder RegisterStorageHandler(this IEndpointRouteBuilder builder, string module, string domain, bool publicRoute = false)
{
var pathUtils = builder.ServiceProvider.GetService<PathUtils>();
{
var pathUtils = builder.ServiceProvider.GetService<PathUtils>();
var virtPath = pathUtils.ResolveVirtualPath(module, domain);
virtPath = virtPath.TrimStart('/');
var handler = new StorageHandler(builder.ServiceProvider, string.Empty, module, domain, !publicRoute);
var url = virtPath + "{*pathInfo}";
if (!builder.DataSources.Any(r => r.Endpoints.Any(e => e.DisplayName == url)))
{
builder.Map(url, handler.Invoke);
var newUrl = url.Replace("{0}", "{t1}/{t2}/{t3}");
if (newUrl != url)
{
builder.Map(url, handler.Invoke);
}
}
virtPath = virtPath.TrimStart('/');
var handler = new StorageHandler(builder.ServiceProvider, string.Empty, module, domain, !publicRoute);
var url = virtPath + "{*pathInfo}";
if (!builder.DataSources.Any(r => r.Endpoints.Any(e => e.DisplayName == url)))
{
builder.Map(url, handler.Invoke);
var newUrl = url.Replace("{0}", "{t1}/{t2}/{t3}");
if (newUrl != url)
{
builder.Map(url, handler.Invoke);
}
}
return builder;
}
public static IServiceCollection AddStorageHandlerService(this IServiceCollection services)
{
return services
.AddTenantManagerService()
.AddSecurityContextService()
.AddStorageFactoryService()
.AddEmailValidationKeyProviderService();
}
}
public static DIHelper AddStorageHandlerService(this DIHelper services)
{
return services
.AddTenantManagerService()
.AddSecurityContextService()
.AddStorageFactoryService()
.AddEmailValidationKeyProviderService();
}
}
}

View File

@ -31,14 +31,13 @@ using System.IO;
using System.Linq;
using System.Net;
using ASC.Common;
using ASC.Common.Logging;
using ASC.Core;
using ASC.Core.Common.Settings;
using ASC.Data.Storage.Configuration;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
@ -235,7 +234,7 @@ namespace ASC.Data.Storage
public static class WebPathExtension
{
public static IServiceCollection AddWebPathService(this IServiceCollection services)
public static DIHelper AddWebPathService(this DIHelper services)
{
services.TryAddScoped<WebPath>();
@ -245,7 +244,7 @@ namespace ASC.Data.Storage
.AddWebPathSettingsService()
.AddCoreBaseSettingsService();
}
public static IServiceCollection AddWebPathSettingsService(this IServiceCollection services)
public static DIHelper AddWebPathSettingsService(this DIHelper services)
{
services.TryAddSingleton<WebPathSettings>();

View File

@ -28,6 +28,7 @@ using System;
using System.Collections.Generic;
using System.Linq;
using ASC.Common;
using ASC.Common.Caching;
using ASC.Common.Utils;
using ASC.Core.Common.EF;
@ -37,8 +38,6 @@ using ASC.FederatedLogin.Profile;
using ASC.Security.Cryptography;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
namespace ASC.FederatedLogin
@ -218,7 +217,7 @@ namespace ASC.FederatedLogin
public static class AccountLinkerStorageExtension
{
public static IServiceCollection AddAccountLinkerStorageService(this IServiceCollection services)
public static DIHelper AddAccountLinkerStorageService(this DIHelper services)
{
services.TryAddSingleton<AccountLinkerStorage>();
services.TryAddSingleton(typeof(ICacheNotify<>), typeof(KafkaCache<>));
@ -229,7 +228,7 @@ namespace ASC.FederatedLogin
public static class AccountLinkerExtension
{
public static IServiceCollection AddAccountLinker(this IServiceCollection services)
public static DIHelper AddAccountLinker(this DIHelper services)
{
services.TryAddScoped<AccountLinker>();
services.TryAddScoped<IConfigureOptions<AccountLinker>, ConfigureAccountLinker>();

View File

@ -24,14 +24,15 @@
*/
using System.Collections.Generic;
using ASC.Common.Caching;
using ASC.Core;
using ASC.Core.Common.Configuration;
using Microsoft.Extensions.Configuration;
using System.Collections.Generic;
using ASC.Common;
using ASC.Common.Caching;
using ASC.Core;
using ASC.Core.Common.Configuration;
using Microsoft.Extensions.Configuration;
namespace ASC.FederatedLogin.LoginProviders
{
public class BoxLoginProvider : Consumer, IOAuthProvider
@ -63,16 +64,30 @@ namespace ASC.FederatedLogin.LoginProviders
public BoxLoginProvider() { }
public BoxLoginProvider(
TenantManager tenantManager,
CoreBaseSettings coreBaseSettings,
CoreSettings coreSettings,
ConsumerFactory consumerFactory,
IConfiguration configuration,
ICacheNotify<ConsumerCacheItem> cache,
public BoxLoginProvider(
TenantManager tenantManager,
CoreBaseSettings coreBaseSettings,
CoreSettings coreSettings,
ConsumerFactory consumerFactory,
IConfiguration configuration,
ICacheNotify<ConsumerCacheItem> cache,
string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null)
: base(tenantManager, coreBaseSettings, coreSettings, consumerFactory, configuration, cache, name, order, props, additional)
{
}
}
public static class BoxLoginProviderExtension
{
public static DIHelper AddBoxLoginProviderService(this DIHelper services)
{
services.TryAddScoped<BoxLoginProvider>();
return services
.AddConsumerFactoryService()
.AddKafkaService()
.AddTenantManagerService()
.AddCoreBaseSettingsService()
.AddCoreSettingsService();
}
}
}

View File

@ -26,15 +26,16 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Text;
using ASC.Common.Caching;
using ASC.Core;
using ASC.Common;
using ASC.Common.Caching;
using ASC.Core;
using ASC.Core.Common.Configuration;
using ASC.FederatedLogin.Helpers;
using Microsoft.Extensions.Configuration;
using ASC.FederatedLogin.Helpers;
using Microsoft.Extensions.Configuration;
namespace ASC.FederatedLogin.LoginProviders
{
public class DocuSignLoginProvider : Consumer, IOAuthProvider
@ -64,13 +65,13 @@ namespace ASC.FederatedLogin.LoginProviders
public DocuSignLoginProvider() { }
public DocuSignLoginProvider(
TenantManager tenantManager,
CoreBaseSettings coreBaseSettings,
CoreSettings coreSettings,
ConsumerFactory consumerFactory,
IConfiguration configuration,
ICacheNotify<ConsumerCacheItem> cache,
public DocuSignLoginProvider(
TenantManager tenantManager,
CoreBaseSettings coreBaseSettings,
CoreSettings coreSettings,
ConsumerFactory consumerFactory,
IConfiguration configuration,
ICacheNotify<ConsumerCacheItem> cache,
string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null)
: base(tenantManager, coreBaseSettings, coreSettings, consumerFactory, configuration, cache, name, order, props, additional)
{
@ -133,4 +134,17 @@ namespace ASC.FederatedLogin.LoginProviders
return refreshed;
}
}
public static class DocuSignLoginProviderExtension
{
public static DIHelper AddDocuSignLoginProviderService(this DIHelper services)
{
services.TryAddScoped<DocuSignLoginProvider>();
return services
.AddConsumerFactoryService()
.AddKafkaService()
.AddTenantManagerService()
.AddCoreBaseSettingsService()
.AddCoreSettingsService();
}
}
}

View File

@ -24,14 +24,15 @@
*/
using System.Collections.Generic;
using ASC.Common.Caching;
using ASC.Core;
using ASC.Core.Common.Configuration;
using Microsoft.Extensions.Configuration;
using System.Collections.Generic;
using ASC.Common;
using ASC.Common.Caching;
using ASC.Core;
using ASC.Core.Common.Configuration;
using Microsoft.Extensions.Configuration;
namespace ASC.FederatedLogin.LoginProviders
{
public class DropboxLoginProvider : Consumer, IOAuthProvider
@ -60,16 +61,29 @@ namespace ASC.FederatedLogin.LoginProviders
public DropboxLoginProvider() { }
public DropboxLoginProvider(
TenantManager tenantManager,
CoreBaseSettings coreBaseSettings,
CoreSettings coreSettings,
ConsumerFactory consumerFactory,
IConfiguration configuration,
ICacheNotify<ConsumerCacheItem> cache,
public DropboxLoginProvider(
TenantManager tenantManager,
CoreBaseSettings coreBaseSettings,
CoreSettings coreSettings,
ConsumerFactory consumerFactory,
IConfiguration configuration,
ICacheNotify<ConsumerCacheItem> cache,
string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null)
: base(tenantManager, coreBaseSettings, coreSettings, consumerFactory, configuration, cache, name, order, props, additional)
{
}
}
public static class DropboxLoginProviderExtension
{
public static DIHelper AddDropboxLoginProviderService(this DIHelper services)
{
services.TryAddScoped<DropboxLoginProvider>();
return services
.AddConsumerFactoryService()
.AddKafkaService()
.AddTenantManagerService()
.AddCoreBaseSettingsService()
.AddCoreSettingsService();
}
}
}

View File

@ -26,42 +26,59 @@
using System;
using System.Linq;
using System.Security;
using System.Security;
using ASC.Common.Utils;
using ASC.Common;
using ASC.Common.Utils;
using ASC.Core;
using ASC.Core.Users;
using ASC.FederatedLogin;
using ASC.FederatedLogin.Profile;
using ASC.Security.Cryptography;
using Microsoft.Extensions.Options;
using ASC.FederatedLogin.Profile;
using ASC.Security.Cryptography;
using Microsoft.Extensions.Options;
using SecurityContext = ASC.Core.SecurityContext;
namespace ASC.Web.Studio.Core
{
public static class BlockchainLoginProvider
public class EncryptionLoginProvider
{
public static void UpdateData(
string account,
UserManager userManager,
TenantManager tenantManager,
SecurityContext securityContext,
Signature signature,
InstanceCrypto instanceCrypto,
IOptionsSnapshot<AccountLinker> snapshot)
{
var tenant = tenantManager.GetCurrentTenant();
var user = userManager.GetUsers(securityContext.CurrentAccount.ID);
if (!securityContext.IsAuthenticated || user.IsVisitor(userManager)) throw new SecurityException();
public UserManager UserManager { get; }
public TenantManager TenantManager { get; }
public SecurityContext SecurityContext { get; }
public Signature Signature { get; }
public InstanceCrypto InstanceCrypto { get; }
public IOptionsSnapshot<AccountLinker> Snapshot { get; }
var loginProfile = new LoginProfile(signature, instanceCrypto)
{
Provider = ProviderConstants.Encryption,
public EncryptionLoginProvider(
UserManager userManager,
TenantManager tenantManager,
SecurityContext securityContext,
Signature signature,
InstanceCrypto instanceCrypto,
IOptionsSnapshot<AccountLinker> snapshot)
{
UserManager = userManager;
TenantManager = tenantManager;
SecurityContext = securityContext;
Signature = signature;
InstanceCrypto = instanceCrypto;
Snapshot = snapshot;
}
public void UpdateAddress(string account)
{
var tenant = TenantManager.GetCurrentTenant();
var user = UserManager.GetUsers(SecurityContext.CurrentAccount.ID);
if (!SecurityContext.IsAuthenticated || user.IsVisitor(UserManager)) throw new SecurityException();
var loginProfile = new LoginProfile(Signature, InstanceCrypto)
{
Provider = ProviderConstants.Encryption,
};
var linker = snapshot.Get("webstudio");
var linker = Snapshot.Get("webstudio");
if (string.IsNullOrEmpty(account))
{
linker.RemoveLink(user.ID.ToString(), loginProfile);
@ -74,14 +91,14 @@ namespace ASC.Web.Studio.Core
}
public static string GetAddress(SecurityContext securityContext, IOptionsSnapshot<AccountLinker> snapshot)
public string GetAddress()
{
return GetAddress(securityContext.CurrentAccount.ID, snapshot);
return GetAddress(SecurityContext.CurrentAccount.ID);
}
public static string GetAddress(Guid userId, IOptionsSnapshot<AccountLinker> snapshot)
public string GetAddress(Guid userId)
{
var linker = snapshot.Get("webstudio");
var linker = Snapshot.Get("webstudio");
var profile = linker.GetLinkedProfiles(userId.ToString(), ProviderConstants.Encryption).FirstOrDefault();
if (profile == null) return null;
@ -89,4 +106,19 @@ namespace ASC.Web.Studio.Core
return account;
}
}
public static class EncryptionLoginProviderExtension
{
public static DIHelper AddEncryptionLoginProviderService(this DIHelper services)
{
services.TryAddScoped<EncryptionLoginProvider>();
return services
.AddUserManagerService()
.AddTenantManagerService()
.AddSecurityContextService()
.AddSignatureService()
.AddInstanceCryptoService()
.AddAccountLinker();
}
}
}

View File

@ -28,6 +28,7 @@ using System;
using System.Collections.Generic;
using System.Web;
using ASC.Common;
using ASC.Common.Caching;
using ASC.Common.Utils;
using ASC.Core;
@ -180,4 +181,20 @@ namespace ASC.FederatedLogin.LoginProviders
public bool primary = false;
}
}
public static class GoogleLoginProviderExtension
{
public static DIHelper AddGoogleLoginProviderService(this DIHelper services)
{
services.TryAddScoped<GoogleLoginProvider>();
return services
.AddConsumerFactoryService()
.AddKafkaService()
.AddTenantManagerService()
.AddCoreBaseSettingsService()
.AddCoreSettingsService()
.AddSignatureService()
.AddInstanceCryptoService();
}
}
}

View File

@ -26,6 +26,7 @@
using System.Collections.Generic;
using ASC.Common;
using ASC.Common.Caching;
using ASC.Core;
using ASC.Core.Common.Configuration;
@ -75,4 +76,18 @@ namespace ASC.FederatedLogin.LoginProviders
{
}
}
public static class OneDriveLoginProviderExtension
{
public static DIHelper AddOneDriveLoginProviderService(this DIHelper services)
{
services.TryAddScoped<OneDriveLoginProvider>();
return services
.AddConsumerFactoryService()
.AddKafkaService()
.AddTenantManagerService()
.AddCoreBaseSettingsService()
.AddCoreSettingsService();
}
}
}

Some files were not shown because too many files have changed in this diff Show More