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;
This commit is contained in:
Фролов 2021-11-09 17:36:44 +05:00
parent 1fd6d3e062
commit 170693f445
10 changed files with 288 additions and 190 deletions

View File

@ -6,7 +6,10 @@ namespace AsbCloudApp.Services
{ {
public interface IDrillingProgramService public interface IDrillingProgramService
{ {
Task<FileInfoDto> GetAsync(int idWell, int fileChangerId, Task<int> CreateFileMarkAsync(FileMarkDto fileMarkDto, int idUser, CancellationToken token);
Task<FileInfoDto> GetOrCreateAsync(int idWell, int fileChangerId,
CancellationToken token = default); CancellationToken token = default);
Task<string> GetOrCreateSharedUrlAsync(int idWell, int idUser, CancellationToken token = default);
Task<int> MarkFileMarkAsDeletedAsync(int idMark, CancellationToken token);
} }
} }

View File

@ -11,7 +11,8 @@ namespace AsbCloudApp.Services
{ {
string RootPath { get; } string RootPath { get; }
Task<string> GetFileWebUrlAsync(FileInfoDto dto, string userLogin, Task<string> GetSharedUrlAsync(int idFileInfo, int idUser, CancellationToken token);
Task<string> GetSharedUrlAsync(FileInfoDto dto, int idUser,
CancellationToken token = default); CancellationToken token = default);
Task<FileInfoDto> SaveAsync(int idWell, int? idUser, int idCategory, string fileFullName, Stream fileStream, CancellationToken token = default); Task<FileInfoDto> 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 idCategory, string companyName = default, string fileName = default, DateTime begin = default, DateTime end = default,
int skip = 0, int take = 32, CancellationToken token = default); int skip = 0, int take = 32, CancellationToken token = default);
Task<FileInfoDto> GetInfoAsync(int fileId, Task<FileInfoDto> GetInfoAsync(int idFile,
CancellationToken token); CancellationToken token);
Task<int> MarkAsDeletedAsync(int idFile, Task<int> MarkAsDeletedAsync(int idFile,
@ -30,9 +31,9 @@ namespace AsbCloudApp.Services
string GetUrl(FileInfoDto fileInfo); string GetUrl(FileInfoDto fileInfo);
string GetUrl(int idFile); string GetUrl(int idFile);
string GetUrl(int idWell, int idCategory, int idFile, string dotExtention); string GetUrl(int idWell, int idCategory, int idFile, string dotExtention);
Task<int> CreateFileMarkAsync(int idWell, int idMarkType, int idProgramPartFile, string comment, Task<int> CreateFileMarkAsync(FileMarkDto fileMarkDto, int idUser, CancellationToken token);
int fileChangerId, string fileChangerLogin, CancellationToken token); Task<int> MarkFileMarkAsDeletedAsync(int idMark, CancellationToken token);
Task<int> MarkFileMarkAsDeletedAsync(int idWell, int idMark, CancellationToken token);
Task<FileInfoDto> MoveAsync(int idWell, int? idUser, int idCategory, string destinationFileName, string srcFileFullName, CancellationToken token = default); Task<FileInfoDto> MoveAsync(int idWell, int? idUser, int idCategory, string destinationFileName, string srcFileFullName, CancellationToken token = default);
Task<FileInfoDto> GetByMarkId(int idMark, CancellationToken token);
} }
} }

View File

@ -0,0 +1,15 @@
using System.Threading;
using System.Threading.Tasks;
using System.IO;
namespace AsbCloudApp.Services
{
public interface IFileShareService
{
Task<string> PublishFileToCloudAsync(string filePath, string originalName,
CancellationToken token);
Task DeleteFileAsync(string sharedFileId,
CancellationToken token = default);
}
}

View File

