From 170693f445ba9256d2ad242544d9ab77ed79f7e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A4=D1=80=D0=BE=D0=BB=D0=BE=D0=B2?= Date: Tue, 9 Nov 2021 17:36:44 +0500 Subject: [PATCH] Refactor: FilesService move FileSharing functions to GoogleDriveService; FilesService.CreateFileMarkAsync() Move drillingProgram related logic into DrillingProgramService.CreateFileMarkAsync(); FilesService.MarkFileMarkAsDeletedAsync() Move drillingProgram related logic into DrillingProgramService.MarkFileMarkAsDeletedAsync(); IGoogleDriveService cleanup and rename to IFileShareService; GoogleDriveService check token before usage and resresh it id needeed; DrillingProgramController move logic to service; DrillingProgramController use dto; FileController remove unused method; --- .../Services/IDrillingProgramService.cs | 5 +- AsbCloudApp/Services/IFileService.cs | 11 +- AsbCloudApp/Services/IFileShareService.cs | 15 +++ AsbCloudApp/Services/IGoogleDriveService.cs | 21 ---- AsbCloudInfrastructure/DependencyInjection.cs | 2 +- .../Services/DrillingProgramService.cs | 91 +++++++++++--- .../Services/FileService.cs | 119 +++++++++--------- .../Services/GoogleDriveService.cs | 83 ++++++++---- .../Controllers/DrillingProgramController.cs | 55 +++----- AsbCloudWebApi/Controllers/FileController.cs | 76 +++++++---- 10 files changed, 288 insertions(+), 190 deletions(-) create mode 100644 AsbCloudApp/Services/IFileShareService.cs delete mode 100644 AsbCloudApp/Services/IGoogleDriveService.cs diff --git a/AsbCloudApp/Services/IDrillingProgramService.cs b/AsbCloudApp/Services/IDrillingProgramService.cs index ab91bde1..8ed7d04a 100644 --- a/AsbCloudApp/Services/IDrillingProgramService.cs +++ b/AsbCloudApp/Services/IDrillingProgramService.cs @@ -6,7 +6,10 @@ namespace AsbCloudApp.Services { public interface IDrillingProgramService { - Task GetAsync(int idWell, int fileChangerId, + Task CreateFileMarkAsync(FileMarkDto fileMarkDto, int idUser, CancellationToken token); + Task GetOrCreateAsync(int idWell, int fileChangerId, CancellationToken token = default); + Task GetOrCreateSharedUrlAsync(int idWell, int idUser, CancellationToken token = default); + Task MarkFileMarkAsDeletedAsync(int idMark, CancellationToken token); } } \ No newline at end of file diff --git a/AsbCloudApp/Services/IFileService.cs b/AsbCloudApp/Services/IFileService.cs index 2d413f1d..85cfff6b 100644 --- a/AsbCloudApp/Services/IFileService.cs +++ b/AsbCloudApp/Services/IFileService.cs @@ -11,7 +11,8 @@ namespace AsbCloudApp.Services { string RootPath { get; } - Task GetFileWebUrlAsync(FileInfoDto dto, string userLogin, + Task GetSharedUrlAsync(int idFileInfo, int idUser, CancellationToken token); + Task GetSharedUrlAsync(FileInfoDto dto, int idUser, CancellationToken token = default); Task SaveAsync(int idWell, int? idUser, int idCategory, string fileFullName, Stream fileStream, CancellationToken token = default); @@ -20,7 +21,7 @@ namespace AsbCloudApp.Services int idCategory, string companyName = default, string fileName = default, DateTime begin = default, DateTime end = default, int skip = 0, int take = 32, CancellationToken token = default); - Task GetInfoAsync(int fileId, + Task GetInfoAsync(int idFile, CancellationToken token); Task MarkAsDeletedAsync(int idFile, @@ -30,9 +31,9 @@ namespace AsbCloudApp.Services string GetUrl(FileInfoDto fileInfo); string GetUrl(int idFile); string GetUrl(int idWell, int idCategory, int idFile, string dotExtention); - Task CreateFileMarkAsync(int idWell, int idMarkType, int idProgramPartFile, string comment, - int fileChangerId, string fileChangerLogin, CancellationToken token); - Task MarkFileMarkAsDeletedAsync(int idWell, int idMark, CancellationToken token); + Task CreateFileMarkAsync(FileMarkDto fileMarkDto, int idUser, CancellationToken token); + Task MarkFileMarkAsDeletedAsync(int idMark, CancellationToken token); Task MoveAsync(int idWell, int? idUser, int idCategory, string destinationFileName, string srcFileFullName, CancellationToken token = default); + Task GetByMarkId(int idMark, CancellationToken token); } } diff --git a/AsbCloudApp/Services/IFileShareService.cs b/AsbCloudApp/Services/IFileShareService.cs new file mode 100644 index 00000000..2a6a2e96 --- /dev/null +++ b/AsbCloudApp/Services/IFileShareService.cs @@ -0,0 +1,15 @@ +using System.Threading; +using System.Threading.Tasks; +using System.IO; + +namespace AsbCloudApp.Services +{ + public interface IFileShareService + { + Task PublishFileToCloudAsync(string filePath, string originalName, + CancellationToken token); + + Task DeleteFileAsync(string sharedFileId, + CancellationToken token = default); + } +} \ No newline at end of file diff --git a/AsbCloudApp/Services/IGoogleDriveService.cs b/AsbCloudApp/Services/IGoogleDriveService.cs deleted file mode 100644 index 1b5d72ab..00000000 --- a/AsbCloudApp/Services/IGoogleDriveService.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System.Threading; -using System.Threading.Tasks; -using System.IO; - -namespace AsbCloudApp.Services -{ - public interface IGoogleDriveService - { - Task GetFileWebLinkAsync(string idFile, - CancellationToken token = default); - Task CreateFolderAsync(string folderName, - CancellationToken token = default) ; - - Task CreatePublicPermissionForFileAsync(string idFile, - CancellationToken token = default); - Task UploadFileAsync(Stream file, string fileName, string fileMime, - string fileDescription, CancellationToken token = default); - Task DeleteFileAsync(string fileId, - CancellationToken token = default); - } -} \ No newline at end of file diff --git a/AsbCloudInfrastructure/DependencyInjection.cs b/AsbCloudInfrastructure/DependencyInjection.cs index 373cf661..bcc361ea 100644 --- a/AsbCloudInfrastructure/DependencyInjection.cs +++ b/AsbCloudInfrastructure/DependencyInjection.cs @@ -45,7 +45,7 @@ namespace AsbCloudInfrastructure services.AddTransient(); services.AddTransient(); services.AddTransient(); - services.AddTransient(); + services.AddTransient(); // admin crud services: services.AddTransient, CrudServiceBase>(); diff --git a/AsbCloudInfrastructure/Services/DrillingProgramService.cs b/AsbCloudInfrastructure/Services/DrillingProgramService.cs index 3006414d..39b56468 100644 --- a/AsbCloudInfrastructure/Services/DrillingProgramService.cs +++ b/AsbCloudInfrastructure/Services/DrillingProgramService.cs @@ -2,6 +2,7 @@ using AsbCloudApp.Services; using ClosedXML.Excel; using ClosedXML.Excel.Drawings; +using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -25,40 +26,57 @@ namespace AsbCloudInfrastructure.Services this.wellService = wellService; } - public async Task GetAsync(int idWell, int fileChangerId, CancellationToken token = default) + public async Task GetOrCreateSharedUrlAsync(int idWell, int idUser, CancellationToken token = default) { - var filesInfos = await fileService.GetInfosByCategoryAsync(idWell, idFileCategoryDrillingProgramItems, token) + var fileInfo = await GetOrCreateAsync(idWell, idUser, token) .ConfigureAwait(false); + if (fileInfo is null) + return null; + + var sharedUrl = await fileService.GetSharedUrlAsync(fileInfo, idUser, token) + .ConfigureAwait(false); + + return sharedUrl; + } + + public async Task GetOrCreateAsync(int idWell, int idUser, CancellationToken token = default) + { + var programParts = (await fileService.GetInfosByCategoryAsync(idWell, idFileCategoryDrillingProgramItems, token) + .ConfigureAwait(false)) + .Where(f => f.FileMarks?.Any(m => m.IdMarkType == 1 && !m.IsDeleted)??false); + var well = await wellService.GetAsync(idWell, token) .ConfigureAwait(false); - var matchFiles = await fileService.GetInfosByCategoryAsync(idWell, idFileCategoryDrillingProgram, token) + var programs = await fileService.GetInfosByCategoryAsync(idWell, idFileCategoryDrillingProgram, token) .ConfigureAwait(false); - if (matchFiles is not null && matchFiles.Any()) + if (programs is not null && programs.Any() && programParts.Any()) { - matchFiles = matchFiles.OrderByDescending(f => f.UploadDate); - var matchFilesIterator = matchFiles.GetEnumerator(); + programs = programs.OrderByDescending(f => f.UploadDate); + var matchFilesIterator = programs.GetEnumerator(); matchFilesIterator.MoveNext(); var matchFile = matchFilesIterator.Current; - while (matchFilesIterator.MoveNext()) - await fileService.DeleteAsync(matchFilesIterator.Current.Id, token) - .ConfigureAwait(false); - if (File.Exists(fileService.GetUrl(matchFile))) + if (programParts.All(pp => matchFile.UploadDate > pp.UploadDate) && + File.Exists(fileService.GetUrl(matchFile))) return matchFile; else await fileService.DeleteAsync(matchFile.Id, token) .ConfigureAwait(false); + + while (matchFilesIterator.MoveNext()) + await fileService.DeleteAsync(matchFilesIterator.Current.Id, token) + .ConfigureAwait(false); } - + + if (!programParts.Any()) + throw new FileNotFoundException("Нет частей для формирования программы бурения"); + var resultFileName = $"Программа бурения {well.Cluster} {well.Caption}.xlsx"; - var filteredFilePaths = filesInfos - .Where(f => f.Name != resultFileName && - f.FileMarks != null && - f.FileMarks.Any(file => file.IdMark == 0)) + var filteredFilePaths = programParts .Select(file => fileService.GetUrl(file)); var tempResultFilePath = Path.Combine(Path.GetTempPath(), "drillingProgram", resultFileName); @@ -71,6 +89,49 @@ namespace AsbCloudInfrastructure.Services return fileInfo; } + public async Task CreateFileMarkAsync(FileMarkDto fileMarkDto, int idUser, CancellationToken token) + { + var fileInfo = await fileService.GetInfoAsync(fileMarkDto.IdFile, token) + .ConfigureAwait(false); + + if (fileInfo.IdCategory != idFileCategoryDrillingProgramItems) + throw new ArgumentException($"Этот метод допустим только для файлов-частей программы бурения idCategory=={idFileCategoryDrillingProgramItems}.", nameof(fileMarkDto)); + + var result = await fileService.CreateFileMarkAsync(fileMarkDto, idUser, token) + .ConfigureAwait(false); + + var drillingPrograms = await fileService.GetInfosByCategoryAsync(fileInfo.IdWell, idFileCategoryDrillingProgram, token) + .ConfigureAwait(false); + + foreach (var drillingProgram in drillingPrograms) + await fileService.DeleteAsync(drillingProgram.Id, token) + .ConfigureAwait(false); + + return result; + } + + public async Task MarkFileMarkAsDeletedAsync(int idMark, + CancellationToken token) + { + var fileInfo = await fileService.GetByMarkId(idMark, token) + .ConfigureAwait(false); + + if (fileInfo.IdCategory != idFileCategoryDrillingProgramItems) + throw new ArgumentException($"Этот метод допустим только для файлов-частей программы бурения idCategory=={idFileCategoryDrillingProgramItems}.", nameof(idMark)); + + var result = await fileService.MarkFileMarkAsDeletedAsync(idMark, token) + .ConfigureAwait(false); + + var drillingPrograms = await fileService.GetInfosByCategoryAsync(fileInfo.IdWell, idFileCategoryDrillingProgram, token) + .ConfigureAwait(false); + + foreach (var drillingProgram in drillingPrograms) + await fileService.DeleteAsync(drillingProgram.Id, token) + .ConfigureAwait(false); + + return result; + } + private static void UniteExcelFiles(IEnumerable excelFilesNames, string resultExcelPath) { var resultExcelFile = new XLWorkbook(XLEventTracking.Disabled); diff --git a/AsbCloudInfrastructure/Services/FileService.cs b/AsbCloudInfrastructure/Services/FileService.cs index 0b8a8c5b..44ac3bae 100644 --- a/AsbCloudInfrastructure/Services/FileService.cs +++ b/AsbCloudInfrastructure/Services/FileService.cs @@ -18,21 +18,32 @@ namespace AsbCloudInfrastructure.Services private readonly IQueryable dbSetConfigured; private readonly IAsbCloudDbContext db; - private readonly IGoogleDriveService googleDriveService; + private readonly IFileShareService fileShareService; - public FileService(IAsbCloudDbContext db, IGoogleDriveService googleDriveService) + public FileService(IAsbCloudDbContext db, IFileShareService fileShareService) { RootPath = "files"; this.db = db; + this.fileShareService = fileShareService; dbSetConfigured = db.Files .Include(f => f.Author) .ThenInclude(u => u.Company) - .ThenInclude(c => c.CompanyType); - - this.googleDriveService = googleDriveService; + .ThenInclude(c => c.CompanyType) + .Include(f => f.FileMarks) + .ThenInclude(m => m.User); } - public async Task GetFileWebUrlAsync(FileInfoDto fileInfo, string userLogin, + public async Task GetSharedUrlAsync(int idFileInfo, int idUser, + CancellationToken token) + { + var fileInfo = await GetInfoAsync(idFileInfo, token); + if (fileInfo is null) + return null; + var sharedUrl = await GetSharedUrlAsync(fileInfo, idUser, token); + return sharedUrl; + } + + public async Task GetSharedUrlAsync(FileInfoDto fileInfo, int idUser, CancellationToken token) { var fileWebUrl = fileInfo.PublishInfo?.WebStorageFileUrl; @@ -41,15 +52,16 @@ namespace AsbCloudInfrastructure.Services return fileWebUrl; var relativePath = GetUrl(fileInfo); - var fileWebLink = await PublishFileToCloudAsync(relativePath, + var sharedUrl = await fileShareService.PublishFileToCloudAsync(relativePath, fileInfo.Name, token); - await SaveWeblinkToFileInfo(fileInfo.Id, userLogin, fileWebLink, token); - return fileWebLink; + await SaveWeblinkToFileInfo(fileInfo.Id, idUser, sharedUrl, token); + + return sharedUrl; } public async Task MoveAsync(int idWell, int? idUser, int idCategory, - string destinationFileName, string srcFilePath, CancellationToken token) + string destinationFileName, string srcFilePath, CancellationToken token = default) { destinationFileName = Path.GetFileName(destinationFileName); srcFilePath = Path.GetFullPath(srcFilePath); @@ -122,7 +134,6 @@ namespace AsbCloudInfrastructure.Services int idCategory, CancellationToken token) { var entities = await dbSetConfigured - .Include(f => f.FileMarks) .Where(e => e.IdWell == idWell && e.IdCategory == idCategory && e.IsDeleted == false) .AsNoTracking() .ToListAsync(token) @@ -137,16 +148,12 @@ namespace AsbCloudInfrastructure.Services DateTime end = default, int skip = 0, int take = 32, CancellationToken token = default) { var query = dbSetConfigured - .Include(f => f.FileMarks) .Where(e => e.IdWell == idWell && e.IdCategory == idCategory && !e.IsDeleted); if (!string.IsNullOrEmpty(companyName)) - query = query - .Include(file => file.Author) - .ThenInclude(a => a.Company) - .Where(e => (e.Author == null) || + query = query.Where(e => (e.Author == null) || (e.Author.Company == null) || e.Author.Company.Caption.Contains(companyName)); @@ -187,13 +194,12 @@ namespace AsbCloudInfrastructure.Services return result; } - public async Task GetInfoAsync(int fileId, + public async Task GetInfoAsync(int idFile, CancellationToken token) { var entity = await dbSetConfigured - .Include(f => f.FileMarks) .AsNoTracking() - .FirstOrDefaultAsync(f => f.Id == fileId, token) + .FirstOrDefaultAsync(f => f.Id == idFile, token) .ConfigureAwait(false); if (entity is null) @@ -233,9 +239,6 @@ namespace AsbCloudInfrastructure.Services return await db.SaveChangesAsync(token).ConfigureAwait(false); } - public string GetUrl(FileInfoDto fileInfo) => - GetUrl(fileInfo.IdWell, fileInfo.IdCategory, fileInfo.Id, Path.GetExtension(fileInfo.Name)); - public string GetUrl(int idFile) { var fileInfo = db.Files @@ -247,70 +250,62 @@ namespace AsbCloudInfrastructure.Services return GetUrl(fileInfo.IdWell, fileInfo.IdCategory, fileInfo.Id, Path.GetExtension(fileInfo.Name)); } + public string GetUrl(FileInfoDto fileInfo) => + GetUrl(fileInfo.IdWell, fileInfo.IdCategory, fileInfo.Id, Path.GetExtension(fileInfo.Name)); + public string GetUrl(int idWell, int idCategory, int idFile, string dotExtention) => Path.Combine(RootPath, idWell.ToString(), idCategory.ToString(), $"{idFile}{dotExtention}"); - public async Task CreateFileMarkAsync(int idWell, int idMarkType, int idProgramPartFile, string comment, - int fileChangerId, string fileChangerLogin, CancellationToken token) + public async Task GetByMarkId(int idMark, + CancellationToken token) + { + var entity = await dbSetConfigured + .FirstOrDefaultAsync(f => f.FileMarks.Any(m => m.Id == idMark), token) + .ConfigureAwait(false); + var dto = entity.Adapt(); + return dto; + } + + public async Task CreateFileMarkAsync(FileMarkDto fileMarkDto, int idUser, CancellationToken token) { var fileMark = await db.FileMarks - .FirstOrDefaultAsync(t => t.IdFile == idProgramPartFile && - t.IdMarkType == idMarkType && t.IdUser == fileChangerId, token) + .FirstOrDefaultAsync(m => m.IdFile == fileMarkDto.IdFile && + m.IdMarkType == fileMarkDto.IdMarkType && + m.IdUser == idUser && + m.IsDeleted == false, + token) .ConfigureAwait(false); if (fileMark is not null) return 0; - var newFileMark = new FileMark() - { - IdMarkType = idMarkType, - DateCreated = DateTime.Now, - IdFile = idProgramPartFile, - IdUser = fileChangerId, - Comment = comment - }; - - var existingPrograms = await GetInfosByCategoryAsync(idWell, 14, token); - if (existingPrograms is not null && existingPrograms.Any()) - await DeleteAsync(existingPrograms.First().Id, token); - + var newFileMark = fileMarkDto.Adapt(); + newFileMark.Id = default; + newFileMark.DateCreated = DateTime.Now; + newFileMark.IdUser = idUser; + db.FileMarks.Add(newFileMark); return await db.SaveChangesAsync(token); } - public async Task MarkFileMarkAsDeletedAsync(int idWell, int idFile, + public async Task MarkFileMarkAsDeletedAsync(int idMark, CancellationToken token) { - var existingPrograms = await GetInfosByCategoryAsync(idWell, 14, token); - if (existingPrograms is not null && existingPrograms.Any()) - await DeleteAsync(existingPrograms.First().Id, token); - - return await MarkAsDeletedAsync(idFile, token); - } - - private async Task PublishFileToCloudAsync(string filePath, string originalName, - CancellationToken token) - { - await using var fileStream = File.Open(filePath, FileMode.Open); - var uploadedFileId = await googleDriveService.UploadFileAsync(fileStream, originalName, - "", "uploaded", token) + var fileMark = await db.FileMarks + .FirstOrDefaultAsync(m => m.Id == idMark, token) .ConfigureAwait(false); - await googleDriveService.CreatePublicPermissionForFileAsync(uploadedFileId, token) - .ConfigureAwait(false); - var webLink = await googleDriveService.GetFileWebLinkAsync(uploadedFileId, token) - .ConfigureAwait(false); - - return webLink; - } + fileMark.IsDeleted = true; + return await db.SaveChangesAsync(token); + } - private async Task SaveWeblinkToFileInfo(int idFileInfo, string userLogin, string weblink, + private async Task SaveWeblinkToFileInfo(int idFileInfo, int idUser, string weblink, CancellationToken token) { var fileInfo = await db.Files.FirstOrDefaultAsync(f => f.Id == idFileInfo, token) .ConfigureAwait(false); fileInfo.PublishInfo = new FilePublishInfo() { - PublisherLogin = userLogin, + IdPublisher = idUser, Date = DateTime.Now, WebStorageFileUrl = weblink }; diff --git a/AsbCloudInfrastructure/Services/GoogleDriveService.cs b/AsbCloudInfrastructure/Services/GoogleDriveService.cs index c553c2d8..fb1a712d 100644 --- a/AsbCloudInfrastructure/Services/GoogleDriveService.cs +++ b/AsbCloudInfrastructure/Services/GoogleDriveService.cs @@ -1,9 +1,8 @@ using System; using Google.Apis.Auth.OAuth2; using Google.Apis.Auth.OAuth2.Flows; -using Google.Apis.Auth.OAuth2.Responses; -using Google.Apis.Drive.v3; using Google.Apis.Services; +using Google.Apis.Drive.v3; using Google.Apis.Util.Store; using Google.Apis.Drive.v3.Data; using System.IO; @@ -12,51 +11,69 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; using AsbCloudApp.Services; +using Google.Apis.Auth.OAuth2.Responses; namespace AsbCloudInfrastructure.Services { - public class GoogleDriveService : IGoogleDriveService, IDisposable + public class GoogleDriveService : IFileShareService, IDisposable { private readonly DriveService service; - - public GoogleDriveService() - { // ключи для почты asbautodrilling@gmail.com. - var tokenResponse = new TokenResponse - { - AccessToken = "ya29.a0ARrdaM-lM7q0TIC_DXixR4oW63QUftjSPHl-8nIdvZwtqA8Z1bXtlYpDrQXj9UFTjW8FW8uqPMrdamUSp4kO4a9JX7FddkBWxaJ_omSJpqzDfnHTHA_7-zGMUohaAsmPLsQtFz_GUmB5ZoVLmA8xWdbJxVxU", - RefreshToken = "1//04FeDguc19IfgCgYIARAAGAQSNwF-L9Ir8U7wX2seanUzsxXXGgFzOYQqjbtN9O27ZZybbOobZjVAo_4_eFNLMX1ElPKOFVWsrJQ" - }; - var applicationName = "Files"; - var username = "asbautodrilling@gmail.com"; + const string applicationName = "FileSharing"; + const string username = "asbautodrilling@gmail.com"; + const string redirectUri = "http://autodrilling.naftagaz.com/AuthCallback/IndexAsync"; + const string clientId = "1020584579240-f7amqg35qg7j94ta1ntgitajq27cgh49.apps.googleusercontent.com"; + const string clientSecret = "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"; + const string authorizationCode = "4/0AX4XfWgwsZ5QIGwAbuyOyA9oGfcHVIhduERn3wUBVL04TPF1unHf5zWr58nWdLlDDlYBIA"; + const string refreshToken = "1//04n0Xn0AxQbN6CgYIARAAGAQSNwF-L9Ir-Lo-3BAskEKuy-SmllhhjYrmAzmZ2h9GaUNqEQjTIpb9wOanarU2JPI3zOj_cyYVRm4"; - var apiCodeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer + static readonly IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = new ClientSecrets { - ClientId = "1020584579240-f7amqg35qg7j94ta1ntgitajq27cgh49.apps.googleusercontent.com", - ClientSecret = "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" + ClientId = clientId, + ClientSecret = clientSecret }, - Scopes = new[] {DriveService.Scope.Drive}, - DataStore = new FileDataStore(applicationName) + + Scopes = new[] { DriveService.Scope.Drive }, + DataStore = new FileDataStore(applicationName), }); - var credential = new UserCredential(apiCodeFlow, username, tokenResponse); + public GoogleDriveService() + { + service = MakeDriveServiceAsync(CancellationToken.None).Result; + } + + ~GoogleDriveService() + { + Dispose(); + } + + private async Task MakeDriveServiceAsync(CancellationToken cancellationToken) + { + var token = await flow.LoadTokenAsync(username, cancellationToken).ConfigureAwait(false); + + if (flow.ShouldForceTokenRetrieval() || token is null || token.IsExpired(flow.Clock)) + { + token = await flow.RefreshTokenAsync(clientId, refreshToken, cancellationToken).ConfigureAwait(false); + //token = await flow.ExchangeCodeForTokenAsync(clientId, authorizationCode, redirectUri, cancellationToken).ConfigureAwait(false); + await flow.DataStore.StoreAsync(username, token).ConfigureAwait(false); + } + + var credential = new UserCredential(flow, username, token); var newService = new DriveService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = applicationName }); - service = newService; + return newService; } - + public async Task> GetAllFileNames() { var fileList = service.Files.List(); fileList.Fields = "files(id, webViewLink, size)"; - //fileList.Q =$"mimeType!='application/vnd.google-apps.folder' and '{folder}' in parents"; - //fileList.Fields = "nextPageToken, files(id, name, size, mimeType)"; var result = new List(); string pageToken = null; @@ -133,9 +150,27 @@ namespace AsbCloudInfrastructure.Services .ConfigureAwait(false); } +#pragma warning disable CA1816 // Методы Dispose должны вызывать SuppressFinalize public void Dispose() { - service.Dispose(); + service?.Dispose(); + } +#pragma warning restore CA1816 // Методы Dispose должны вызывать SuppressFinalize + + public async Task PublishFileToCloudAsync(string filePath, string originalName, CancellationToken token) + { + await using var fileStream = System.IO.File.Open(filePath, FileMode.Open); + var uploadedFileId = await UploadFileAsync(fileStream, originalName, + "", "uploaded", token) + .ConfigureAwait(false); + + await CreatePublicPermissionForFileAsync(uploadedFileId, token) + .ConfigureAwait(false); + + var webLink = await GetFileWebLinkAsync(uploadedFileId, token) + .ConfigureAwait(false); + + return webLink; } } } \ No newline at end of file diff --git a/AsbCloudWebApi/Controllers/DrillingProgramController.cs b/AsbCloudWebApi/Controllers/DrillingProgramController.cs index 720817a9..5807a430 100644 --- a/AsbCloudWebApi/Controllers/DrillingProgramController.cs +++ b/AsbCloudWebApi/Controllers/DrillingProgramController.cs @@ -44,7 +44,7 @@ namespace AsbCloudWebApi.Controllers idWell, token).ConfigureAwait(false)) return Forbid(); - var fileInfo = await drillingProgramService.GetAsync(idWell, + var fileInfo = await drillingProgramService.GetOrCreateAsync(idWell, (int)fileChangerId, token) .ConfigureAwait(false); @@ -64,74 +64,59 @@ namespace AsbCloudWebApi.Controllers /// Возвращает ссылку на файл программы бурения в облаке [HttpGet("webUrl")] [ProducesResponseType(typeof(string), (int)System.Net.HttpStatusCode.OK)] - public async Task GetFileWebLinkAsync(int idWell, CancellationToken token = default) + public async Task GetOrCreateSharedUrlAsync(int idWell, CancellationToken token = default) { var idCompany = User.GetCompanyId(); - var fileChangerId = User.GetUserId(); + var idUser = User.GetUserId(); - if (idCompany is null || fileChangerId is null || + if (idCompany is null || idUser is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token).ConfigureAwait(false)) return Forbid(); - var fileInfo = await drillingProgramService.GetAsync(idWell, - (int)fileChangerId, token) + var sharedUrl = await drillingProgramService.GetOrCreateSharedUrlAsync(idWell, + (int)idUser, token) .ConfigureAwait(false); - if (fileInfo is null) - return NoContent(); - - var userLogin = User.Identity?.Name ?? ""; - - var fileWebUrl = await fileService.GetFileWebUrlAsync(fileInfo, - userLogin, token); - - return Ok(fileWebUrl); + return Ok(sharedUrl); } - + /// - /// Регистрирует совершенные действия с частями программы бурения + /// Создает метку для файла входящего в проргамму бурения /// /// id скважины - /// id действия - /// id файла - /// Комментарий + /// метка файла /// Токен отмены задачи /// [HttpPost("fileMark")] - [ProducesResponseType(typeof(FileMarkDto), (int)System.Net.HttpStatusCode.OK)] - public async Task CreateFileMarkAsync(int idWell, int idMark, - int idFile, string comment, CancellationToken token = default) + public async Task CreateFileMarkAsync(int idWell, FileMarkDto markDto, CancellationToken token = default) { var idCompany = User.GetCompanyId(); - var fileChangerId = User.GetUserId(); - var fileChangerLogin = User.Identity?.Name ?? ""; + var idUser = User.GetUserId(); - if (idCompany is null || fileChangerId is null || + if (idCompany is null || idUser is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token).ConfigureAwait(false)) return Forbid(); - var result = await fileService.CreateFileMarkAsync(idWell, idMark, - idFile, comment, (int)fileChangerId, fileChangerLogin, - token) + var result = await drillingProgramService.CreateFileMarkAsync(markDto, (int)idUser, token) .ConfigureAwait(false); return Ok(result); } - + /// - /// Удаляет отметку о действии с файлом-частью программы бурения + /// Помечает метку у файла входящего, в проргамму бурения, как удаленную /// /// id скважины - /// id действия + /// id метки /// Токен отмены задачи /// [HttpDelete("fileMark")] [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)] - public async Task DeleteFileMarkAsync(int idWell, int idFile, + public async Task DeleteFileMarkAsync(int idWell, int idMark, CancellationToken token = default) { var idCompany = User.GetCompanyId(); @@ -140,8 +125,8 @@ namespace AsbCloudWebApi.Controllers idWell, token).ConfigureAwait(false)) return Forbid(); - var result = await fileService.MarkFileMarkAsDeletedAsync(idWell, - idFile, token); + var result = await drillingProgramService.MarkFileMarkAsDeletedAsync(idMark, token) + .ConfigureAwait(false); return Ok(result); } diff --git a/AsbCloudWebApi/Controllers/FileController.cs b/AsbCloudWebApi/Controllers/FileController.cs index 28cf1d3b..1e659061 100644 --- a/AsbCloudWebApi/Controllers/FileController.cs +++ b/AsbCloudWebApi/Controllers/FileController.cs @@ -4,7 +4,6 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; -using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; @@ -66,30 +65,6 @@ namespace AsbCloudWebApi.Controllers return Ok(); } - /// - /// Возвращает информацию о файлах для скважины в выбраной категории - /// - /// id скважины - /// id категории файла - /// Токен отмены задачи - /// Список информации о файлах в этой категории - [HttpGet] - [Route("category/{idCategory}")] - [ProducesResponseType(typeof(IEnumerable), (int)System.Net.HttpStatusCode.OK)] - public async Task GetInfosByCategoryAsync([FromRoute] int idWell, int idCategory, CancellationToken token = default) - { - int? idCompany = User.GetCompanyId(); - - if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, - idWell, token).ConfigureAwait(false)) - return Forbid(); - - var filesInfo = await fileService.GetInfosByCategoryAsync(idWell, idCategory, token) - .ConfigureAwait(false); - - return Ok(filesInfo); - } - /// /// Возвращает информацию о файлах для скважины в выбраной категории /// @@ -171,7 +146,7 @@ namespace AsbCloudWebApi.Controllers /// /// id скважины /// id запрашиваемого файла - /// Токен отмены задачи + /// Токен отмены задачи /// [HttpDelete("{idFile}")] [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)] @@ -188,5 +163,54 @@ namespace AsbCloudWebApi.Controllers return Ok(result); } + + /// + /// Создает метку для файла + /// + /// id скважины + /// метка файла + /// Токен отмены задачи + /// + [HttpPost("fileMark")] + public async Task CreateFileMarkAsync(int idWell, FileMarkDto markDto, CancellationToken token = default) + { + var idCompany = User.GetCompanyId(); + + var idUser = User.GetUserId(); + + if (idCompany is null || idUser is null || + !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, + idWell, token).ConfigureAwait(false)) + return Forbid(); + + var result = await fileService.CreateFileMarkAsync(markDto, (int)idUser, token) + .ConfigureAwait(false); + + return Ok(result); + } + + /// + /// Помечает метку у файла как удаленную + /// + /// id скважины + /// id метки + /// Токен отмены задачи + /// + [HttpDelete("fileMark")] + [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)] + public async Task DeleteFileMarkAsync(int idWell, int idMark, + CancellationToken token = default) + { + var idCompany = User.GetCompanyId(); + + if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, + idWell, token).ConfigureAwait(false)) + return Forbid(); + + var result = await fileService.MarkFileMarkAsDeletedAsync(idMark, token) + .ConfigureAwait(false); + + return Ok(result); + } } }