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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
|
using Google.Protobuf;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Tango.Core;
using Tango.Core.Commands;
using Tango.Core.ExtensionMethods;
using Tango.Core.Threading;
using Tango.Logging;
using Tango.PMR.IO;
using Tango.Transport;
namespace Tango.Integration.Storage
{
public class StorageManager : ExtendedObject
{
private ITransporter _transporter;
#region Properties
private String _currentPath;
/// <summary>
/// Gets or sets the current path.
/// </summary>
public String CurrentPath
{
get { return _currentPath; }
set { _currentPath = value; RaisePropertyChangedAuto(); }
}
private StorageFolder _currentFolder;
/// <summary>
/// Gets or sets the current folder.
/// </summary>
public StorageFolder CurrentFolder
{
get { return _currentFolder; }
set { _currentFolder = value; RaisePropertyChangedAuto(); }
}
private StorageDrive _storageDrive;
/// <summary>
/// Gets or sets the storage drive.
/// </summary>
public StorageDrive StorageDrive
{
get { return _storageDrive; }
set { _storageDrive = value; RaisePropertyChangedAuto(); }
}
/// <summary>
/// Gets or sets a value indicating whether to disable the transporter keep alive mechanism while a file is being uploaded.
/// </summary>
public bool SuppressKeepAliveWhileFileUploads { get; set; }
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="StorageManager"/> class.
/// </summary>
/// <param name="transporter">The transporter.</param>
public StorageManager(ITransporter transporter)
{
_transporter = transporter;
}
#endregion
#region Private Methods
/// <summary>
/// Ensures the transporter is connected.
/// </summary>
/// <exception cref="System.InvalidOperationException">Error executing storage command. Transporter is not connected.</exception>
private void EnsureTransporter()
{
if (_transporter.State != TransportComponentState.Connected)
{
throw new InvalidOperationException("Error executing storage command. Transporter is not connected.");
}
}
#endregion
#region Public Methods
/// <summary>
/// Gets the storage drive information.
/// </summary>
/// <returns></returns>
public async Task<StorageDrive> GetStorageDrive()
{
EnsureTransporter();
GetStorageInfoResponse response = null;
GetStorageInfoRequest request = new GetStorageInfoRequest();
try
{
response = await _transporter.SendRequest<GetStorageInfoRequest, GetStorageInfoResponse>(request, new TransportRequestConfig() { ShouldLog = true });
}
catch (Exception ex)
{
throw ex;
}
StorageDrive = new StorageDrive()
{
Capacity = response.Capacity,
FreeSpace = response.FreeSpace,
Root = response.Root,
};
return StorageDrive;
}
/// <summary>
/// Gets the root folder of the current storage driver.
/// </summary>
/// <returns></returns>
public Task<StorageFolder> GetRootFolder()
{
return GetFolder(new StorageFolder()
{
Path = StorageDrive.Root,
});
}
/// <summary>
/// Gets the specified folder information.
/// </summary>
/// <param name="folder">The folder.</param>
/// <returns></returns>
public Task<StorageFolder> GetFolder(StorageFolder folder)
{
return GetFolder(folder.Path);
}
/// <summary>
/// Gets the specified path folder information.
/// </summary>
/// <param name="path">The path.</param>
/// <returns></returns>
public async Task<StorageFolder> GetFolder(String path)
{
EnsureTransporter();
GetFilesResponse response = null;
GetFilesRequest request = new GetFilesRequest();
request.Path = path;
try
{
response = await _transporter.SendRequest<GetFilesRequest, GetFilesResponse>(request, new TransportRequestConfig() { ShouldLog = true });
}
catch (Exception ex)
{
throw ex;
}
StorageFolder sf = new StorageFolder();
sf.Path = path;
List<StorageItem> items = new List<StorageItem>();
foreach (var item in response.Items)
{
if (!item.Attribute.HasFlag(FileAttribute.Directory))
{
items.Add(new StorageFile()
{
Length = item.Length,
Path = item.FullPath,
Attribute = item.Attribute,
});
}
else
{
items.Add(new StorageFolder()
{
Path = item.FullPath,
Attribute = item.Attribute,
});
}
}
sf.Items = new ReadOnlyCollection<StorageItem>(items);
_currentFolder = sf;
_currentPath = sf.Path;
RaisePropertyChanged(nameof(CurrentFolder));
RaisePropertyChanged(nameof(CurrentPath));
return sf;
}
/// <summary>
/// Uploads the specified file stream to the specified destination path.
/// Returns a file handler for keeping track on the upload progress.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="stream">The stream.</param>
/// <returns></returns>
public async Task<StorageFileHandler> UploadFile(String path, Stream stream)
{
FileUploadRequest request = new FileUploadRequest();
request.Path = path;
request.Length = stream.Length;
var fileUploadResponse = await _transporter.SendRequest<FileUploadRequest, FileUploadResponse>(request, new TransportRequestConfig() { ShouldLog = true });
String uploadId = fileUploadResponse.Message.UploadID;
long max_length = fileUploadResponse.Message.MaxChunkLength;
bool canceled = false;
StorageFileHandler handler = new StorageFileHandler(new StorageFile()
{
Path = path,
Length = (int)stream.Length,
}, () =>
{
canceled = true;
});
handler.Total = stream.Length;
ThreadFactory.StartNew(() =>
{
bool oldKeepAlive = _transporter.UseKeepAlive;
try
{
if (SuppressKeepAliveWhileFileUploads)
{
_transporter.UseKeepAlive = false;
}
while (stream.Position < stream.Length)
{
if (!canceled)
{
if (!handler.IsPaused)
{
byte[] buffer = new byte[Math.Min(max_length, stream.Length - stream.Position)];
stream.Read(buffer, 0, buffer.Length);
FileChunkUploadRequest chunk = new FileChunkUploadRequest();
chunk.UploadID = uploadId;
chunk.Path = path;
chunk.Buffer = ByteString.CopyFrom(buffer);
var chunk_response = _transporter.SendRequest<FileChunkUploadRequest, FileChunkUploadResponse>(chunk, new TransportRequestConfig() { Priority = QueuePriority.Low }).Result;
if (chunk_response.Message.IsCanceled)
{
canceled = true;
handler.RaiseFailed(new IOException("The storage device controller has canceled the current upload."));
return;
}
handler.Current = stream.Position;
}
else
{
Thread.Sleep(100);
}
}
else
{
handler.RaiseCanceled();
return;
}
}
if (!canceled)
{
handler.RaiseCompleted();
}
}
catch (Exception ex)
{
handler.RaiseFailed(ex);
}
finally
{
if (SuppressKeepAliveWhileFileUploads)
{
_transporter.UseKeepAlive = oldKeepAlive;
}
}
});
return handler;
}
/// <summary>
/// Uploads the specified file stream to the specified destination path.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="stream">The stream.</param>
/// <returns></returns>
public async Task UploadFileSync(String path, Stream stream)
{
TaskCompletionSource<object> source = new TaskCompletionSource<object>();
var handler = await UploadFile(path, stream);
handler.Completed += (_, __) =>
{
source.SetResult(true);
};
handler.Failed += (_, ex) =>
{
source.SetException(ex);
};
await source.Task;
}
/// <summary>
/// Downloads the specified storage file to the specified stream.
/// Returns a file handler for keeping track on the download progress.
/// </summary>
/// <param name="file">The file.</param>
/// <param name="stream">The stream.</param>
/// <returns></returns>
public async Task<StorageFileHandler> DownloadFile(StorageFile file, Stream stream)
{
FileDownloadRequest request = new FileDownloadRequest();
request.FileName = file.Path;
var fileDownloadResponse = await _transporter.SendRequest<FileDownloadRequest, FileDownloadResponse>(request, new TransportRequestConfig() { ShouldLog = true });
String download_id = fileDownloadResponse.Message.DownloadID;
long max_length = fileDownloadResponse.Message.MaxChunkLength;
bool canceled = false;
StorageFileHandler handler = new StorageFileHandler(file, () =>
{
canceled = true;
});
handler.Total = file.Length;
ThreadFactory.StartNew(() =>
{
try
{
while (stream.Length < file.Length)
{
if (!canceled)
{
if (!handler.IsPaused)
{
FileChunkDownloadRequest chunk = new FileChunkDownloadRequest();
chunk.DownloadID = download_id;
chunk.FileName = file.Path;
chunk.Position = stream.Length;
var chunk_response = _transporter.SendRequest<FileChunkDownloadRequest, FileChunkDownloadResponse>(chunk, new TransportRequestConfig() { Priority = QueuePriority.Low }).Result;
if (chunk_response.Message.IsCanceled)
{
canceled = true;
handler.RaiseFailed(new IOException("The storage device controller has canceled the current download."));
return;
}
byte[] buffer = chunk_response.Message.Buffer.ToByteArray();
stream.Write(buffer, 0, buffer.Length);
handler.Current = stream.Length;
}
else
{
Thread.Sleep(100);
}
}
else
{
handler.RaiseCanceled();
return;
}
}
if (!canceled)
{
handler.RaiseCompleted();
}
}
catch (Exception ex)
{
handler.RaiseFailed(ex);
}
});
return handler;
}
/// <summary>
/// Deletes the specified storage item.
/// </summary>
/// <param name="item">The item.</param>
/// <returns></returns>
public async Task DeleteItem(StorageItem item)
{
await _transporter.SendRequest<DeleteRequest, DeleteResponse>(new DeleteRequest()
{
Path = item.Path,
Attribute = item.Attribute,
}, new TransportRequestConfig() { ShouldLog = true });
}
/// <summary>
/// Creates a new folder on the specified destination path.
/// </summary>
/// <param name="path">The path.</param>
/// <returns></returns>
public async Task CreateFolder(String path)
{
await _transporter.SendRequest<CreateRequest, CreateResponse>(new CreateRequest()
{
Path = path,
Attribute = FileAttribute.Directory,
}, new TransportRequestConfig() { ShouldLog = true });
}
#endregion
}
}
|