@ -1,21 +0,0 @@
using System.Threading;
using System.Threading.Tasks;
using System.IO;
namespace AsbCloudApp.Services
{
public interface IGoogleDriveService
{
Task<string> GetFileWebLinkAsync(string idFile,
CancellationToken token = default);
Task<string> CreateFolderAsync(string folderName,
CancellationToken token = default) ;
Task CreatePublicPermissionForFileAsync(string idFile,
CancellationToken token = default);
Task<string> UploadFileAsync(Stream file, string fileName, string fileMime,
string fileDescription, CancellationToken token = default);
Task DeleteFileAsync(string fileId,
CancellationToken token = default);
}
}

View File

@ -45,7 +45,7 @@ namespace AsbCloudInfrastructure
services.AddTransient<IDrillingProgramService, DrillingProgramService>(); services.AddTransient<IDrillingProgramService, DrillingProgramService>();
services.AddTransient<IDrillParamsService, DrillParamsService>(); services.AddTransient<IDrillParamsService, DrillParamsService>();
services.AddTransient<IDrillFlowChartService, DrillFlowChartService>(); services.AddTransient<IDrillFlowChartService, DrillFlowChartService>();
services.AddTransient<IGoogleDriveService, GoogleDriveService>(); services.AddTransient<IFileShareService, GoogleDriveService>();
// admin crud services: // admin crud services:
services.AddTransient<ICrudService<DepositDto>, CrudServiceBase<DepositDto, Deposit>>(); services.AddTransient<ICrudService<DepositDto>, CrudServiceBase<DepositDto, Deposit>>();

View File

