forked from managedcode/Storage
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGoogleDriveClient.cs
More file actions
239 lines (202 loc) · 9.77 KB
/
GoogleDriveClient.cs
File metadata and controls
239 lines (202 loc) · 9.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
using Google.Apis.Drive.v3;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipelines;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using DriveFile = Google.Apis.Drive.v3.Data.File;
namespace ManagedCode.Storage.GoogleDrive.Clients;
public class GoogleDriveClient : IGoogleDriveClient
{
private const string FolderMimeType = "application/vnd.google-apps.folder";
private readonly DriveService _driveService;
public GoogleDriveClient(DriveService driveService)
{
_driveService = driveService ?? throw new ArgumentNullException(nameof(driveService));
}
public Task EnsureRootAsync(string rootFolderId, bool createIfNotExists, CancellationToken cancellationToken)
{
// Google Drive root exists by default when using "root". Additional folder tree is created on demand in UploadAsync.
return Task.CompletedTask;
}
public async Task<DriveFile> UploadAsync(string rootFolderId, string path, Stream content, string? contentType, bool supportsAllDrives, CancellationToken cancellationToken)
{
var (parentId, fileName) = await EnsureParentFolderAsync(rootFolderId, path, supportsAllDrives, cancellationToken);
var fileMetadata = new DriveFile
{
Name = fileName,
Parents = new List<string> { parentId }
};
var request = _driveService.Files.Create(fileMetadata, content, contentType ?? "application/octet-stream");
request.Fields = "id,name,parents,createdTime,modifiedTime,md5Checksum,size";
request.SupportsAllDrives = supportsAllDrives;
await request.UploadAsync(cancellationToken);
return request.ResponseBody ?? throw new InvalidOperationException("Google Drive upload returned no metadata.");
}
public async Task<Stream> DownloadAsync(string rootFolderId, string path, bool supportsAllDrives, CancellationToken cancellationToken)
{
var file = await FindFileByPathAsync(rootFolderId, path, supportsAllDrives, cancellationToken) ?? throw new FileNotFoundException(path);
var pipe = new Pipe();
var getRequest = _driveService.Files.Get(file.Id);
getRequest.SupportsAllDrives = supportsAllDrives;
_ = Task.Run(async () =>
{
try
{
await using var destination = pipe.Writer.AsStream(leaveOpen: true);
await getRequest.DownloadAsync(destination, cancellationToken);
pipe.Writer.Complete();
}
catch (Exception ex)
{
pipe.Writer.Complete(ex);
}
}, cancellationToken);
return pipe.Reader.AsStream();
}
public async Task<bool> DeleteAsync(string rootFolderId, string path, bool supportsAllDrives, CancellationToken cancellationToken)
{
var file = await FindFileByPathAsync(rootFolderId, path, supportsAllDrives, cancellationToken);
if (file == null)
{
return false;
}
await DeleteRecursiveAsync(file.Id, file.MimeType, supportsAllDrives, cancellationToken);
return true;
}
public async Task<bool> ExistsAsync(string rootFolderId, string path, bool supportsAllDrives, CancellationToken cancellationToken)
{
return await FindFileByPathAsync(rootFolderId, path, supportsAllDrives, cancellationToken) != null;
}
public Task<DriveFile?> GetMetadataAsync(string rootFolderId, string path, bool supportsAllDrives, CancellationToken cancellationToken)
{
return FindFileByPathAsync(rootFolderId, path, supportsAllDrives, cancellationToken);
}
public async IAsyncEnumerable<DriveFile> ListAsync(string rootFolderId, string? directory, bool supportsAllDrives, [EnumeratorCancellation] CancellationToken cancellationToken)
{
string parentId;
if (string.IsNullOrWhiteSpace(directory))
{
parentId = rootFolderId;
}
else
{
parentId = await EnsureFolderPathAsync(rootFolderId, directory!, false, supportsAllDrives, cancellationToken) ?? string.Empty;
if (string.IsNullOrWhiteSpace(parentId))
{
yield break;
}
}
var request = _driveService.Files.List();
request.SupportsAllDrives = supportsAllDrives;
request.IncludeItemsFromAllDrives = supportsAllDrives;
request.Q = $"'{parentId}' in parents and trashed=false";
request.Fields = "nextPageToken,files(id,name,parents,createdTime,modifiedTime,md5Checksum,size,mimeType)";
do
{
var response = await request.ExecuteAsync(cancellationToken);
foreach (var file in response.Files ?? Enumerable.Empty<DriveFile>())
{
cancellationToken.ThrowIfCancellationRequested();
yield return file;
}
request.PageToken = response.NextPageToken;
} while (!string.IsNullOrEmpty(request.PageToken));
}
private async Task<(string ParentId, string Name)> EnsureParentFolderAsync(string rootFolderId, string fullPath, bool supportsAllDrives, CancellationToken cancellationToken)
{
var normalizedPath = fullPath.Replace("\\", "/").Trim('/');
var segments = normalizedPath.Split('/', StringSplitOptions.RemoveEmptyEntries);
if (segments.Length == 0)
{
return (rootFolderId, Guid.NewGuid().ToString("N"));
}
var parentPath = string.Join('/', segments.Take(segments.Length - 1));
var parentId = await EnsureFolderPathAsync(rootFolderId, parentPath, true, supportsAllDrives, cancellationToken) ?? rootFolderId;
return (parentId, segments.Last());
}
private async Task<string?> EnsureFolderPathAsync(string rootFolderId, string path, bool createIfMissing, bool supportsAllDrives, CancellationToken cancellationToken)
{
var currentId = rootFolderId;
foreach (var segment in path.Split('/', StringSplitOptions.RemoveEmptyEntries))
{
var folder = await FindChildAsync(currentId, segment, supportsAllDrives, cancellationToken);
if (folder == null)
{
if (!createIfMissing)
{
return null;
}
var metadata = new DriveFile { Name = segment, MimeType = "application/vnd.google-apps.folder", Parents = new List<string> { currentId } };
var createRequest = _driveService.Files.Create(metadata);
createRequest.SupportsAllDrives = supportsAllDrives;
folder = await createRequest.ExecuteAsync(cancellationToken);
}
currentId = folder.Id;
}
return currentId;
}
private async Task<DriveFile?> FindChildAsync(string parentId, string name, bool supportsAllDrives, CancellationToken cancellationToken)
{
var request = _driveService.Files.List();
request.Q = $"'{parentId}' in parents and name='{name}' and trashed=false";
request.Fields = "files(id,name,parents,createdTime,modifiedTime,md5Checksum,size,mimeType)";
request.SupportsAllDrives = supportsAllDrives;
request.IncludeItemsFromAllDrives = supportsAllDrives;
var response = await request.ExecuteAsync(cancellationToken);
return response.Files?.FirstOrDefault();
}
private async Task DeleteRecursiveAsync(string fileId, string? mimeType, bool supportsAllDrives, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (string.Equals(mimeType, FolderMimeType, StringComparison.OrdinalIgnoreCase))
{
await DeleteFolderChildrenAsync(fileId, supportsAllDrives, cancellationToken);
}
var trashRequest = _driveService.Files.Update(new DriveFile { Trashed = true }, fileId);
trashRequest.SupportsAllDrives = supportsAllDrives;
await trashRequest.ExecuteAsync(cancellationToken);
}
private async Task DeleteFolderChildrenAsync(string folderId, bool supportsAllDrives, CancellationToken cancellationToken)
{
var request = _driveService.Files.List();
request.Q = $"'{folderId}' in parents and trashed=false";
request.Fields = "nextPageToken,files(id,mimeType)";
request.SupportsAllDrives = supportsAllDrives;
request.IncludeItemsFromAllDrives = supportsAllDrives;
do
{
var response = await request.ExecuteAsync(cancellationToken);
foreach (var entry in response.Files ?? Enumerable.Empty<DriveFile>())
{
cancellationToken.ThrowIfCancellationRequested();
if (string.IsNullOrWhiteSpace(entry.Id))
{
continue;
}
await DeleteRecursiveAsync(entry.Id, entry.MimeType, supportsAllDrives, cancellationToken);
}
request.PageToken = response.NextPageToken;
} while (!string.IsNullOrWhiteSpace(request.PageToken));
}
private async Task<DriveFile?> FindFileByPathAsync(string rootFolderId, string path, bool supportsAllDrives, CancellationToken cancellationToken)
{
var normalizedPath = path.Replace("\\", "/").Trim('/');
var segments = normalizedPath.Split('/', StringSplitOptions.RemoveEmptyEntries);
if (segments.Length == 0)
{
return null;
}
var parentPath = string.Join('/', segments.Take(segments.Length - 1));
var fileName = segments.Last();
var parentId = await EnsureFolderPathAsync(rootFolderId, parentPath, false, supportsAllDrives, cancellationToken);
if (parentId == null)
{
return null;
}
return await FindChildAsync(parentId, fileName, supportsAllDrives, cancellationToken);
}
}