Skip to content

Commit

Permalink
Make 'await using' consistent and remove unused code
Browse files Browse the repository at this point in the history
Replaced 'using' with 'await using' for consistency in asynchronous context. Removed redundant methods and unused variables across multiple files to improve code clarity and efficiency. Updated access modifiers for better encapsulation and refactored magic strings to constants for maintainability.
  • Loading branch information
pavelbannov committed Dec 9, 2024
1 parent a8f8f28 commit 44478ab
Show file tree
Hide file tree
Showing 14 changed files with 57 additions and 98 deletions.
1 change: 0 additions & 1 deletion common/ASC.Core.Common/GlobalUsings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@
global using Amazon.SimpleEmail;
global using Amazon.SimpleEmail.Model;
global using ASC.Api.Core.Extensions;
global using ASC.Api.Core.Extensions;
global using ASC.AuditTrail.Models;
global using ASC.Collections;
global using ASC.Common;
Expand Down
4 changes: 2 additions & 2 deletions common/ASC.EventBus.RabbitMQ/EventBusRabbitMQ.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ private async Task SubsManager_OnEventRemovedAsync(object sender, string eventNa
await _persistentConnection.TryConnectAsync();
}

using var channel = await _persistentConnection.CreateModelAsync();
await using var channel = await _persistentConnection.CreateModelAsync();

await channel.QueueUnbindAsync(queue: _queueName,
exchange: EXCHANGE_NAME,
Expand Down Expand Up @@ -124,7 +124,7 @@ public async Task PublishAsync(IntegrationEvent @event)

_logger.TraceCreatingRabbitMQChannel(@event.Id, eventName);

using var channel = await _persistentConnection.CreateModelAsync();
await using var channel = await _persistentConnection.CreateModelAsync();

_logger.TraceDeclaringRabbitMQChannel(@event.Id);

Expand Down
5 changes: 0 additions & 5 deletions common/ASC.MessagingSystem/Core/HistorySocketManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,6 @@ await MakeRequest(
);
}
}

public void UpdateHistory(int tenantId, IEnumerable<DbFilesAuditReference> auditReference)
{
UpdateHistoryAsync(tenantId, auditReference).GetAwaiter().GetResult();
}