@ -2,6 +2,7 @@
using AsbCloudApp.Services; using AsbCloudApp.Services;
using ClosedXML.Excel; using ClosedXML.Excel;
using ClosedXML.Excel.Drawings; using ClosedXML.Excel.Drawings;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
@ -25,40 +26,57 @@ namespace AsbCloudInfrastructure.Services
this.wellService = wellService; this.wellService = wellService;
} }
public async Task<FileInfoDto> GetAsync(int idWell, int fileChangerId, CancellationToken token = default) public async Task<string> 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); .ConfigureAwait(false);
if (fileInfo is null)
return null;
var sharedUrl = await fileService.GetSharedUrlAsync(fileInfo, idUser, token)
.ConfigureAwait(false);
return sharedUrl;
}
public async Task<FileInfoDto> 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) var well = await wellService.GetAsync(idWell, token)
.ConfigureAwait(false); .ConfigureAwait(false);
var matchFiles = await fileService.GetInfosByCategoryAsync(idWell, idFileCategoryDrillingProgram, token) var programs = await fileService.GetInfosByCategoryAsync(idWell, idFileCategoryDrillingProgram, token)
.ConfigureAwait(false); .ConfigureAwait(false);
if (matchFiles is not null && matchFiles.Any()) if (programs is not null && programs.Any() && programParts.Any())
{ {
matchFiles = matchFiles.OrderByDescending(f => f.UploadDate); programs = programs.OrderByDescending(f => f.UploadDate);
var matchFilesIterator = matchFiles.GetEnumerator(); var matchFilesIterator = programs.GetEnumerator();
matchFilesIterator.MoveNext(); matchFilesIterator.MoveNext();
var matchFile = matchFilesIterator.Current; 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; return matchFile;
else else
await fileService.DeleteAsync(matchFile.Id, token) await fileService.DeleteAsync(matchFile.Id, token)
.ConfigureAwait(false); .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 resultFileName = $"Программа бурения {well.Cluster} {well.Caption}.xlsx";
var filteredFilePaths = filesInfos var filteredFilePaths = programParts
.Where(f => f.Name != resultFileName &&
f.FileMarks != null &&
f.FileMarks.Any(file => file.IdMark == 0))
.Select(file => fileService.GetUrl(file)); .Select(file => fileService.GetUrl(file));
var tempResultFilePath = Path.Combine(Path.GetTempPath(), "drillingProgram", resultFileName); var tempResultFilePath = Path.Combine(Path.GetTempPath(), "drillingProgram", resultFileName);
@ -71,6 +89,49 @@ namespace AsbCloudInfrastructure.Services
return fileInfo; return fileInfo;
} }
public async Task<int> 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<int> 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<string> excelFilesNames, string resultExcelPath) private static void UniteExcelFiles(IEnumerable<string> excelFilesNames, string resultExcelPath)
{ {
var resultExcelFile = new XLWorkbook(XLEventTracking.Disabled); var resultExcelFile = new XLWorkbook(XLEventTracking.Disabled);

View File

@ -18,21 +18,32 @@ namespace AsbCloudInfrastructure.Services
private readonly IQueryable<AsbCloudDb.Model.FileInfo> dbSetConfigured; private readonly IQueryable<AsbCloudDb.Model.FileInfo> dbSetConfigured;
private readonly IAsbCloudDbContext db; 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"; RootPath = "files";
this.db = db; this.db = db;
this.fileShareService = fileShareService;
dbSetConfigured = db.Files dbSetConfigured = db.Files
.Include(f => f.Author) .Include(f => f.Author)
.ThenInclude(u => u.Company) .ThenInclude(u => u.Company)
.ThenInclude(c => c.CompanyType); .ThenInclude(c => c.CompanyType)
.Include(f => f.FileMarks)
this.googleDriveService = googleDriveService; .ThenInclude(m => m.User);
} }
public async Task<string> GetFileWebUrlAsync(FileInfoDto fileInfo, string userLogin, public async Task<string> 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<string> GetSharedUrlAsync(FileInfoDto fileInfo, int idUser,
CancellationToken token) CancellationToken token)
{ {
var fileWebUrl = fileInfo.PublishInfo?.WebStorageFileUrl; var fileWebUrl = fileInfo.PublishInfo?.WebStorageFileUrl;
@ -41,15 +52,16 @@ namespace AsbCloudInfrastructure.Services
return fileWebUrl; return fileWebUrl;
var relativePath = GetUrl(fileInfo); var relativePath = GetUrl(fileInfo);
var fileWebLink = await PublishFileToCloudAsync(relativePath, var sharedUrl = await fileShareService.PublishFileToCloudAsync(relativePath,
fileInfo.Name, token); fileInfo.Name, token);
await SaveWeblinkToFileInfo(fileInfo.Id, userLogin, fileWebLink, token);
return fileWebLink; await SaveWeblinkToFileInfo(fileInfo.Id, idUser, sharedUrl, token);
return sharedUrl;
} }
public async Task<FileInfoDto> MoveAsync(int idWell, int? idUser, int idCategory, public async Task<FileInfoDto> MoveAsync(int idWell, int? idUser, int idCategory,
string destinationFileName, string srcFilePath, CancellationToken token) string destinationFileName, string srcFilePath, CancellationToken token = default)
{ {
destinationFileName = Path.GetFileName(destinationFileName); destinationFileName = Path.GetFileName(destinationFileName);
srcFilePath = Path.GetFullPath(srcFilePath); srcFilePath = Path.GetFullPath(srcFilePath);
@ -122,7 +134,6 @@ namespace AsbCloudInfrastructure.Services
int idCategory, CancellationToken token) int idCategory, CancellationToken token)
{ {
var entities = await dbSetConfigured var entities = await dbSetConfigured
.Include(f => f.FileMarks)
.Where(e => e.IdWell == idWell && e.IdCategory == idCategory && e.IsDeleted == false) .Where(e => e.IdWell == idWell && e.IdCategory == idCategory && e.IsDeleted == false)
.AsNoTracking() .AsNoTracking()
.ToListAsync(token) .ToListAsync(token)
@ -137,16 +148,12 @@ namespace AsbCloudInfrastructure.Services
DateTime end = default, int skip = 0, int take = 32, CancellationToken token = default) DateTime end = default, int skip = 0, int take = 32, CancellationToken token = default)
{ {
var query = dbSetConfigured var query = dbSetConfigured
.Include(f => f.FileMarks)
.Where(e => e.IdWell == idWell && .Where(e => e.IdWell == idWell &&
e.IdCategory == idCategory && e.IdCategory == idCategory &&
!e.IsDeleted); !e.IsDeleted);
if (!string.IsNullOrEmpty(companyName)) if (!string.IsNullOrEmpty(companyName))
query = query query = query.Where(e => (e.Author == null) ||
.Include(file => file.Author)
.ThenInclude(a => a.Company)
.Where(e => (e.Author == null) ||
(e.Author.Company == null) || (e.Author.Company == null) ||
e.Author.Company.Caption.Contains(companyName)); e.Author.Company.Caption.Contains(companyName));
@ -187,13 +194,12 @@ namespace AsbCloudInfrastructure.Services
return result; return result;
} }
public async Task<FileInfoDto> GetInfoAsync(int fileId, public async Task<FileInfoDto> GetInfoAsync(int idFile,
CancellationToken token) CancellationToken token)
{ {
var entity = await dbSetConfigured var entity = await dbSetConfigured
.Include(f => f.FileMarks)
.AsNoTracking() .AsNoTracking()
.FirstOrDefaultAsync(f => f.Id == fileId, token) .FirstOrDefaultAsync(f => f.Id == idFile, token)
.ConfigureAwait(false); .ConfigureAwait(false);
if (entity is null) if (entity is null)
@ -233,9 +239,6 @@ namespace AsbCloudInfrastructure.Services
return await db.SaveChangesAsync(token).ConfigureAwait(false); 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) public string GetUrl(int idFile)
{ {
var fileInfo = db.Files var fileInfo = db.Files
@ -247,70 +250,62 @@ namespace AsbCloudInfrastructure.Services
return GetUrl(fileInfo.IdWell, fileInfo.IdCategory, fileInfo.Id, Path.GetExtension(fileInfo.Name)); 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) => public string GetUrl(int idWell, int idCategory, int idFile, string dotExtention) =>
Path.Combine(RootPath, idWell.ToString(), idCategory.ToString(), $"{idFile}{dotExtention}"); Path.Combine(RootPath, idWell.ToString(), idCategory.ToString(), $"{idFile}{dotExtention}");
public async Task<int> CreateFileMarkAsync(int idWell, int idMarkType, int idProgramPartFile, string comment, public async Task<FileInfoDto> GetByMarkId(int idMark,
int fileChangerId, string fileChangerLogin, CancellationToken token) CancellationToken token)
{
var entity = await dbSetConfigured
.FirstOrDefaultAsync(f => f.FileMarks.Any(m => m.Id == idMark), token)
.ConfigureAwait(false);
var dto = entity.Adapt<FileInfoDto>();
return dto;
}
public async Task<int> CreateFileMarkAsync(FileMarkDto fileMarkDto, int idUser, CancellationToken token)
{ {
var fileMark = await db.FileMarks var fileMark = await db.FileMarks
.FirstOrDefaultAsync(t => t.IdFile == idProgramPartFile && .FirstOrDefaultAsync(m => m.IdFile == fileMarkDto.IdFile &&
t.IdMarkType == idMarkType && t.IdUser == fileChangerId, token) m.IdMarkType == fileMarkDto.IdMarkType &&
m.IdUser == idUser &&
m.IsDeleted == false,
token)
.ConfigureAwait(false); .ConfigureAwait(false);
if (fileMark is not null) if (fileMark is not null)
return 0; return 0;
var newFileMark = new FileMark() var newFileMark = fileMarkDto.Adapt<FileMark>();
{ newFileMark.Id = default;
IdMarkType = idMarkType, newFileMark.DateCreated = DateTime.Now;
DateCreated = DateTime.Now, newFileMark.IdUser = idUser;
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);
db.FileMarks.Add(newFileMark); db.FileMarks.Add(newFileMark);
return await db.SaveChangesAsync(token); return await db.SaveChangesAsync(token);
} }
public async Task<int> MarkFileMarkAsDeletedAsync(int idWell, int idFile, public async Task<int> MarkFileMarkAsDeletedAsync(int idMark,
CancellationToken token) CancellationToken token)
{ {
var existingPrograms = await GetInfosByCategoryAsync(idWell, 14, token); var fileMark = await db.FileMarks
if (existingPrograms is not null && existingPrograms.Any()) .FirstOrDefaultAsync(m => m.Id == idMark, token)
await DeleteAsync(existingPrograms.First().Id, token);
return await MarkAsDeletedAsync(idFile, token);
}
private async Task<string> 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)
.ConfigureAwait(false); .ConfigureAwait(false);
await googleDriveService.CreatePublicPermissionForFileAsync(uploadedFileId, token) fileMark.IsDeleted = true;
.ConfigureAwait(false); return await db.SaveChangesAsync(token);
var webLink = await googleDriveService.GetFileWebLinkAsync(uploadedFileId, token) }
.ConfigureAwait(false);
return webLink;
}
private async Task<int> SaveWeblinkToFileInfo(int idFileInfo, string userLogin, string weblink, private async Task<int> SaveWeblinkToFileInfo(int idFileInfo, int idUser, string weblink,
CancellationToken token) CancellationToken token)
{ {
var fileInfo = await db.Files.FirstOrDefaultAsync(f => f.Id == idFileInfo, token) var fileInfo = await db.Files.FirstOrDefaultAsync(f => f.Id == idFileInfo, token)
.ConfigureAwait(false); .ConfigureAwait(false);
fileInfo.PublishInfo = new FilePublishInfo() fileInfo.PublishInfo = new FilePublishInfo()
{ {
PublisherLogin = userLogin, IdPublisher = idUser,
Date = DateTime.Now, Date = DateTime.Now,
WebStorageFileUrl = weblink WebStorageFileUrl = weblink
}; };

View File

@ -1,9 +1,8 @@
using System; using System;
using Google.Apis.Auth.OAuth2; using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Flows; using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Auth.OAuth2.Responses;
using Google.Apis.Drive.v3;
using Google.Apis.Services; using Google.Apis.Services;
using Google.Apis.Drive.v3;
using Google.Apis.Util.Store; using Google.Apis.Util.Store;
using Google.Apis.Drive.v3.Data; using Google.Apis.Drive.v3.Data;
using System.IO; using System.IO;
@ -12,51 +11,69 @@ using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using Google.Apis.Auth.OAuth2.Responses;
namespace AsbCloudInfrastructure.Services namespace AsbCloudInfrastructure.Services
{ {
public class GoogleDriveService : IGoogleDriveService, IDisposable public class GoogleDriveService : IFileShareService, IDisposable
{ {
private readonly DriveService service; 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"; const string applicationName = "FileSharing";
var username = "asbautodrilling@gmail.com"; 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 ClientSecrets = new ClientSecrets
{ {
ClientId = "1020584579240-f7amqg35qg7j94ta1ntgitajq27cgh49.apps.googleusercontent.com", ClientId = clientId,
ClientSecret = "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" 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<DriveService> 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 var newService = new DriveService(new BaseClientService.Initializer
{ {
HttpClientInitializer = credential, HttpClientInitializer = credential,
ApplicationName = applicationName ApplicationName = applicationName
}); });
service = newService; return newService;
} }
public async Task<IEnumerable<string>> GetAllFileNames() public async Task<IEnumerable<string>> GetAllFileNames()
{ {
var fileList = service.Files.List(); var fileList = service.Files.List();
fileList.Fields = "files(id, webViewLink, size)"; 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<Google.Apis.Drive.v3.Data.File>(); var result = new List<Google.Apis.Drive.v3.Data.File>();
string pageToken = null; string pageToken = null;
@ -133,9 +150,27 @@ namespace AsbCloudInfrastructure.Services
.ConfigureAwait(false); .ConfigureAwait(false);
} }
#pragma warning disable CA1816 // Методы Dispose должны вызывать SuppressFinalize
public void Dispose() public void Dispose()
{ {
service.Dispose(); service?.Dispose();
}
#pragma warning restore CA1816 // Методы Dispose должны вызывать SuppressFinalize
public async Task<string> 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;
} }
} }
} }

