forked from ddrilling/AsbCloudServer
remove file share service
This commit is contained in:
parent
6d63f8d02e
commit
0eb9410ecc
@ -39,11 +39,6 @@ namespace AsbCloudApp.Data
|
||||
/// </summary>
|
||||
public long Size { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// инфо о публикации файла на гугл диске
|
||||
/// </summary>
|
||||
public FilePublishInfoDto PublishInfo { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// DTO автора
|
||||
/// </summary>
|
||||
|
@ -1,25 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace AsbCloudApp.Data
|
||||
{
|
||||
/// <summary>
|
||||
/// èíôî î ôàéëå íà ãóãë äèñêå
|
||||
/// </summary>
|
||||
public class FilePublishInfoDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Ëîãèí ïîëüçîâàòåëÿ âûëîæèâøåãî ôàéë íà äèñê
|
||||
/// </summary>
|
||||
public string PublisherLogin { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// äàòà ïóáëèêàöèè
|
||||
/// </summary>
|
||||
public DateTime Date { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// ññûëêà äëÿ ñêà÷èâàíèÿ
|
||||
/// </summary>
|
||||
public string WebStorageFileUrl { get; set; }
|
||||
}
|
||||
}
|
@ -19,27 +19,6 @@ namespace AsbCloudApp.Services
|
||||
/// </summary>
|
||||
string RootPath { get; }
|
||||
|
||||
/// <summary>
|
||||
/// получить url Google drive
|
||||
/// </summary>
|
||||
/// <param name="idFileInfo"></param>
|
||||
/// <param name="idUser"></param>
|
||||
/// <param name="fileShareService"></param>
|
||||
/// <param name="token"></param>
|
||||
/// <returns></returns>
|
||||
Task<string> GetSharedUrlAsync(int idFileInfo, int idUser, IFileShareService fileShareService, CancellationToken token);
|
||||
|
||||
/// <summary>
|
||||
/// получить url Google drive
|
||||
/// </summary>
|
||||
/// <param name="dto"></param>
|
||||
/// <param name="idUser"></param>
|
||||
/// <param name="fileShareService"></param>
|
||||
/// <param name="token"></param>
|
||||
/// <returns></returns>
|
||||
Task<string> GetSharedUrlAsync(FileInfoDto dto, int idUser, IFileShareService fileShareService,
|
||||
CancellationToken token = default);
|
||||
|
||||
/// <summary>
|
||||
/// Сохранить файл
|
||||
/// </summary>
|
||||
|
@ -1,32 +0,0 @@
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AsbCloudApp.Services
|
||||
{
|
||||
//TODO: Óäàëèòü ýòîò ôóíêöèîíàë
|
||||
|
||||
/// <summary>
|
||||
/// Ñåðâèñ âûêëàäûâàíèÿ ôàéëà íà Google disk
|
||||
/// </summary>
|
||||
public interface IFileShareService
|
||||
{
|
||||
/// <summary>
|
||||
/// Îïóáëèêîâàòü
|
||||
/// </summary>
|
||||
/// <param name="filePath"></param>
|
||||
/// <param name="originalName"></param>
|
||||
/// <param name="token"></param>
|
||||
/// <returns></returns>
|
||||
Task<string> PublishFileToCloudAsync(string filePath, string originalName,
|
||||
CancellationToken token);
|
||||
|
||||
/// <summary>
|
||||
/// Óäàëèòü ïóáëèêàöèþ
|
||||
/// </summary>
|
||||
/// <param name="sharedFileId"></param>
|
||||
/// <param name="token"></param>
|
||||
/// <returns></returns>
|
||||
Task DeleteFileAsync(string sharedFileId,
|
||||
CancellationToken token = default);
|
||||
}
|
||||
}
|
6303
AsbCloudDb/Migrations/20220811101026_Remove_fileShare_service.Designer.cs
generated
Normal file
6303
AsbCloudDb/Migrations/20220811101026_Remove_fileShare_service.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,26 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace AsbCloudDb.Migrations
|
||||
{
|
||||
public partial class Remove_fileShare_service : Migration
|
||||
{
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "publish_info",
|
||||
table: "t_file_info");
|
||||
}
|
||||
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "publish_info",
|
||||
table: "t_file_info",
|
||||
type: "jsonb",
|
||||
nullable: true,
|
||||
comment: "Информация о файле в облаке");
|
||||
}
|
||||
}
|
||||
}
|
@ -709,11 +709,6 @@ namespace AsbCloudDb.Migrations
|
||||
.HasColumnName("name")
|
||||
.HasComment("Название файла");
|
||||
|
||||
b.Property<string>("PublishInfo")
|
||||
.HasColumnType("jsonb")
|
||||
.HasColumnName("publish_info")
|
||||
.HasComment("Информация о файле в облаке");
|
||||
|
||||
b.Property<long>("Size")
|
||||
.HasColumnType("bigint")
|
||||
.HasColumnName("file_size")
|
||||
|
@ -276,12 +276,6 @@ namespace AsbCloudDb.Model
|
||||
.HasJsonConversion();
|
||||
});
|
||||
|
||||
modelBuilder.Entity<FileInfo>(entity =>
|
||||
{
|
||||
entity.Property(e => e.PublishInfo)
|
||||
.HasJsonConversion();
|
||||
});
|
||||
|
||||
modelBuilder.Entity<FileMark>(entity =>
|
||||
{
|
||||
entity.HasOne(d => d.User)
|
||||
|
@ -33,9 +33,6 @@ namespace AsbCloudDb.Model
|
||||
[Column("file_size"), Comment("Размер файла")]
|
||||
public long Size { get; set; }
|
||||
|
||||
[Column("publish_info", TypeName = "jsonb"), Comment("Информация о файле в облаке")]
|
||||
public FilePublishInfo PublishInfo { get; set; }
|
||||
|
||||
[Column("is_deleted"), Comment("Удален ли файл")]
|
||||
public bool IsDeleted { get; set; }
|
||||
|
||||
|
@ -78,7 +78,6 @@ namespace AsbCloudInfrastructure
|
||||
services.AddFluentValidation();
|
||||
|
||||
services.AddScoped<IAsbCloudDbContext>(provider => provider.GetService<AsbCloudDbContext>());
|
||||
services.AddScoped<IFileShareService, GoogleDriveService>();
|
||||
services.AddScoped<IEmailService, EmailService>();
|
||||
|
||||
services.AddHostedService<OperationDetectionBackgroundService>();
|
||||
|
@ -434,7 +434,6 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
|
||||
IdCategory = fileEntity.IdCategory,
|
||||
IdWell = fileEntity.IdWell,
|
||||
Name = fileEntity.Name,
|
||||
PublishInfo = fileEntity.PublishInfo.Adapt<FilePublishInfoDto>(),
|
||||
Size = fileEntity.Size,
|
||||
UploadDate = fileEntity.UploadDate.ToRemoteDateTime(timezoneOffset),
|
||||
};
|
||||
|
@ -33,33 +33,6 @@ namespace AsbCloudInfrastructure.Services
|
||||
.Include(f => f.Well);
|
||||
}
|
||||
|
||||
public async Task<string> GetSharedUrlAsync(int idFileInfo, int idUser, IFileShareService fileShareService,
|
||||
CancellationToken token)
|
||||
{
|
||||
var fileInfo = await GetInfoAsync(idFileInfo, token);
|
||||
if (fileInfo is null)
|
||||
return null;
|
||||
var sharedUrl = await GetSharedUrlAsync(fileInfo, idUser, fileShareService, token);
|
||||
return sharedUrl;
|
||||
}
|
||||
|
||||
public async Task<string> GetSharedUrlAsync(FileInfoDto fileInfo, int idUser, IFileShareService fileShareService,
|
||||
CancellationToken token)
|
||||
{
|
||||
var fileWebUrl = fileInfo.PublishInfo?.WebStorageFileUrl;
|
||||
|
||||
if (!string.IsNullOrEmpty(fileWebUrl))
|
||||
return fileWebUrl;
|
||||
|
||||
var relativePath = GetUrl(fileInfo);
|
||||
var sharedUrl = await fileShareService.PublishFileToCloudAsync(relativePath,
|
||||
fileInfo.Name, token);
|
||||
|
||||
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 = default)
|
||||
{
|
||||
@ -357,21 +330,6 @@ namespace AsbCloudInfrastructure.Services
|
||||
fileMark.IsDeleted = true;
|
||||
|
||||
return await db.SaveChangesAsync(token);
|
||||
}
|
||||
|
||||
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()
|
||||
{
|
||||
IdPublisher = idUser,
|
||||
Date = DateTime.UtcNow,
|
||||
WebStorageFileUrl = weblink
|
||||
};
|
||||
|
||||
return await db.SaveChangesAsync(token).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,176 +0,0 @@
|
||||
using AsbCloudApp.Services;
|
||||
using Google.Apis.Auth.OAuth2;
|
||||
using Google.Apis.Auth.OAuth2.Flows;
|
||||
using Google.Apis.Drive.v3;
|
||||
using Google.Apis.Drive.v3.Data;
|
||||
using Google.Apis.Services;
|
||||
using Google.Apis.Util.Store;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AsbCloudInfrastructure.Services
|
||||
{
|
||||
public class GoogleDriveService : IFileShareService, IDisposable
|
||||
{
|
||||
private readonly DriveService service;
|
||||
|
||||
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/0AX4XfWjAV_cwaXdtBHHIseToLqI36PeMycW7wMCdZBmumADKu0Ov2AoVg3F6NDRCApmW8A";
|
||||
const string refreshToken = "1//04rHpwsBJqXWyCgYIARAAGAQSNwF-L9IrzEaVHpC_Ajim5ZF0_hlSyOOW-QFARlRx4Xanx_H9TxyuRJSCIMmdVDf6S-qejlGli54";
|
||||
//const string accessToken = "ya29.a0ARrdaM8jLcdNDylpV70X08ix-pqU-1QfLbmQy4iRb7KWUgl3keukmd2mx5AxraEO0eveR3I_p1EacrgtlbbxtNWbXxl_YPf4mQTbhhNaoltp2aSn6VndUlyydLDKzw9J9r8ouFNnVZip9fivBmc-AX_rWXsj";
|
||||
|
||||
static readonly IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
|
||||
{
|
||||
ClientSecrets = new ClientSecrets
|
||||
{
|
||||
ClientId = clientId,
|
||||
ClientSecret = clientSecret
|
||||
},
|
||||
|
||||
Scopes = new[] { DriveService.Scope.Drive },
|
||||
DataStore = new FileDataStore(applicationName),//TODO: replace FileDataStore by thread safe static datastore service
|
||||
});
|
||||
|
||||
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
|
||||
});
|
||||
return newService;
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<string>> GetAllFileNames()
|
||||
{
|
||||
var fileList = service.Files.List();
|
||||
fileList.Fields = "files(id, webViewLink, size)";
|
||||
|
||||
var result = new List<Google.Apis.Drive.v3.Data.File>();
|
||||
string pageToken = null;
|
||||
do
|
||||
{
|
||||
fileList.PageToken = pageToken;
|
||||
var filesResult = await fileList.ExecuteAsync();
|
||||
var files = filesResult.Files;
|
||||
pageToken = filesResult.NextPageToken;
|
||||
result.AddRange(files);
|
||||
} while (pageToken != null);
|
||||
|
||||
return result.Select(r => r.Name);
|
||||
}
|
||||
|
||||
public async Task<string> GetFileWebLinkAsync(string idFile,
|
||||
CancellationToken token = default)
|
||||
{
|
||||
var fileList = service.Files.List();
|
||||
fileList.Fields = "files(id, webViewLink, size)";
|
||||
var filesResult = await fileList.ExecuteAsync(token)
|
||||
.ConfigureAwait(false);
|
||||
var file = filesResult.Files.FirstOrDefault(f => f.Id == idFile);
|
||||
return file?.WebViewLink ?? string.Empty;
|
||||
}
|
||||
|
||||
public async Task<string> CreateFolderAsync(string folderName,
|
||||
CancellationToken token = default)
|
||||
{
|
||||
var driveFolder = new Google.Apis.Drive.v3.Data.File();
|
||||
driveFolder.Name = folderName;
|
||||
driveFolder.MimeType = "application/vnd.google-apps.folder";
|
||||
//driveFolder.Parents = new string[] { parent };
|
||||
var command = service.Files.Create(driveFolder);
|
||||
var file = await command.ExecuteAsync(token)
|
||||
.ConfigureAwait(false);
|
||||
return file.Id;
|
||||
}
|
||||
|
||||
public async Task CreatePublicPermissionForFileAsync(string idFile,
|
||||
CancellationToken token = default)
|
||||
{
|
||||
var permission = new Permission() { Type = "anyone", Role = "reader" };
|
||||
var addPermissionRequest = service.Permissions.Create(permission, idFile);
|
||||
await addPermissionRequest.ExecuteAsync(token)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task<string> UploadFileAsync(Stream file, string fileName, string fileMime,
|
||||
string fileDescription, CancellationToken token = default)
|
||||
{
|
||||
var driveFile = new Google.Apis.Drive.v3.Data.File();
|
||||
driveFile.Name = fileName;
|
||||
driveFile.Description = fileDescription;
|
||||
driveFile.MimeType = fileMime;
|
||||
//driveFile.Parents = new [] {folder};
|
||||
|
||||
var request = service.Files.Create(driveFile, file, fileMime);
|
||||
request.Fields = "id";
|
||||
|
||||
var response = await request.UploadAsync(token)
|
||||
.ConfigureAwait(false);
|
||||
if (response.Status != Google.Apis.Upload.UploadStatus.Completed)
|
||||
throw response.Exception;
|
||||
|
||||
return request.ResponseBody.Id;
|
||||
}
|
||||
|
||||
public async Task DeleteFileAsync(string fileId,
|
||||
CancellationToken token = default)
|
||||
{
|
||||
var command = service.Files.Delete(fileId);
|
||||
await command.ExecuteAsync(token)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
#pragma warning disable CA1816 // Методы Dispose должны вызывать SuppressFinalize
|
||||
public void 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;
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user