private static string GetRoom(int tenantId, int entryId, int entryType)
{
Expand Down
37 changes: 7 additions & 30 deletions common/ASC.MessagingSystem/Core/MessageFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,13 @@
namespace ASC.MessagingSystem.Core;

[Scope]
public class MessageFactory(AuthContext authContext,
TenantManager tenantManager,
ILogger<MessageFactory> logger,
IHttpContextAccessor httpContextAccessor)
public class MessageFactory(
AuthContext authContext,
TenantManager tenantManager,
ILogger<MessageFactory> logger,
IHttpContextAccessor httpContextAccessor)
{
public EventMessage Create(HttpRequest request, string initiator, DateTime? dateTime, MessageAction action, MessageTarget target,
IEnumerable<FilesAuditReference> references = null, params string[] description)
public EventMessage Create(HttpRequest request, string initiator, DateTime? dateTime, MessageAction action, MessageTarget target, IEnumerable<FilesAuditReference> references = null, params string[] description)
{
try
{
Expand All @@ -60,8 +60,7 @@ public EventMessage Create(HttpRequest request, string initiator, DateTime? date
}
}

public EventMessage Create(IDictionary<string, StringValues> headers, MessageAction action, MessageTarget target,
IEnumerable<FilesAuditReference> references = null, params string[] description)
public EventMessage Create(IDictionary<string, StringValues> headers, MessageAction action, MessageTarget target, IEnumerable<FilesAuditReference> references = null, params string[] description)
{
try
{
Expand Down Expand Up @@ -101,28 +100,6 @@ public EventMessage Create(IDictionary<string, StringValues> headers, MessageAct
}
}

public EventMessage Create(string initiator, MessageAction action, MessageTarget target, params string[] description)
{
try
{
return new EventMessage
{
Initiator = initiator,
Date = DateTime.UtcNow,
TenantId = tenantManager.GetCurrentTenantId(),
Action = action,
Description = description,
Target = target,
};
}
catch (Exception ex)
{
logger.ErrorWhileParseInitiatorMessage(action, ex);

return null;
}
}

public EventMessage Create(HttpRequest request, MessageUserData userData, MessageAction action)
{
try
Expand Down
62 changes: 31 additions & 31 deletions common/ASC.Migration/Migrators/Migrator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,27 +44,27 @@ public abstract class Migrator(
UserManagerWrapper userManagerWrapper)
: IAsyncDisposable
{
protected SecurityContext SecurityContext { get; } = securityContext;
private SecurityContext SecurityContext { get; } = securityContext;
protected UserManager UserManager { get; } = userManager;
protected TenantQuotaFeatureStatHelper TenantQuotaFeatureStatHelper { get; } = tenantQuotaFeatureStatHelper;
protected QuotaSocketManager QuotaSocketManager { get; } = quotaSocketManager;
protected FileStorageService FileStorageService { get; } = fileStorageService;
protected GlobalFolderHelper GlobalFolderHelper { get; } = globalFolderHelper;
protected IServiceProvider ServiceProvider { get; } = serviceProvider;
protected IDaoFactory DaoFactory { get; } = daoFactory;
protected EntryManager EntryManager { get; } = entryManager;
private TenantQuotaFeatureStatHelper TenantQuotaFeatureStatHelper { get; } = tenantQuotaFeatureStatHelper;
private QuotaSocketManager QuotaSocketManager { get; } = quotaSocketManager;
private FileStorageService FileStorageService { get; } = fileStorageService;
private GlobalFolderHelper GlobalFolderHelper { get; } = globalFolderHelper;
private IServiceProvider ServiceProvider { get; } = serviceProvider;
private IDaoFactory DaoFactory { get; } = daoFactory;
private EntryManager EntryManager { get; } = entryManager;
protected MigrationLogger MigrationLogger { get; } = migrationLogger;
protected AuthContext AuthContext { get; } = authContext;
private AuthContext AuthContext { get; } = authContext;
protected DisplayUserSettingsHelper DisplayUserSettingsHelper { get; } = displayUserSettingsHelper;
protected UserManagerWrapper UserManagerWrapper { get; } = userManagerWrapper;
private UserManagerWrapper UserManagerWrapper { get; } = userManagerWrapper;

public MigrationInfo MigrationInfo { get; set; }
protected IAccount _currentUser;
public MigrationInfo MigrationInfo { get; protected init; }
private IAccount _currentUser;
private Dictionary<string, MigrationUser> _usersForImport;
protected List<string> _importedUsers;
protected List<string> _failedUsers;
protected readonly string _folderKey = "folder";
protected readonly string _fileKey = "file";
private List<string> _importedUsers;
private List<string> _failedUsers;
private const string FolderKey = "folder";
private const string FileKey = "file";

protected double _lastProgressUpdate;
protected string _lastStatusUpdate;
Expand Down Expand Up @@ -332,20 +332,20 @@ private async Task MigrateStorageAsync(MigrationStorage storage, MigrationUser u
newFolder.Id = -1;
}

matchingFilesIds.Add($"{_folderKey}-{storage.RootKey}", newFolder);
matchingFilesIds.Add($"{FolderKey}-{storage.RootKey}", newFolder);
var orderedFolders = storage.Folders.OrderBy(f => f.Level);
foreach (var folder in orderedFolders)
{
if (!storage.ShouldImportSharedFolders ||
!storage.Securities.Any(s => s.EntryId == folder.Id && s.EntryType == 1) && matchingFilesIds[$"{_folderKey}-{folder.ParentId}"].Id != 0)
!storage.Securities.Any(s => s.EntryId == folder.Id && s.EntryType == 1) && matchingFilesIds[$"{FolderKey}-{folder.ParentId}"].Id != 0)
{
if (storage.Type == FolderType.BUNCH && !folder.Private)
{
newFolder = await FileStorageService.CreateRoomAsync(folder.Title, RoomType.PublicRoom, false, false, new List<FileShareParams>(), 0, null, false, null, null, null, null, null);
}
else
{
newFolder = await FileStorageService.CreateFolderAsync(matchingFilesIds[$"{_folderKey}-{folder.ParentId}"].Id, folder.Title);
newFolder = await FileStorageService.CreateFolderAsync(matchingFilesIds[$"{FolderKey}-{folder.ParentId}"].Id, folder.Title);
}

Log(string.Format(MigrationResource.CreateFolder, newFolder.Title));
Expand All @@ -355,7 +355,7 @@ private async Task MigrateStorageAsync(MigrationStorage storage, MigrationUser u
newFolder = ServiceProvider.GetService<Folder<int>>();
newFolder.Title = folder.Title;
}
matchingFilesIds.Add($"{_folderKey}-{folder.Id}", newFolder);
matchingFilesIds.Add($"{FolderKey}-{folder.Id}", newFolder);
}

var fileDao = DaoFactory.GetFileDao<int>();
Expand All @@ -367,7 +367,7 @@ private async Task MigrateStorageAsync(MigrationStorage storage, MigrationUser u
await using var fs = new FileStream(file.Path, FileMode.Open);

var newFile = ServiceProvider.GetService<File<int>>();
newFile.ParentId = matchingFilesIds[$"{_folderKey}-{file.Folder}"].Id;
newFile.ParentId = matchingFilesIds[$"{FolderKey}-{file.Folder}"].Id;
newFile.Comment = FilesCommonResource.CommentCreate;
newFile.Title = Path.GetFileName(file.Title);
newFile.ContentLength = fs.Length;
Expand All @@ -376,18 +376,18 @@ private async Task MigrateStorageAsync(MigrationStorage storage, MigrationUser u
newFile.Comment = file.Comment;
newFile.CreateOn = file.Created;
newFile.ModifiedOn = file.Modified;
if (matchingFilesIds.ContainsKey($"{_fileKey}-{file.Id}"))
if (matchingFilesIds.ContainsKey($"{FileKey}-{file.Id}"))
{
newFile.Id = matchingFilesIds[$"{_fileKey}-{file.Id}"].Id;
newFile.Id = matchingFilesIds[$"{FileKey}-{file.Id}"].Id;
}
if (!storage.ShouldImportSharedFolders || !storage.Securities.Any(s => s.EntryId == file.Folder && s.EntryType == 1) && newFile.ParentId != 0)
{
newFile = await fileDao.SaveFileAsync(newFile, fs);
Log(string.Format(MigrationResource.CreateFile, file.Title));
}
if (!matchingFilesIds.ContainsKey($"{_fileKey}-{file.Id}") && newFile.Id != 0)
if (!matchingFilesIds.ContainsKey($"{FileKey}-{file.Id}") && newFile.Id != 0)
{
matchingFilesIds.Add($"{_fileKey}-{file.Id}", newFile);
matchingFilesIds.Add($"{FileKey}-{file.Id}", newFile);
}
}
catch (Exception ex)
Expand Down Expand Up @@ -419,7 +419,7 @@ private async Task MigrateStorageAsync(MigrationStorage storage, MigrationUser u
var entryIsFile = security.EntryType == 2;
if (entryIsFile && storage.ShouldImportSharedFiles)
{
var key = $"{_fileKey}-{security.EntryId}";
var key = $"{FileKey}-{security.EntryId}";
if(!matchingFilesIds.ContainsKey(key))
{
continue;
Expand Down Expand Up @@ -478,7 +478,7 @@ private async Task MigrateStorageAsync(MigrationStorage storage, MigrationUser u
else if (storage.ShouldImportSharedFolders)
{
var localMatchingRoomIds = new Dictionary<int, FileEntry<int>>();
var key = $"{_folderKey}-{security.EntryId}";
var key = $"{FolderKey}-{security.EntryId}";

if (innerFolders.Contains(security.EntryId))
{
Expand Down Expand Up @@ -551,15 +551,15 @@ private async Task MigrateStorageAsync(MigrationStorage storage, MigrationUser u
newFile.VersionGroup = file.VersionGroup;
newFile.CreateOn = file.Created;
newFile.ModifiedOn = file.Modified;
if (matchingFilesIds.ContainsKey($"{_fileKey}-{file.Id}"))
if (matchingFilesIds.ContainsKey($"{FileKey}-{file.Id}"))
{
newFile.Id = matchingFilesIds[$"{_fileKey}-{file.Id}"].Id;
newFile.Id = matchingFilesIds[$"{FileKey}-{file.Id}"].Id;
}
newFile = await fileDao.SaveFileAsync(newFile, fs);
Log(string.Format(MigrationResource.CreateFile, file.Title));
if (!matchingFilesIds.ContainsKey($"{_fileKey}-{file.Id}"))
if (!matchingFilesIds.ContainsKey($"{FileKey}-{file.Id}"))
{
matchingFilesIds.Add($"{_fileKey}-{file.Id}", newFile);
matchingFilesIds.Add($"{FileKey}-{file.Id}", newFile);
}
}
catch(Exception ex)
Expand Down
6 changes: 3 additions & 3 deletions common/ASC.Migration/Migrators/Provider/WorkspaceMigrator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ private void ParseAndUnionStorage(MigrationStorage newStorage, MigrationStorage
destinationStorage.Folders = destinationStorage.Folders.Union(newStorage.Folders).ToList();
}

public async Task ParseUsersAsync(bool reportProgress, int count)
private async Task ParseUsersAsync(bool reportProgress, int count)
{
await using var stream = _dataReader.GetEntry("databases/core/core_user");
var data = new DataTable();
Expand Down Expand Up @@ -307,7 +307,7 @@ public async Task ParseUsersAsync(bool reportProgress, int count)
}
}

public void ParseStorage(MigrationStorage storage, string createBy = "")
private void ParseStorage(MigrationStorage storage, string createBy = "")
{
//docker unzip filesfolder_... instend of files/folder...
var folderFiles = _dataReader.GetDirectories("").Select(Path.GetFileName).FirstOrDefault(d => d.StartsWith("files"));
Expand Down Expand Up @@ -553,7 +553,7 @@ private void DbExtractFilesSecurity(MigrationStorage storage, string createBy)
}
}

public void ParseGroup()
private void ParseGroup()
{
using var streamGroup = _dataReader.GetEntry("databases/core/core_group");
var dataGroup = new DataTable();
Expand Down
2 changes: 1 addition & 1 deletion products/ASC.Files/Core/Core/Dao/TeamlabDao/SecurityDao.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1096,7 +1096,7 @@ public async Task<bool> IsSharedAsync(FileEntry<int> entry, IEnumerable<SubjectT
{
return entry.FileEntryType is FileEntryType.File &&
await filesDbContext.IsPureSharedAsync(tenantId, entry.Id.ToString(), FileEntryType.File, subjectTypes);
}
}

if (entry.RootFolderType is not FolderType.VirtualRooms)
{
Expand Down
4 changes: 2 additions & 2 deletions products/ASC.Files/Core/Core/Entries/FileEntry.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ public abstract class FileEntry : ICloneable
[JsonIgnore]
public FileHelper FileHelper { get; set; }

[JsonIgnore]
public Global Global { get; set; }
[JsonIgnore]
private Global Global { get; }

protected FileEntry() { }

Expand Down
3 changes: 2 additions & 1 deletion products/ASC.Files/Core/Helpers/DocumentService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -621,7 +621,8 @@ private sealed class ConvertionBody
public SpreadsheetLayout SpreadsheetLayout { get; set; }
public required string Url { get; set; }
public required string Region { get; set; }
public WatermarkOnDraw Watermark { get; set; } public string Token { get; set; }
public WatermarkOnDraw Watermark { get; set; }
public string Token { get; set; }
public PdfData Pdf { get; set; }

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ public class DocumentConfig<T>(
private string _key = string.Empty;
private FileReferenceData _referenceData;
public string GetFileType(File<T> file) => file.ConvertedExtension.Trim('.');
public InfoConfig<T> Info { get; set; } = infoConfig;
public InfoConfig<T> Info { get; } = infoConfig;
public bool IsLinkedForMe { get; set; }

public string Key
Expand Down
4 changes: 1 addition & 3 deletions products/ASC.Files/Server/Helpers/FilesControllerHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,16 +41,14 @@ public class FilesControllerHelper(IServiceProvider serviceProvider,
FileConverter fileConverter,
PathProvider pathProvider,
FileChecker fileChecker,
IDistributedCache distributedCache,
FillingFormResultDtoHelper fillingFormResultDtoHelper)
: FilesHelperBase(filesSettingsHelper,
fileUploader,
socketManager,
fileDtoHelper,
fileStorageService,
fileChecker,
httpContextAccessor,
distributedCache)
httpContextAccessor)
{
private readonly ILogger _logger = logger;

Expand Down
4 changes: 1 addition & 3 deletions products/ASC.Files/Server/Helpers/FilesHelperBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,12 @@ public abstract class FilesHelperBase(
FileDtoHelper fileDtoHelper,
FileStorageService fileStorageService,
FileChecker fileChecker,
IHttpContextAccessor httpContextAccessor,
IDistributedCache distributedCache)
IHttpContextAccessor httpContextAccessor)
{
protected readonly FilesSettingsHelper _filesSettingsHelper = filesSettingsHelper;
protected readonly FileUploader _fileUploader = fileUploader;
protected readonly FileDtoHelper _fileDtoHelper = fileDtoHelper;
protected readonly FileStorageService _fileStorageService = fileStorageService;
protected readonly IDistributedCache _distributedCache = distributedCache;

protected readonly FileChecker _fileChecker = fileChecker;
protected readonly IHttpContextAccessor _httpContextAccessor = httpContextAccessor;
Expand Down
15 changes: 4 additions & 11 deletions products/ASC.Files/Server/Helpers/SecurityControllerHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,26 +36,24 @@ public class SecurityControllerHelper(
IHttpContextAccessor httpContextAccessor,
FileShareDtoHelper fileShareDtoHelper,
FileShareParamsHelper fileShareParamsHelper,
FileChecker fileChecker,
IDistributedCache distributedCache)
FileChecker fileChecker)
: FilesHelperBase(
filesSettingsHelper,
fileUploader,
socketManager,
fileDtoHelper,
fileStorageService,
fileChecker,
httpContextAccessor,
distributedCache)
httpContextAccessor)
{
public IAsyncEnumerable<FileShareDto> GetFileSecurityInfoAsync<T>(T fileId)
{
return GetSecurityInfoAsync(new List<T> { fileId }, new List<T>());
return GetSecurityInfoAsync(new List<T> { fileId }, []);
}

public IAsyncEnumerable<FileShareDto> GetFolderSecurityInfoAsync<T>(T folderId)
{
return GetSecurityInfoAsync(new List<T>(), new List<T> { folderId });
return GetSecurityInfoAsync([], new List<T> { folderId });
}

public async IAsyncEnumerable<FileShareDto> GetSecurityInfoAsync<T>(IEnumerable<T> fileIds, IEnumerable<T> folderIds)
Expand All @@ -75,11 +73,6 @@ public async Task<bool> RemoveSecurityInfoAsync<T>(List<T> fileIds, List<T> fold
return true;
}

public IAsyncEnumerable<FileShareDto> SetFolderSecurityInfoAsync<T>(T folderId, IEnumerable<FileShareParams> share, bool notify, string sharingMessage)
{
return SetSecurityInfoAsync(new List<T>(), new List<T> { folderId }, share, notify, sharingMessage);
}

public async IAsyncEnumerable<FileShareDto> SetSecurityInfoAsync<T>(IEnumerable<T> fileIds, IEnumerable<T> folderIds, IEnumerable<FileShareParams> share, bool notify, string sharingMessage)
{
if (share != null && share.Any())
Expand Down
Loading

0 comments on commit 44478ab

Please sign in to comment.