View File

@ -44,7 +44,7 @@ namespace AsbCloudWebApi.Controllers
idWell, token).ConfigureAwait(false)) idWell, token).ConfigureAwait(false))
return Forbid(); return Forbid();
var fileInfo = await drillingProgramService.GetAsync(idWell, var fileInfo = await drillingProgramService.GetOrCreateAsync(idWell,
(int)fileChangerId, token) (int)fileChangerId, token)
.ConfigureAwait(false); .ConfigureAwait(false);
@ -64,74 +64,59 @@ namespace AsbCloudWebApi.Controllers
/// <returns> Возвращает ссылку на файл программы бурения в облаке </returns> /// <returns> Возвращает ссылку на файл программы бурения в облаке </returns>
[HttpGet("webUrl")] [HttpGet("webUrl")]
[ProducesResponseType(typeof(string), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(string), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetFileWebLinkAsync(int idWell, CancellationToken token = default) public async Task<IActionResult> GetOrCreateSharedUrlAsync(int idWell, CancellationToken token = default)
{ {
var idCompany = User.GetCompanyId(); 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, !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
idWell, token).ConfigureAwait(false)) idWell, token).ConfigureAwait(false))
return Forbid(); return Forbid();
var fileInfo = await drillingProgramService.GetAsync(idWell, var sharedUrl = await drillingProgramService.GetOrCreateSharedUrlAsync(idWell,
(int)fileChangerId, token) (int)idUser, token)
.ConfigureAwait(false); .ConfigureAwait(false);
if (fileInfo is null) return Ok(sharedUrl);
return NoContent();
var userLogin = User.Identity?.Name ?? "";
var fileWebUrl = await fileService.GetFileWebUrlAsync(fileInfo,
userLogin, token);
return Ok(fileWebUrl);
} }
/// <summary> /// <summary>
/// Регистрирует совершенные действия с частями программы бурения /// Создает метку для файла входящего в проргамму бурения
/// </summary> /// </summary>
/// <param name="idWell"> id скважины </param> /// <param name="idWell"> id скважины </param>
/// <param name="idMark"> id действия </param> /// <param name="markDto">метка файла</param>
/// <param name="idFile"> id файла </param>
/// <param name="comment"> Комментарий </param>
/// <param name="token"> Токен отмены задачи </param> /// <param name="token"> Токен отмены задачи </param>
/// <returns></returns> /// <returns></returns>
[HttpPost("fileMark")] [HttpPost("fileMark")]
[ProducesResponseType(typeof(FileMarkDto), (int)System.Net.HttpStatusCode.OK)] public async Task<IActionResult> CreateFileMarkAsync(int idWell, FileMarkDto markDto, CancellationToken token = default)
public async Task<IActionResult> CreateFileMarkAsync(int idWell, int idMark,
int idFile, string comment, CancellationToken token = default)
{ {
var idCompany = User.GetCompanyId(); var idCompany = User.GetCompanyId();
var fileChangerId = User.GetUserId(); var idUser = User.GetUserId();
var fileChangerLogin = User.Identity?.Name ?? "";
if (idCompany is null || fileChangerId is null || if (idCompany is null || idUser is null ||
!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
idWell, token).ConfigureAwait(false)) idWell, token).ConfigureAwait(false))
return Forbid(); return Forbid();
var result = await fileService.CreateFileMarkAsync(idWell, idMark, var result = await drillingProgramService.CreateFileMarkAsync(markDto, (int)idUser, token)
idFile, comment, (int)fileChangerId, fileChangerLogin,
token)
.ConfigureAwait(false); .ConfigureAwait(false);
return Ok(result); return Ok(result);
} }
/// <summary> /// <summary>
/// Удаляет отметку о действии с файлом-частью программы бурения /// Помечает метку у файла входящего, в проргамму бурения, как удаленную
/// </summary> /// </summary>
/// <param name="idWell"> id скважины </param> /// <param name="idWell"> id скважины </param>
/// <param name="idFile"> id действия </param> /// <param name="idMark"> id метки </param>
/// <param name="token"> Токен отмены задачи </param> /// <param name="token"> Токен отмены задачи </param>
/// <returns></returns> /// <returns></returns>
[HttpDelete("fileMark")] [HttpDelete("fileMark")]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> DeleteFileMarkAsync(int idWell, int idFile, public async Task<IActionResult> DeleteFileMarkAsync(int idWell, int idMark,
CancellationToken token = default) CancellationToken token = default)
{ {
var idCompany = User.GetCompanyId(); var idCompany = User.GetCompanyId();
@ -140,8 +125,8 @@ namespace AsbCloudWebApi.Controllers
idWell, token).ConfigureAwait(false)) idWell, token).ConfigureAwait(false))
return Forbid(); return Forbid();
var result = await fileService.MarkFileMarkAsDeletedAsync(idWell, var result = await drillingProgramService.MarkFileMarkAsDeletedAsync(idMark, token)
idFile, token); .ConfigureAwait(false);
return Ok(result); return Ok(result);
} }

