aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.Integration/Storage/StorageManager.cs
blob: 5dd97546343175bc98a27d1bd788a1936b445c5f (plain)
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
generated by cgit v1.3.1 (git 2.54.0) at 2026-07-28 11:15:02 +0000
 


'#n325'>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
    }
}