Added crud operation on files at Google drive

This commit is contained in:
KharchenkoVladimir 2021-10-26 17:22:32 +05:00
parent b553f74a50
commit 896f2dd9b8
6 changed files with 151 additions and 5 deletions

View File

@ -12,7 +12,7 @@ namespace AsbCloudDevOperations
{
var controllerTester = new ControllerLoadTester();
controllerTester.TestControllerRoute();
DbDemoDataFiller.AddDemoData();
//.GetAwaiter().GetResult();
Console.WriteLine("End of Test");

View File

@ -10,7 +10,7 @@ namespace AsbCloudInfrastructure.Services
{
public class TelemetryTracker : ITelemetryTracker
{
private Dictionary<string, DateTime> requests;
private readonly Dictionary<string, DateTime> requests;
public TelemetryTracker(CacheDb cacheDb)
{

View File

@ -8,6 +8,7 @@
<ItemGroup>
<PackageReference Include="BenchmarkDotNet" Version="0.13.1" />
<PackageReference Include="Google.Apis.Drive.v3" Version="1.55.0.2481" />
<PackageReference Include="Mapster" Version="7.2.0" />
<PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" />
<PackageReference Include="System.Net.Http" Version="4.3.4" />

View File

@ -21,7 +21,7 @@ namespace ConsoleApp1
.Options;
using var db = new AsbCloudDbContext(options);
var cacheDb = new CacheDb();
var telemetryService = new TelemetryService(db, new TelemetryTracker(), cacheDb);
var telemetryService = new TelemetryService(db, new TelemetryTracker(cacheDb), cacheDb);
var wellService = new WellService(db, telemetryService, cacheDb);
var wellOptsStat = new WellOperationsStatService(db, cacheDb, wellService);
var tvd = wellOptsStat.GetTvdAsync(1, default).Result;

View File

@ -0,0 +1,130 @@
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.Util.Store;
using Google.Apis.Drive.v3.Data;
using System.IO;
using System.Collections.Generic;
// usage example at the very bottom
namespace ConsoleApp1
{
public class GoogleDriveFilesService
{
private static DriveService GetService()
{ // ключи для почты 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"; // Use the name of the project in Google Cloud
var username = "asbautodrilling@gmail.com"; // Use your email
var apiCodeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = "1020584579240-f7amqg35qg7j94ta1ntgitajq27cgh49.apps.googleusercontent.com",
ClientSecret = "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"
},
Scopes = new[] {DriveService.Scope.Drive},
DataStore = new FileDataStore(applicationName)
});
var credential = new UserCredential(apiCodeFlow, username, tokenResponse);
var service = new DriveService(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = applicationName
});
return service;
}
//public string CreateFolder(string parent, string folderName)
public string CreateFolder(string folderName) // Это fileName. У гугла почему-то все называется folder: и папка, и файл.
{ // С parent почему-то не дружит, выкидывает Exception.
var service = GetService();
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 = command.Execute();
return file.Id;
}
//public string UploadFile(Stream file, string fileName, string fileMime, string folder, string fileDescription)
public string UploadFile(Stream file, string fileName, string fileMime, string fileDescription)
{
DriveService service = GetService();
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 = request.Upload();
if (response.Status != Google.Apis.Upload.UploadStatus.Completed)
throw response.Exception;
return request.ResponseBody.Id;
}
//public IEnumerable<Google.Apis.Drive.v3.Data.File> GetFiles(string folder)
public IEnumerable<Google.Apis.Drive.v3.Data.File> GetFiles()
{
var service = GetService();
var fileList = service.Files.List();
// Это выражение ниже тоже чот не работает, выкидывает Exception. Без них выгружаются все файлы и
// папки водин список.
//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;
do
{
fileList.PageToken = pageToken;
var filesResult = fileList.Execute();
var files = filesResult.Files;
pageToken = filesResult.NextPageToken;
result.AddRange(files);
} while (pageToken != null);
return result;
}
public void DeleteFile(string fileId)
{
var service = GetService();
var command = service.Files.Delete(fileId);
var result = command.Execute();
}
}
}
// usage example:
// var service = new GoogleDriveFilesService();
//
// var files = service.GetFiles();
// Console.WriteLine(files);
//
// var newFolderId = service.CreateFolder("testText.txt");
// Console.WriteLine(newFolderId);
//
// var path = "/home/vladimir/TestUploadFile.txt";
// var fileInfo = new FileInfo(path);
// var fileStream = File.Open(path, FileMode.Open);
// var uploadedFileId = service.UploadFile(fileStream, fileInfo.Name, "", "uploaded");
// Console.WriteLine(uploadedFileId);

View File

@ -1,4 +1,7 @@
namespace ConsoleApp1
using System;
using System.IO;
namespace ConsoleApp1
{
//var options = new DbContextOptionsBuilder<AsbCloudDbContext>()
// .UseNpgsql("Host=localhost;Database=postgres;Username=postgres;Password=q;Persist Security Info=True")
@ -9,7 +12,19 @@
{
static void Main(/*string[] args*/)
{
DebugWellOperationImportService.Main();
var service = new GoogleDriveFilesService();
var files = service.GetFiles();
Console.WriteLine(files);
var newFolderId = service.CreateFolder("testText.txt");
Console.WriteLine(newFolderId);
var path = "/home/vladimir/TestUploadFile.txt";
var fileInfo = new FileInfo(path);
var fileStream = File.Open(path, FileMode.Open);
var uploadedFileId = service.UploadFile(fileStream, fileInfo.Name, "", "uploaded");
Console.WriteLine(uploadedFileId);
}
}
}