View File

@ -4,7 +4,6 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using System; using System;
using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
@ -66,30 +65,6 @@ namespace AsbCloudWebApi.Controllers
return Ok(); return Ok();
} }
/// <summary>
/// Возвращает информацию о файлах для скважины в выбраной категории
/// </summary>
/// <param name="idWell">id скважины</param>
/// <param name="idCategory">id категории файла</param>
/// <param name="token"> Токен отмены задачи </param>
/// <returns>Список информации о файлах в этой категории</returns>
[HttpGet]
[Route("category/{idCategory}")]
[ProducesResponseType(typeof(IEnumerable<FileInfoDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> 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);
}
/// <summary> /// <summary>
/// Возвращает информацию о файлах для скважины в выбраной категории /// Возвращает информацию о файлах для скважины в выбраной категории
/// </summary> /// </summary>
@ -171,7 +146,7 @@ namespace AsbCloudWebApi.Controllers
/// </summary> /// </summary>
/// <param name="idWell">id скважины</param> /// <param name="idWell">id скважины</param>
/// <param name="idFile">id запрашиваемого файла</param> /// <param name="idFile">id запрашиваемого файла</param>
/// <param name="token"> Токен отмены задачи </param> /// <param name="token">Токен отмены задачи </param>
/// <returns></returns> /// <returns></returns>
[HttpDelete("{idFile}")] [HttpDelete("{idFile}")]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
@ -188,5 +163,54 @@ namespace AsbCloudWebApi.Controllers
return Ok(result); return Ok(result);
} }
/// <summary>
/// Создает метку для файла
/// </summary>
/// <param name="idWell">id скважины </param>
/// <param name="markDto">метка файла</param>
/// <param name="token">Токен отмены задачи </param>
/// <returns></returns>
[HttpPost("fileMark")]
public async Task<IActionResult> 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);
}
/// <summary>
/// Помечает метку у файла как удаленную
/// </summary>
/// <param name="idWell">id скважины </param>
/// <param name="idMark">id метки </param>
/// <param name="token">Токен отмены задачи </param>
/// <returns></returns>
[HttpDelete("fileMark")]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> 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);
}
} }
} }