aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/PPC/Tango.PPC.Common/FileSystem/DefaultFileSystemService.cs
blob: 8272ea34d39363969af76a364a4b97355e82712d (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
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
Diffstat (limited to 'Software/Visual_Studio/MachineStudio/Tango.MachineStudio.UI/Views/ReportIssueView.xaml.cs')
0 files changed, 0 insertions, 0 deletions
8 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
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tango.Core;
using Tango.Core.DI;
using Tango.Core.IO;
using Tango.FileSystem;
using Tango.FileSystem.Network;
using Tango.Integration.ExternalBridge;
using Tango.Integration.Operation;
using Tango.Logging;
using Tango.PPC.Common.ExternalBridge;
using Tango.PPC.Shared.Logs;
using Tango.Settings;
using Tango.Transport;
using Tango.Transport.Transporters;
using Tango.WebRTC;

namespace Tango.PPC.Common.FileSystem
{
    /// <summary>
    /// Represents the <see cref="IFileSystemService"/> default implementation.
    /// </summary>
    /// <seealso cref="Tango.Core.ExtendedObject" />
    /// <seealso cref="Tango.PPC.Common.FileSystem.IFileSystemService" />
    /// <seealso cref="Tango.Integration.ExternalBridge.IExternalBridgeRequestHandler" />
    [TangoCreateWhenRegistered]
    public class DefaultFileSystemService : ExtendedObject, IFileSystemService, IExternalBridgeRequestHandler
    {
        private FileSystemManager _manager;
        private Dictionary<String, FileSystemOperation> _operations;
        private Dictionary<ExternalBridgeReceiver, BasicTransporter> _webRtcClients;
        private PPCSettings _settings;

        public bool Enabled { get; set; } = true;
        public bool EnableWebRTC { get; set; } = true;

        public DefaultFileSystemService(IPPCExternalBridgeService externalBridge)
        {
            _webRtcClients = new Dictionary<ExternalBridgeReceiver, BasicTransporter>();
            _manager = new FileSystemManager();
            _operations = new Dictionary<string, FileSystemOperation>();
            externalBridge.RegisterRequestHandler(this);
            _settings = SettingsManager.Default.GetOrCreate<PPCSettings>();
        }

        [ExternalBridgeRequestHandlerMethod(typeof(InitWebRtcRequest), RequestHandlerLoggingMode.LogRequestNameAndContent)]
        public async Task OnInitWebRtcRequest(InitWebRtcRequest request, String token, ExternalBridgeReceiver receiver)
        {
            this.ThrowIfDisabled();

            try
            {
                if (!EnableWebRTC)
                {
                    await receiver.SendErrorResponse(new InvalidOperationException("The file system service WebRTC channel is disabled on this machine."), token);
                    return;
                }

                LogManager.Log("Initializing WebRTC channel for file system service.");

                if (_webRtcClients.ContainsKey(receiver))
                {
                    _webRtcClients[receiver].Dispose();
                }

                LogManager.Log("Initializing WebRTC transport adapter on 'Passive' mode.");
                var webRtcAdapter = new WebRtcTransportAdapter(receiver, WebRtcTransportAdapterMode.Passive, request.DataChannelName)
                {
                    EnableCompression = receiver.Adapter.EnableCompression
                };
                webRtcAdapter.Ready += (x, e) =>
                {
                    LogManager.Log("The file system service WebRTC channel is ready.");
                };

                BasicTransporter webRtcTransporter = new BasicTransporter(webRtcAdapter);
                webRtcTransporter.GenericProtocol = receiver.GenericProtocol;
                webRtcTransporter.ComponentName = "File System Passive WebRTC Transporter";
                webRtcTransporter.UseKeepAlive = false;
                webRtcTransporter.RegisterRequestHandler<ChunkDownloadRequest>(WebRtcChunkDownloadRequestReceived);
                webRtcTransporter.RegisterRequestHandler<ChunkUploadRequest>(WebRtcChunkUploadRequestReceived);
                await webRtcTransporter.Connect();

                LogManager.Log("Sending WebRTC initialization response...");

                await receiver.SendGenericResponse(new InitWebRtcResponse(), token);
                _webRtcClients[receiver] = webRtcTransporter;
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, "Error initializing WebRTC channel for file system service.");
                await receiver.SendErrorResponse(ex, token);
            }
        }

        private async void WebRtcChunkDownloadRequestReceived(ITransporter transporter, ChunkDownloadRequest request, string token)
        {
            await OnChunkDownloadRequest(request, token, transporter);
        }

        private async void WebRtcChunkUploadRequestReceived(ITransporter transporter, ChunkUploadRequest request, string token)
        {
            await OnChunkUploadRequest(request, token, transporter);
        }

        [ExternalBridgeRequestHandlerMethod(typeof(GetFileSystemItemRequest), RequestHandlerLoggingMode.LogRequestNameAndContent)]
        public async Task OnGetFileSystemItemRequest(GetFileSystemItemRequest request, String token, ExternalBridgeReceiver receiver)
        {
            this.ThrowIfDisabled();

            FileSystemItemDTO dto = _manager.GetFolder(request);
            await receiver.SendGenericResponse(new GetFileSystemItemResponse() { FileSystemItem = dto }, token);
        }

        [ExternalBridgeRequestHandlerMethod(typeof(FileUploadRequest), RequestHandlerLoggingMode.LogRequestNameAndContent)]
        public async Task OnFileUploadRequest(FileUploadRequest request, String token, ExternalBridgeReceiver receiver)
        {
            this.ThrowIfDisabled();

            var tempFile = TemporaryManager.CreateFile();
            using (var stream = new FileStream(tempFile, FileMode.Create)) { }

            FileSystemOperation operation = new FileSystemOperation(FileSystemOperationMode.Upload, tempFile) { UploadPostPath = request.Path };
            _operations.Add(operation.Id, operation);

            await receiver.SendGenericResponse(new FileUploadResponse() { OperationId = operation.Id }, token);
        }

        [ExternalBridgeRequestHandlerMethod(typeof(FolderUploadRequest), RequestHandlerLoggingMode.LogRequestNameAndContent)]
        public async Task OnFolderUploadRequest(FolderUploadRequest request, String token, ExternalBridgeReceiver receiver)
        {
            this.ThrowIfDisabled();

            var tempFile = TemporaryManager.CreateFile();
            using (var stream = new FileStream(tempFile, FileMode.Create)) { }

            FileSystemOperation operation = new FileSystemOperation(FileSystemOperationMode.Upload, tempFile) { UploadPostPath = request.Path, IsPathTempZip = true };
            _operations.Add(operation.Id, operation);

            await receiver.SendGenericResponse(new FolderUploadResponse() { OperationId = operation.Id }, token);
        }

        [ExternalBridgeRequestHandlerMethod(typeof(FileDownloadRequest), RequestHandlerLoggingMode.LogRequestNameAndContent)]
        public async Task OnFileDownloadRequest(FileDownloadRequest request, String token, ExternalBridgeReceiver receiver)
        {
            this.ThrowIfDisabled();

            if (!File.Exists(request.Path))
            {
                throw new FileNotFoundException("Could not find the specified file.");
            }

            FileSystemOperation operation = new FileSystemOperation(FileSystemOperationMode.Download, request.Path);

            _operations.Add(operation.Id, operation);

            await receiver.SendGenericResponse(new FileDownloadResponse()
            {
                OperationId = operation.Id,
                Length = new FileInfo(request.Path).Length
            }, token);
        }

        [ExternalBridgeRequestHandlerMethod(typeof(FolderDownloadRequest), RequestHandlerLoggingMode.LogRequestNameAndContent)]
        public async Task OnFolderDownloadRequest(FolderDownloadRequest request, String token, ExternalBridgeReceiver receiver)
        {
            this.ThrowIfDisabled();

            if (!Directory.Exists(request.Path))
            {
                throw new FileNotFoundException("Could not find the specified directory.");
            }

            var tempFile = TemporaryManager.CreateImaginaryFile();

            ZipFile.CreateFromDirectory(request.Path, tempFile);

            FileSystemOperation operation = new FileSystemOperation(FileSystemOperationMode.Download, tempFile);
            operation.IsPathTempZip = true;

            _operations.Add(operation.Id, operation);

            await receiver.SendGenericResponse(new FolderDownloadResponse()
            {
                OperationId = operation.Id,
                Length = new FileInfo(tempFile).Length
            }, token);
        }

        [ExternalBridgeRequestHandlerMethod(typeof(ChunkUploadRequest))]
        public async Task OnChunkUploadRequest(ChunkUploadRequest request, String token, ITransporter receiver)
        {
            this.ThrowIfDisabled();

            FileSystemOperation operation;
            _operations.TryGetValue(request.OperationId, out operation);

            if (operation == null)
            {
                throw new ArgumentException("Invalid operation id.");
            }

            using (var stream = new FileStream(operation.Path, FileMode.Append))
            {
                stream.Write(request.Data, 0, request.Data.Length);
            }

            if (request.IsCompleted)
            {
                if (!operation.IsPathTempZip)
                {
                    File.Copy(operation.Path, operation.UploadPostPath, true);
                    try
                    {
                        File.Delete(operation.Path);
                    }
                    catch { }
                }
                else
                {
                    using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(operation.Path))
                    {
                        zip.ExtractAll(operation.UploadPostPath, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
                    }

                    try
                    {
                        File.Delete(operation.Path);
                    }
                    catch { }
                }
            }

            await receiver.SendGenericResponse(new ChunkUploadResponse(), token, new TransportResponseConfig() { Priority = QueuePriority.Low });
        }

        [ExternalBridgeRequestHandlerMethod(typeof(ChunkDownloadRequest))]
        public async Task OnChunkDownloadRequest(ChunkDownloadRequest request, String token, ITransporter receiver)
        {
            this.ThrowIfDisabled();

            FileSystemOperation operation;
            _operations.TryGetValue(request.OperationId, out operation);

            if (operation == null)
            {
                throw new ArgumentException("Invalid operation id.");
            }

            FileStream stream = null;
            bool removeTempZipFile = false;

            try
            {
                stream = new FileStream(operation.Path, FileMode.Open);
                stream.Position = request.Position;
                byte[] data = new byte[Math.Min(request.MaxChunkSize, stream.Length - stream.Position)];

                if (stream.Position + data.Length == stream.Length)
                {
                    removeTempZipFile = true;
                }

                await stream.ReadAsync(data, 0, data.Length);
                stream.Dispose();
                stream = null;
                await receiver.SendGenericResponse(new ChunkDownloadResponse()
                {
                    Data = data
                }, token, new TransportResponseConfig() { Priority = QueuePriority.Low });
            }
            catch (Exception ex)
            {
                stream?.Dispose();
                throw ex;
            }
            finally
            {
                if (operation.IsPathTempZip && removeTempZipFile)
                {
                    try
                    {
                        if (File.Exists(operation.Path))
                        {
                            File.Delete(operation.Path);
                        }
                    }
                    catch { }
                }
            }
        }

        [ExternalBridgeRequestHandlerMethod(typeof(AbortOperationRequest), RequestHandlerLoggingMode.LogRequestNameAndContent)]
        public async Task OnAbortOperationRequest(AbortOperationRequest request, String token, ExternalBridgeReceiver receiver)
        {
            this.ThrowIfDisabled();

            FileSystemOperation operation;
            _operations.TryGetValue(request.OperationId, out operation);

            if (operation == null)
            {
                throw new ArgumentException("Invalid operation id.");
            }

            if (operation.Mode == FileSystemOperationMode.Upload)
            {
                if (File.Exists(operation.Path))
                {
                    File.Delete(operation.Path);
                }
            }
            else if (operation.IsPathTempZip)
            {
                if (File.Exists(operation.Path))
                {
                    File.Delete(operation.Path);
                }
            }

            await receiver.SendGenericResponse(new AbortOperationResponse(), token);
        }

        [ExternalBridgeRequestHandlerMethod(typeof(MoveRequest), RequestHandlerLoggingMode.LogRequestNameAndContent)]
        public async Task OnMoveRequest(MoveRequest request, String token, ExternalBridgeReceiver receiver)
        {
            this.ThrowIfDisabled();

            _manager.Move(request);
            await receiver.SendGenericResponse(new MoveResponse(), token);
        }

        [ExternalBridgeRequestHandlerMethod(typeof(CopyRequest), RequestHandlerLoggingMode.LogRequestNameAndContent)]
        public async Task OnCopyRequest(CopyRequest request, String token, ExternalBridgeReceiver receiver)
        {
            this.ThrowIfDisabled();

            _manager.Copy(request);
            await receiver.SendGenericResponse(new CopyResponse(), token);
        }

        [ExternalBridgeRequestHandlerMethod(typeof(DeleteRequest), RequestHandlerLoggingMode.LogRequestNameAndContent)]
        public async Task OnDeleteRequest(DeleteRequest request, String token, ExternalBridgeReceiver receiver)
        {
            this.ThrowIfDisabled();

            _manager.Delete(request.Path);
            await receiver.SendGenericResponse(new DeleteResponse(), token);
        }

        [ExternalBridgeRequestHandlerMethod(typeof(CreateFolderRequest), RequestHandlerLoggingMode.LogRequestNameAndContent)]
        public async Task OnCreateFolderRequest(CreateFolderRequest request, String token, ExternalBridgeReceiver receiver)
        {
            this.ThrowIfDisabled();

            var dto = _manager.CreateFolder(request.Path, request.FolderName);
            await receiver.SendGenericResponse(new CreateFolderResponse() { FolderItem = dto }, token);
        }

        [ExternalBridgeRequestHandlerMethod(typeof(PerformDiskSpaceOptimizationRequest), RequestHandlerLoggingMode.LogRequestNameAndContent)]
        public async Task OnPerformDiskSpaceOptimizationRequest(PerformDiskSpaceOptimizationRequest request, String token, ExternalBridgeReceiver receiver)
        {
            var deletedBytes = _manager.PerformDiskSpaceOptimization();
            await receiver.SendGenericResponse(new PerformDiskSpaceOptimizationResponse() { DeletedBytes = deletedBytes }, token);
        }

        [ExternalBridgeRequestHandlerMethod(typeof(GetLogFilesRequest), RequestHandlerLoggingMode.LogRequestNameAndContent)]
        public async Task OnGetLogFilesRequest(GetLogFilesRequest request, String token, ExternalBridgeReceiver receiver)
        {
            FolderItem folder = null;

            if (request.LogFileType == RemoteLogFileType.Application)
            {
                var fileLogger = LogManager.RegisteredLoggers.SingleOrDefault(x => x.GetType() == typeof(FileLogger)) as FileLogger;

                if (fileLogger == null)
                {
                    throw new InvalidOperationException("Could not locate the application file logger.");
                }

                folder = await _manager.GetFolder(fileLogger.Folder, false, "*.log") as FolderItem;
            }
            else
            {
                if (MachineOperator.EmbeddedLogsFolder == null)
                {
                    throw new InvalidOperationException("The firmware file logger folder could not be read.");
                }

                folder = await _manager.GetFolder(MachineOperator.EmbeddedLogsFolder, false, "*.log") as FolderItem;
            }

            GetLogFilesResponse response = new GetLogFilesResponse();

            foreach (var file in folder.Items.OfType<FileItem>().OrderByDescending(x => x.DateCreated).DistinctBy(x => x.Name))
            {
                response.LogFiles.Add(new RemoteLogFile()
                {
                    DateModified = file.DateModified,
                    DateCreated = file.DateCreated,
                    Name = file.Name,
                    Path = file.Path,
                    Length = new FileInfo(file.Path).Length
                });
            }

            await receiver.SendGenericResponse(response, token);
        }

        public void OnReceiverDisconnected(ExternalBridgeReceiver receiver)
        {
            if (_webRtcClients.ContainsKey(receiver))
            {
                try
                {
                    LogManager.Log("External bridge receiver disconnected. Disposing file system service WebRTC channel...");
                    var webRtcTransporter = _webRtcClients[receiver];
                    _webRtcClients.Remove(receiver);
                    webRtcTransporter.Dispose();
                }
                catch (Exception ex)
                {
                    LogManager.Log(ex, "Error disposing the WebRTC channel.");
                }
            }
        }
    }
}