forked from ddrilling/AsbCloudServer
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:
parent
1fd6d3e062
commit
170693f445
@ -6,7 +6,10 @@ namespace AsbCloudApp.Services
|
||||
{
|
||||
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);
|
||||
Task<string> GetOrCreateSharedUrlAsync(int idWell, int idUser, CancellationToken token = default);
|
||||
Task<int> MarkFileMarkAsDeletedAsync(int idMark, CancellationToken token);
|
||||
}
|
||||
}
|
@ -11,7 +11,8 @@ namespace AsbCloudApp.Services
|
||||
{
|
||||
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);
|
||||
|
||||
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 skip = 0, int take = 32, CancellationToken token = default);
|
||||
|
||||
Task<FileInfoDto> GetInfoAsync(int fileId,
|
||||
Task<FileInfoDto> GetInfoAsync(int idFile,
|
||||
CancellationToken token);
|
||||
|
||||
Task<int> 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<int> CreateFileMarkAsync(int idWell, int idMarkType, int idProgramPartFile, string comment,
|
||||
int fileChangerId, string fileChangerLogin, CancellationToken token);
|
||||
Task<int> MarkFileMarkAsDeletedAsync(int idWell, int idMark, CancellationToken token);
|
||||
Task<int> CreateFileMarkAsync(FileMarkDto fileMarkDto, int idUser, CancellationToken token);
|
||||
Task<int> MarkFileMarkAsDeletedAsync(int idMark, CancellationToken token);
|
||||
Task<FileInfoDto> MoveAsync(int idWell, int? idUser, int idCategory, string destinationFileName, string srcFileFullName, CancellationToken token = default);
|
||||
Task<FileInfoDto> GetByMarkId(int idMark, CancellationToken token);
|
||||
}
|
||||
}
|
||||
|
15
AsbCloudApp/Services/IFileShareService.cs
Normal file
15
AsbCloudApp/Services/IFileShareService.cs
Normal 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);
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -45,7 +45,7 @@ namespace AsbCloudInfrastructure
|
||||
services.AddTransient<IDrillingProgramService, DrillingProgramService>();
|
||||
services.AddTransient<IDrillParamsService, DrillParamsService>();
|
||||
services.AddTransient<IDrillFlowChartService, DrillFlowChartService>();
|
||||
services.AddTransient<IGoogleDriveService, GoogleDriveService>();
|
||||
services.AddTransient<IFileShareService, GoogleDriveService>();
|
||||
|
||||
// admin crud services:
|
||||
services.AddTransient<ICrudService<DepositDto>, CrudServiceBase<DepositDto, Deposit>>();
|
||||
|
@ -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<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);
|
||||
|
||||
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)
|
||||
.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<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)
|
||||
{
|
||||
var resultExcelFile = new XLWorkbook(XLEventTracking.Disabled);
|
||||
|
@ -18,21 +18,32 @@ namespace AsbCloudInfrastructure.Services
|
||||
|
||||
private readonly IQueryable<AsbCloudDb.Model.FileInfo> 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<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)
|
||||
{
|
||||
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<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);
|
||||
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<FileInfoDto> GetInfoAsync(int fileId,
|
||||
public async Task<FileInfoDto> 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<int> CreateFileMarkAsync(int idWell, int idMarkType, int idProgramPartFile, string comment,
|
||||
int fileChangerId, string fileChangerLogin, CancellationToken token)
|
||||
public async Task<FileInfoDto> 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<FileInfoDto>();
|
||||
return dto;
|
||||
}
|
||||
|
||||
public async Task<int> 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<FileMark>();
|
||||
newFileMark.Id = default;
|
||||
newFileMark.DateCreated = DateTime.Now;
|
||||
newFileMark.IdUser = idUser;
|
||||
|
||||
db.FileMarks.Add(newFileMark);
|
||||
return await db.SaveChangesAsync(token);
|
||||
}
|
||||
|
||||
public async Task<int> MarkFileMarkAsDeletedAsync(int idWell, int idFile,
|
||||
public async Task<int> 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<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)
|
||||
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<int> SaveWeblinkToFileInfo(int idFileInfo, string userLogin, string weblink,
|
||||
private async Task<int> 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
|
||||
};
|
||||
|
@ -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<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
|
||||
{
|
||||
HttpClientInitializer = credential,
|
||||
ApplicationName = applicationName
|
||||
});
|
||||
service = newService;
|
||||
return newService;
|
||||
}
|
||||
|
||||
|
||||
public async Task<IEnumerable<string>> 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<Google.Apis.Drive.v3.Data.File>();
|
||||
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<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;
|
||||
}
|
||||
}
|
||||
}
|
@ -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
|
||||
/// <returns> Возвращает ссылку на файл программы бурения в облаке </returns>
|
||||
[HttpGet("webUrl")]
|
||||
[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 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);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Регистрирует совершенные действия с частями программы бурения
|
||||
/// Создает метку для файла входящего в проргамму бурения
|
||||
/// </summary>
|
||||
/// <param name="idWell"> id скважины </param>
|
||||
/// <param name="idMark"> id действия </param>
|
||||
/// <param name="idFile"> id файла </param>
|
||||
/// <param name="comment"> Комментарий </param>
|
||||
/// <param name="markDto">метка файла</param>
|
||||
/// <param name="token"> Токен отмены задачи </param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("fileMark")]
|
||||
[ProducesResponseType(typeof(FileMarkDto), (int)System.Net.HttpStatusCode.OK)]
|
||||
public async Task<IActionResult> CreateFileMarkAsync(int idWell, int idMark,
|
||||
int idFile, string comment, CancellationToken token = default)
|
||||
public async Task<IActionResult> 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);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Удаляет отметку о действии с файлом-частью программы бурения
|
||||
/// Помечает метку у файла входящего, в проргамму бурения, как удаленную
|
||||
/// </summary>
|
||||
/// <param name="idWell"> id скважины </param>
|
||||
/// <param name="idFile"> 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 idFile,
|
||||
public async Task<IActionResult> 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);
|
||||
}
|
||||
|
@ -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();
|
||||
}
|
||||
|
||||
/// <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>
|
||||
@ -171,7 +146,7 @@ namespace AsbCloudWebApi.Controllers
|
||||
/// </summary>
|
||||
/// <param name="idWell">id скважины</param>
|
||||
/// <param name="idFile">id запрашиваемого файла</param>
|
||||
/// <param name="token"> Токен отмены задачи </param>
|
||||
/// <param name="token">Токен отмены задачи </param>
|
||||
/// <returns></returns>
|
||||
[HttpDelete("{idFile}")]
|
||||
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
|
||||
@ -188,5 +163,54 @@ namespace AsbCloudWebApi.Controllers
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user