From 50c0596efffadb42e69a36af6ebb9dd5a650dd15 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Tue, 11 Jan 2022 18:37:19 +0300 Subject: [PATCH] analizators/U2U1009 --- .../ASC.Core.Common/Billing/CouponManager.cs | 14 ++- .../EF/Context/BaseDbContext.cs | 12 +- .../Tasks/PortalTaskBase.cs | 8 +- common/ASC.Data.Storage/StorageHandler.cs | 37 +++--- .../Engine/FactoryIndexer.cs | 26 ++-- .../ContactPhotoHandlerMiddleware.cs | 17 ++- .../ImportFileHandlerMiddleware.cs | 11 +- .../OrganisationLogoHandlerMiddleware.cs | 12 +- .../Core/Core/Dao/TeamlabDao/FileDao.cs | 9 +- .../Core/HttpHandlers/FileHandler.ashx.cs | 115 +++++++++++------- 10 files changed, 179 insertions(+), 82 deletions(-) diff --git a/common/ASC.Core.Common/Billing/CouponManager.cs b/common/ASC.Core.Common/Billing/CouponManager.cs index fc8bcd932c..eb1c9c4180 100644 --- a/common/ASC.Core.Common/Billing/CouponManager.cs +++ b/common/ASC.Core.Common/Billing/CouponManager.cs @@ -112,19 +112,23 @@ namespace ASC.Core.Common.Billing Log.Error(ex.Message, ex); throw; } + } + + internal Task> GetProducts() + { + if (Products != null) return Task.FromResult(Products); + return InternalGetProducts(); } - internal async Task> GetProducts() - { - if (Products != null) return Products; - + private async Task> InternalGetProducts() + { await SemaphoreSlim.WaitAsync(); if (Products != null) { SemaphoreSlim.Release(); return Products; - } + } try { diff --git a/common/ASC.Core.Common/EF/Context/BaseDbContext.cs b/common/ASC.Core.Common/EF/Context/BaseDbContext.cs index 771201928c..e61b9536c2 100644 --- a/common/ASC.Core.Common/EF/Context/BaseDbContext.cs +++ b/common/ASC.Core.Common/EF/Context/BaseDbContext.cs @@ -133,10 +133,16 @@ namespace ASC.Core.Common.EF } } } - public async ValueTask DisposeAsync() - { - if (Context == null) return; + public ValueTask DisposeAsync() + { + if (Context == null) return ValueTask.CompletedTask; + + return InternalDisposeAsync(); + } + + private async ValueTask InternalDisposeAsync() + { foreach (var c in Context) { if (c != null) diff --git a/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs b/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs index 079bcdba69..d5de8af201 100644 --- a/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs +++ b/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs @@ -280,11 +280,15 @@ namespace ASC.Data.Backup.Tasks Logger.DebugFormat("complete mysql file {0}", file); } - protected async Task RunMysqlFile(Stream stream, string delimiter = ";") + protected Task RunMysqlFile(Stream stream, string delimiter = ";") { + if (stream == null) return Task.CompletedTask; - if (stream == null) return; + return InternalRunMysqlFile(stream, delimiter); + } + private async Task InternalRunMysqlFile(Stream stream, string delimiter) + { using var reader = new StreamReader(stream, Encoding.UTF8); string commandText; diff --git a/common/ASC.Data.Storage/StorageHandler.cs b/common/ASC.Data.Storage/StorageHandler.cs index b36f22aba8..6a26f7c3e8 100644 --- a/common/ASC.Data.Storage/StorageHandler.cs +++ b/common/ASC.Data.Storage/StorageHandler.cs @@ -63,9 +63,9 @@ namespace ASC.Data.Storage.DiscStorage } private IServiceProvider ServiceProvider { get; } - - public async Task Invoke(HttpContext context) - { + + public Task Invoke(HttpContext context) + { using var scope = ServiceProvider.CreateScope(); var scopeClass = scope.ServiceProvider.GetService(); var (tenantManager, securityContext, storageFactory, emailValidationKeyProvider) = scopeClass; @@ -73,11 +73,11 @@ namespace ASC.Data.Storage.DiscStorage if (_checkAuth && !securityContext.IsAuthenticated) { context.Response.StatusCode = (int)HttpStatusCode.Forbidden; - return; + return Task.CompletedTask; } var storage = storageFactory.GetStorage(tenantManager.GetCurrentTenant().TenantId.ToString(CultureInfo.InvariantCulture), _module); - var path = CrossPlatform.PathCombine(_path, GetRouteValue("pathInfo").Replace('/', Path.DirectorySeparatorChar)); + var path = CrossPlatform.PathCombine(_path, GetRouteValue("pathInfo", context).Replace('/', Path.DirectorySeparatorChar)); var header = context.Request.Query[Constants.QUERY_HEADER].FirstOrDefault() ?? ""; var auth = context.Request.Query[Constants.QUERY_AUTH].FirstOrDefault() ?? ""; @@ -92,14 +92,14 @@ namespace ASC.Data.Storage.DiscStorage if (validateResult != EmailValidationKeyProvider.ValidationResult.Ok) { context.Response.StatusCode = (int)HttpStatusCode.Forbidden; - return; + return Task.CompletedTask; } } if (!storage.IsFile(_domain, path)) { context.Response.StatusCode = (int)HttpStatusCode.NotFound; - return; + return Task.CompletedTask; } var headers = header.Length > 0 ? header.Split('&').Select(HttpUtility.UrlDecode) : new string[] { }; @@ -113,9 +113,9 @@ namespace ASC.Data.Storage.DiscStorage //context.Response.Cache.SetCacheability(HttpCacheability.NoCache); context.Response.Redirect(uri.ToString()); - return; - } - + return Task.CompletedTask; + } + string encoding = null; if (storage is DiscDataStore && storage.IsFile(_domain, path + ".gz")) { @@ -143,18 +143,23 @@ namespace ASC.Data.Storage.DiscStorage if (encoding != null) context.Response.Headers["Content-Encoding"] = encoding; + return InternalInvoke(context, storage, path); + } + + private async Task InternalInvoke(HttpContext context, IDataStore storage, string path) + { using (var stream = storage.GetReadStream(_domain, path)) { await stream.CopyToAsync(context.Response.Body); } await context.Response.Body.FlushAsync(); - await context.Response.CompleteAsync(); - - string GetRouteValue(string name) - { - return (context.GetRouteValue(name) ?? "").ToString(); - } + await context.Response.CompleteAsync(); + } + + private string GetRouteValue(string name, HttpContext context) + { + return (context.GetRouteValue(name) ?? "").ToString(); } } diff --git a/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs b/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs index 1f90cd008a..4c23f20347 100644 --- a/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs @@ -271,13 +271,18 @@ namespace ASC.ElasticSearch throw; } } - } + } - public async Task IndexAsync(List data, bool immediately = true, int retry = 0) + public Task IndexAsync(List data, bool immediately = true, int retry = 0) { var t = ServiceProvider.GetService(); - if (!Support(t) || !data.Any()) return; + if (!Support(t) || !data.Any()) return Task.CompletedTask; + return InternalIndexAsync(data, immediately, retry); + } + + private async Task InternalIndexAsync(List data, bool immediately, int retry) + { try { await Indexer.IndexAsync(data, immediately).ConfigureAwait(false); @@ -627,9 +632,9 @@ namespace ASC.ElasticSearch return false; } } - - public async Task CheckStateAsync(bool cacheState = true) - { + + public Task CheckStateAsync(bool cacheState = true) + { const string key = "elasticsearch"; if (cacheState) @@ -637,10 +642,15 @@ namespace ASC.ElasticSearch var cacheValue = cache.Get(key); if (!string.IsNullOrEmpty(cacheValue)) { - return Convert.ToBoolean(cacheValue); + return Task.FromResult(Convert.ToBoolean(cacheValue)); } - } + } + + return InternalCheckStateAsync(cacheState, key); + } + private async Task InternalCheckStateAsync(bool cacheState, string key) + { var cacheTime = DateTime.UtcNow.AddMinutes(15); try diff --git a/products/ASC.CRM/Server/Middlewares/ContactPhotoHandlerMiddleware.cs b/products/ASC.CRM/Server/Middlewares/ContactPhotoHandlerMiddleware.cs index 01ed9567f7..450e5b2316 100644 --- a/products/ASC.CRM/Server/Middlewares/ContactPhotoHandlerMiddleware.cs +++ b/products/ASC.CRM/Server/Middlewares/ContactPhotoHandlerMiddleware.cs @@ -54,7 +54,7 @@ namespace ASC.Web.CRM.HttpHandlers private readonly RequestDelegate _next; - public async System.Threading.Tasks.Task Invoke(HttpContext context, + public System.Threading.Tasks.Task Invoke(HttpContext context, SetupInfo setupInfo, CrmSecurity crmSecurity, FileSizeComment fileSizeComment, @@ -62,8 +62,7 @@ namespace ASC.Web.CRM.HttpHandlers MessageTarget messageTarget, MessageService messageService, DaoFactory daoFactory, - ContactPhotoManager contactPhotoManager) - { + ContactPhotoManager contactPhotoManager){ if (!webItemSecurity.IsAvailableForMe(ProductEntryPoint.ID)) throw crmSecurity.CreateSecurityException(); @@ -82,6 +81,18 @@ namespace ASC.Web.CRM.HttpHandlers throw crmSecurity.CreateSecurityException(); } + return InternalInvoke(context, setupInfo, fileSizeComment, messageTarget, messageService, contactPhotoManager, contact, contactId); + } + + private async System.Threading.Tasks.Task InternalInvoke(HttpContext context, + SetupInfo setupInfo, + FileSizeComment fileSizeComment, + MessageTarget messageTarget, + MessageService messageService, + ContactPhotoManager contactPhotoManager, + Contact contact, + int contactId) + { var fileUploadResult = new FileUploadResult(); if (context.Request.Form.Files.Count == 0) diff --git a/products/ASC.CRM/Server/Middlewares/ImportFileHandlerMiddleware.cs b/products/ASC.CRM/Server/Middlewares/ImportFileHandlerMiddleware.cs index 1e495a831b..cdc1d25219 100644 --- a/products/ASC.CRM/Server/Middlewares/ImportFileHandlerMiddleware.cs +++ b/products/ASC.CRM/Server/Middlewares/ImportFileHandlerMiddleware.cs @@ -50,7 +50,7 @@ namespace ASC.Web.CRM.HttpHandlers _next = next; } - public async Task Invoke(HttpContext context, + public Task Invoke(HttpContext context, WebItemSecurity webItemSecurity, CrmSecurity crmSecurity, Global global, @@ -59,6 +59,15 @@ namespace ASC.Web.CRM.HttpHandlers if (!webItemSecurity.IsAvailableForMe(ProductEntryPoint.ID)) throw crmSecurity.CreateSecurityException(); + return InternalInvoke(context, webItemSecurity, crmSecurity, global, importFromCSV); + } + + private async Task InternalInvoke(HttpContext context, + WebItemSecurity webItemSecurity, + CrmSecurity crmSecurity, + Global global, + ImportFromCSV importFromCSV) + { var fileUploadResult = new FileUploadResult(); if (context.Request.Form.Files.Count == 0) diff --git a/products/ASC.CRM/Server/Middlewares/OrganisationLogoHandlerMiddleware.cs b/products/ASC.CRM/Server/Middlewares/OrganisationLogoHandlerMiddleware.cs index 7891665425..8e8a1e8d75 100644 --- a/products/ASC.CRM/Server/Middlewares/OrganisationLogoHandlerMiddleware.cs +++ b/products/ASC.CRM/Server/Middlewares/OrganisationLogoHandlerMiddleware.cs @@ -50,7 +50,7 @@ namespace ASC.Web.CRM.HttpHandlers _next = next; } - public async System.Threading.Tasks.Task Invoke(HttpContext context, + public System.Threading.Tasks.Task Invoke(HttpContext context, CrmSecurity crmSecurity, SetupInfo setupInfo, FileSizeComment fileSizeComment, @@ -62,6 +62,16 @@ namespace ASC.Web.CRM.HttpHandlers if (!crmSecurity.IsAdmin) throw crmSecurity.CreateSecurityException(); + return InternalInvoke(context, crmSecurity, setupInfo, fileSizeComment, contactPhotoManager, organisationLogoManager); + } + + private async System.Threading.Tasks.Task InternalInvoke(HttpContext context, + CrmSecurity crmSecurity, + SetupInfo setupInfo, + FileSizeComment fileSizeComment, + ContactPhotoManager contactPhotoManager, + OrganisationLogoManager organisationLogoManager) + { var fileUploadResult = new FileUploadResult(); if (context.Request.Form.Files.Count == 0) diff --git a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs index 6e98f63dbf..b636462f6e 100644 --- a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs +++ b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs @@ -1507,7 +1507,7 @@ namespace ASC.Files.Core.Data return dbFile; } - internal protected async Task InitDocumentAsync(DbFile dbFile) + internal protected Task InitDocumentAsync(DbFile dbFile) { if (!FactoryIndexer.CanIndexByContent(dbFile)) { @@ -1515,9 +1515,14 @@ namespace ASC.Files.Core.Data { Data = Convert.ToBase64String(Encoding.UTF8.GetBytes("")) }; - return dbFile; + return Task.FromResult(dbFile); } + return InernalInitDocumentAsync(dbFile); + } + + private async Task InernalInitDocumentAsync(DbFile dbFile) + { var file = ServiceProvider.GetService>(); file.ID = dbFile.Id; file.Title = dbFile.Title; diff --git a/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs b/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs index 7575a48260..4ed9f1b5f8 100644 --- a/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs +++ b/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs @@ -41,6 +41,7 @@ using ASC.Common.Logging; using ASC.Common.Utils; using ASC.Common.Web; using ASC.Core; +using ASC.Data.Storage; using ASC.Files.Core; using ASC.Files.Core.Resources; using ASC.Files.Core.Security; @@ -172,17 +173,22 @@ namespace ASC.Web.Files TempStream = tempStream; UserManager = userManager; Logger = optionsMonitor.CurrentValue; - } - - public async Task Invoke(HttpContext context) - { + } + + public Task Invoke(HttpContext context) + { if (TenantExtra.IsNotPaid()) { context.Response.StatusCode = (int)HttpStatusCode.PaymentRequired; //context.Response.StatusDescription = "Payment Required."; - return; - } + return Task.CompletedTask; + } + + return InternalInvoke(context); + } + private async Task InternalInvoke(HttpContext context) + { try { switch ((context.Request.Query[FilesLinkUtility.Action].FirstOrDefault() ?? "").ToLower()) @@ -228,13 +234,13 @@ namespace ASC.Web.Files throw new HttpException((int)HttpStatusCode.InternalServerError, FilesCommonResource.ErrorMassage_BadRequest, e); } } - - private async Task BulkDownloadFile(HttpContext context) - { + + private Task BulkDownloadFile(HttpContext context) + { if (!SecurityContext.IsAuthenticated) { context.Response.StatusCode = (int)HttpStatusCode.Forbidden; - return; + return Task.CompletedTask; } var ext = CompressToArchive.GetExt(ServiceProvider, context.Request.Query["ext"]); @@ -245,18 +251,22 @@ namespace ASC.Web.Files { Logger.ErrorFormat("BulkDownload file error. File is not exist on storage. UserId: {0}.", AuthContext.CurrentAccount.ID); context.Response.StatusCode = (int)HttpStatusCode.NotFound; - return; + return Task.CompletedTask; } if (store.IsSupportedPreSignedUri) { var url = store.GetPreSignedUri(FileConstant.StorageDomainTmp, path, TimeSpan.FromHours(1), null).ToString(); context.Response.Redirect(url); - return; - } - - context.Response.Clear(); + return Task.CompletedTask; + } + + context.Response.Clear(); + return InternalBulkDownloadFile(context, store, path, ext); + } + private async Task InternalBulkDownloadFile(HttpContext context, IDataStore store, string path, string ext) + { try { var flushed = false; @@ -1041,9 +1051,9 @@ namespace ASC.Web.Files { return file.ID + ":" + file.Version + ":" + file.Title.GetHashCode() + ":" + file.ContentLength; } - - private async Task CreateFile(HttpContext context) - { + + private Task CreateFile(HttpContext context) + { if (!SecurityContext.IsAuthenticated) { //var refererURL = context.Request.GetUrlRewriter().AbsoluteUri; @@ -1051,9 +1061,14 @@ namespace ASC.Web.Files //context.Session["refererURL"] = refererURL; var authUrl = "~/Auth.aspx"; context.Response.Redirect(authUrl, true); - return; - } + return Task.CompletedTask; + } + + return InternalCreateFile(context); + } + private async Task InternalCreateFile(HttpContext context) + { var folderId = context.Request.Query[FilesLinkUtility.FolderId].FirstOrDefault(); if (string.IsNullOrEmpty(folderId)) { @@ -1070,11 +1085,12 @@ namespace ASC.Web.Files await CreateFile(context, folderId); } } - } - - private async Task CreateFile(HttpContext context, T folderId) - { - var responseMessage = context.Request.Query["response"] == "message"; + } + + private Task CreateFile(HttpContext context, T folderId) + { + var responseMessage = context.Request.Query["response"] == "message"; + Folder folder; var folderDao = DaoFactory.GetFolderDao(); @@ -1100,28 +1116,40 @@ namespace ASC.Web.Files } catch (Exception ex) { - Logger.Error(ex); - if (responseMessage) - { - await context.Response.WriteAsync("error: " + ex.Message); - return; - } - context.Response.Redirect(PathProvider.StartURL + "#error/" + HttpUtility.UrlEncode(ex.Message), true); - return; + return InternalWriteError(context, ex, responseMessage); } FileMarker.MarkAsNew(file); if (responseMessage) { - await context.Response.WriteAsync("ok: " + string.Format(FilesCommonResource.MessageFileCreated, folder.Title)); - return; + return InternalWriteOk(context, folder); } context.Response.Redirect( (context.Request.Query["openfolder"].FirstOrDefault() ?? "").Equals("true") ? PathProvider.GetFolderUrlById(file.FolderID) - : (FilesLinkUtility.GetFileWebEditorUrl(file.ID) + "#message/" + HttpUtility.UrlEncode(string.Format(FilesCommonResource.MessageFileCreated, folder.Title)))); + : (FilesLinkUtility.GetFileWebEditorUrl(file.ID) + "#message/" + HttpUtility.UrlEncode(string.Format(FilesCommonResource.MessageFileCreated, folder.Title)))); + + return Task.CompletedTask; + } + + private async Task InternalWriteError(HttpContext context, Exception ex, bool responseMessage) + { + Logger.Error(ex); + + if (responseMessage) + { + await context.Response.WriteAsync("error: " + ex.Message); + return; + } + context.Response.Redirect(PathProvider.StartURL + "#error/" + HttpUtility.UrlEncode(ex.Message), true); + return; + } + + private async Task InternalWriteOk(HttpContext context, Folder folder) + { + await context.Response.WriteAsync("ok: " + string.Format(FilesCommonResource.MessageFileCreated, folder.Title)); } private File CreateFileFromTemplate(Folder folder, string fileTitle, string docType) @@ -1264,10 +1292,10 @@ namespace ASC.Web.Files { await TrackFile(context, q.FirstOrDefault() ?? ""); } - } - - private async Task TrackFile(HttpContext context, T fileId) - { + } + + private Task TrackFile(HttpContext context, T fileId) + { var auth = context.Request.Query[FilesLinkUtility.AuthKey].FirstOrDefault(); Logger.Debug("DocService track fileid: " + fileId); @@ -1277,8 +1305,13 @@ namespace ASC.Web.Files { Logger.ErrorFormat("DocService track auth error: {0}, {1}: {2}", validateResult.ToString(), FilesLinkUtility.AuthKey, auth); throw new HttpException((int)HttpStatusCode.Forbidden, FilesCommonResource.ErrorMassage_SecurityException); - } + } + + return InternalTrackFile(context, fileId); + } + private async Task InternalTrackFile(HttpContext context, T fileId) + { DocumentServiceTracker.TrackerData fileData; try {