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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using Tango.BL.Enumerations;
using Tango.Core;
using Tango.Core.DI;
using Tango.Core.ExtensionMethods;
using Tango.Core.Threading;
using Tango.FSE.Common.Authentication;
using Tango.FSE.Common.Connection;
using Tango.FSE.Common.Notifications;
using Tango.FSE.Common.RemoteDesktop;
using Tango.PMR;
using Tango.PMR.Integration;
using Tango.RemoteDesktop.Frames;
using Tango.RemoteDesktop.Network;
using Tango.Transport;
using Tango.WebRTC;
namespace Tango.FSE.UI.RemoteDesktop
{
/// <summary>
/// Represents the <see cref="IRemoteDesktopProvider"/> default implementation.
/// </summary>
/// <seealso cref="Tango.Core.ExtendedObject" />
/// <seealso cref="Tango.FSE.Common.RemoteDesktop.IRemoteDesktopProvider" />
public class DefaultRemoteDesktopProvider : ExtendedObject, IRemoteDesktopProvider
{
private class MouseMovement
{
public Point Location { get; set; }
public Size ViewSize { get; set; }
}
private IMachineProvider _machineProvider;
private RasterFrame _currentFrame;
private MemoryStream _currentStream;
private Size? _frameSize;
private IntervalMessageDispatcher<StartRemoteDesktopSessionResponse> _frameDispatcher;
private Thread _mouseMoveThread;
private ProducerConsumerQueue<MouseMovement> _mouseMovements;
private WebRtcClient _webRtcClient;
private List<IceCandidate> _iceCandidates;
private bool _answerReceived;
private JsonSerializerSettings _jsonSettings;
[TangoInject]
private INotificationProvider NotificationProvider { get; set; }
[TangoInject]
private IAuthenticationProvider AuthenticationProvider { get; set; }
#region Events
/// <summary>
/// Occurs when a new remote desktop screen frame is available.
/// </summary>
public event EventHandler<DesktopFrameReceivedEventArgs> FrameReceived;
#endregion
#region Properties
private bool _inSession;
/// <summary>
/// Gets a value indicating whether a remote desktop session is active.
/// </summary>
public bool InSession
{
get { return _inSession; }
set { _inSession = value; RaisePropertyChangedAuto(); RaisePropertyChanged(nameof(CanStartSession)); }
}
/// <summary>
/// Gets or sets a value indicating whether enable the WebRTC channel.
/// </summary>
public bool EnableWebRtc { get; set; }
private bool _isWebRtcActive;
/// <summary>
/// Gets a value indicating whether the WebRTC channel is available.
/// </summary>
public bool IsWebRtcActive
{
get { return _isWebRtcActive; }
set
{
if (_isWebRtcActive != value)
{
_isWebRtcActive = value;
RaisePropertyChangedAuto();
if (_isWebRtcActive)
{
LogManager.Log("WebRTC is now active.");
}
}
}
}
/// <summary>
/// Gets or sets the mouse move send interval.
/// </summary>
public TimeSpan MouseMoveInterval { get; set; }
/// <summary>
/// Gets a value indicating whether a remote desktop session can be started.
/// </summary>
public bool CanStartSession
{
get { return _machineProvider.IsConnected && !InSession; }
}
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="DefaultRemoteDesktopProvider"/> class.
/// </summary>
public DefaultRemoteDesktopProvider()
{
_jsonSettings = new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.All,
};
_iceCandidates = new List<IceCandidate>();
MouseMoveInterval = TimeSpan.FromMilliseconds(100);
EnableWebRtc = true;
}
/// <summary>
/// Initializes a new instance of the <see cref="DefaultRemoteDesktopProvider"/> class.
/// </summary>
/// <param name="machineProvider">The machine provider.</param>
public DefaultRemoteDesktopProvider(IMachineProvider machineProvider) : this()
{
_machineProvider = machineProvider;
_machineProvider.MachineConnected += (_, __) =>
{
InSession = false;
};
_machineProvider.MachineDisconnected += (_, __) =>
{
InSession = false;
OnFrameReceived(null);
};
_machineProvider.MachineOperator.RegisterRequestHandler<WebRtcIceCandidateRequest>(OnIceCandidateRequestReceived);
}
#endregion
#region Request Handlers
/// <summary>
/// Called when a new ice candidate received from the remote peer.
/// </summary>
/// <param name="transporter">The transporter.</param>
/// <param name="request">The request.</param>
/// <param name="token">The token.</param>
private async void OnIceCandidateRequestReceived(ITransporter transporter, WebRtcIceCandidateRequest request, string token)
{
try
{
LogManager.Log("Ice candidate request received from the remote peer. Adding ice candidate and sending confirmation response...");
_webRtcClient.AddIceCandidate(request.IceCandidate);
}
catch (Exception ex)
{
LogManager.Log(ex, $"Error adding ice candidate:\n{request.IceCandidate.ToJsonString()}");
}
try
{
await _machineProvider.MachineOperator.SendGenericResponse(new WebRtcIceCandidateResponse() { }, token);
}
catch (Exception ex)
{
LogManager.Log(ex, "Error sending Ice candidate confirmation response.");
}
}
#endregion
#region Start/Stop Session
/// <summary>
/// Starts a remote desktop session.
/// </summary>
/// <returns></returns>
/// <exception cref="System.InvalidOperationException">Unable to start a remote desktop session at the moment.</exception>
public async Task StartSession()
{
AuthenticationProvider.ThrowIfNoPermission(Permissions.FSE_RemoteDesktopView);
TaskCompletionSource<bool> completionSource = new TaskCompletionSource<bool>();
if (!CanStartSession)
{
throw new InvalidOperationException("Unable to start a remote desktop session at the moment.");
}
if (!InSession)
{
LogManager.Log("Starting remote desktop session...");
_currentFrame = null;
_currentStream = null;
_iceCandidates.Clear();
_answerReceived = false;
InSession = true;
var taskItem = NotificationProvider.PushTaskItem("Starting remote desktop session...");
await Task.Delay(2000);
if (_frameDispatcher != null)
{
_frameDispatcher.Dispose();
}
_frameDispatcher = new IntervalMessageDispatcher<StartRemoteDesktopSessionResponse>(OnRemoteDesktopResponse);
_frameDispatcher.DriftCompensationInterval = (int)TimeSpan.FromSeconds(10).TotalMilliseconds;
_frameDispatcher.Start();
bool taskCompleted = false;
LogManager.Log("Sending continuous remote desktop session request...");
_machineProvider.MachineOperator.SendGenericContinuousRequest<StartRemoteDesktopSessionRequest, StartRemoteDesktopSessionResponse>(new StartRemoteDesktopSessionRequest() { }, new TransportContinuousRequestConfig()
{
Timeout = TimeSpan.FromSeconds(10)
}).Subscribe((response) =>
{
if (!taskCompleted)
{
LogManager.Log("Remote desktop session started.");
taskCompleted = true;
taskItem.Dispose();
completionSource.SetResult(true);
if (EnableWebRtc)
{
LogManager.Log("WebRTC for remote desktop is enabled. Starting WebRTC channel...");
StartWebRTC();
}
}
_frameDispatcher.Push(response);
}, (ex) =>
{
if (!taskCompleted)
{
taskCompleted = true;
taskItem.Dispose();
completionSource.SetException(ex);
}
else if (InSession)
{
OnFailed(ex);
}
InSession = false;
}, () =>
{
InSession = false;
OnFrameReceived(null);
});
await completionSource.Task;
}
else
{
await Task.FromResult(true);
}
}
/// <summary>
/// Ends the current remote desktop session.
/// </summary>
/// <returns></returns>
public async Task EndSession()
{
if (InSession)
{
using (NotificationProvider.PushTaskItem("Stopping remote desktop session..."))
{
LogManager.Log("Stopping remote desktop session...");
await Task.Delay(2000);
try
{
LogManager.Log("Sending stop remote desktop session request...");
await _machineProvider.MachineOperator.SendGenericRequest<StopRemoteDesktopSessionRequest, StopRemoteDesktopSessionResponse>(new StopRemoteDesktopSessionRequest(), new TransportRequestConfig()
{
ShouldLog = true
});
LogManager.Log("Remote desktop session stopped.");
}
catch (Exception ex)
{
LogManager.Log(ex, "Error stopping the remote desktop session.");
}
DisposeWebRtc();
InSession = false;
}
}
}
#endregion
#region Virtual Methods
/// <summary>
/// Raises the <see cref="FrameReceived"/> event.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="origin">The origin.</param>
protected virtual void OnFrameReceived(BitmapSource source, DesktopFrameReceivedEventArgs.FrameOrigin origin = DesktopFrameReceivedEventArgs.FrameOrigin.WebSockets)
{
IsWebRtcActive = origin == DesktopFrameReceivedEventArgs.FrameOrigin.WebRTC;
if (InSession)
{
FrameReceived?.Invoke(this, new DesktopFrameReceivedEventArgs()
{
Source = source,
Origin = origin
});
}
}
#endregion
#region SignalR Response Received
/// <summary>
/// Called when by the interval message dispatcher for processing a frame received by the standard SignalR channel.
/// </summary>
/// <param name="response">The response.</param>
private void OnRemoteDesktopResponse(StartRemoteDesktopSessionResponse response)
{
if (!InSession) return; //To stop frame delivery immediately.
if (response.Packet == null)
{
LogManager.Log($"Remote desktop session frame rate is now: {response.FrameRate} per second.");
_frameDispatcher.Interval = 1000 / response.FrameRate;
return; //This is the first message with empty bitmap and only the frame rate.
}
try
{
if (!response.Packet.IsPartial)
{
_currentFrame?.Dispose();
_currentStream?.Dispose();
_currentStream = new MemoryStream(response.Packet.Bitmap);
_currentFrame = new RasterFrame(new System.Drawing.Bitmap(_currentStream));
_frameSize = new Size(_currentFrame.Width, _currentFrame.Height);
}
else
{
using (MemoryStream ms = new MemoryStream(response.Packet.Bitmap))
{
var diffFrame = new RasterFrame(new System.Drawing.Bitmap(ms), response.Packet.PartialRegion.Left, response.Packet.PartialRegion.Top);
diffFrame.Apply(_currentFrame);
diffFrame.Dispose();
}
}
OnFrameReceived(_currentFrame.ToBitmapSource());
}
catch (Exception ex)
{
LogManager.Log(ex, "Error occurred while trying to process a remote desktop response.");
}
}
#endregion
#region Mouse/Keyboard
/// <summary>
/// Sends a mouse down command to the remote PPC.
/// </summary>
/// <param name="button">The button.</param>
/// <param name="location">The location.</param>
/// <param name="viewSize">Size of the view.</param>
public async void MouseDown(MouseButton button, Point location, Size viewSize)
{
if (!InSession || _frameSize == null) return;
if (!AuthenticationProvider.CurrentUser.HasPermission(Permissions.FSE_RemoteDesktopControl)) return;
try
{
var request = new MouseStateRequest()
{
Button = button,
EventType = MouseEventType.Down,
Location = TranslateLocation(location, viewSize)
};
if (IsWebRtcActive)
{
SendWebRtcObject(request);
}
else
{
await _machineProvider.MachineOperator.SendGenericRequest<MouseStateRequest, MouseStateResponse>(request);
}
}
catch (Exception ex)
{
LogManager.Log(ex, "Error sending remote desktop mouse down command.");
}
}
/// <summary>
/// Sends a mouse up command to the remote PPC.
/// </summary>
/// <param name="button">The button.</param>
/// <param name="location">The location.</param>
/// <param name="viewSize">Size of the view.</param>
public async void MouseUp(MouseButton button, Point location, Size viewSize)
{
if (!InSession || _frameSize == null) return;
if (!AuthenticationProvider.CurrentUser.HasPermission(Permissions.FSE_RemoteDesktopControl)) return;
try
{
var request = new MouseStateRequest()
{
Button = button,
EventType = MouseEventType.Up,
Location = TranslateLocation(location, viewSize)
};
if (IsWebRtcActive)
{
SendWebRtcObject(request);
}
else
{
await _machineProvider.MachineOperator.SendGenericRequest<MouseStateRequest, MouseStateResponse>(request);
}
}
catch (Exception ex)
{
LogManager.Log(ex, "Error sending remote desktop mouse up command.");
}
}
/// <summary>
/// Sends a mouse move command to the remote PPC.
/// </summary>
/// <param name="location">The location.</param>
/// <param name="viewSize">Size of the view.</param>
public void MouseMove(Point location, Size viewSize)
{
if (!InSession || _frameSize == null) return;
if (!AuthenticationProvider.CurrentUser.HasPermission(Permissions.FSE_RemoteDesktopControl)) return;
if (_mouseMoveThread == null)
{
_mouseMovements = new ProducerConsumerQueue<MouseMovement>();
_mouseMoveThread = new Thread(async () =>
{
while (InSession)
{
MouseMovement movement = _mouseMovements.BlockDequeue();
while (_mouseMovements.Count > 0)
{
movement = _mouseMovements.BlockDequeue();
}
try
{
var request = new MouseStateRequest()
{
Button = MouseButton.Left,
EventType = MouseEventType.Move,
Location = TranslateLocation(movement.Location, movement.ViewSize)
};
if (IsWebRtcActive)
{
SendWebRtcObject(request);
}
else
{
await _machineProvider.MachineOperator.SendGenericRequest<MouseStateRequest, MouseStateResponse>(request);
}
}
catch (Exception ex)
{
LogManager.Log(ex, "Error sending remote desktop mouse move command.");
}
Thread.Sleep(MouseMoveInterval);
}
_mouseMoveThread = null;
});
_mouseMoveThread.IsBackground = true;
_mouseMoveThread.Start();
}
_mouseMovements.BlockEnqueue(new MouseMovement()
{
Location = location,
ViewSize = viewSize,
});
}
/// <summary>
/// Sends a mouse double click command to the remote PPC.
/// </summary>
/// <param name="button">The button.</param>
/// <param name="location">The location.</param>
/// <param name="viewSize">Size of the view.</param>
public async void MouseDoubleClick(MouseButton button, Point location, Size viewSize)
{
if (!InSession || _frameSize == null) return;
if (!AuthenticationProvider.CurrentUser.HasPermission(Permissions.FSE_RemoteDesktopControl)) return;
try
{
var request = new MouseStateRequest()
{
Button = button,
EventType = MouseEventType.DoubleClick,
Location = TranslateLocation(location, viewSize)
};
if (IsWebRtcActive)
{
SendWebRtcObject(request);
}
else
{
await _machineProvider.MachineOperator.SendGenericRequest<MouseStateRequest, MouseStateResponse>(request);
}
}
catch (Exception ex)
{
LogManager.Log(ex, "Error sending remote desktop mouse double click command.");
}
}
/// <summary>
/// Translates the location.
/// </summary>
/// <param name="location">The location.</param>
/// <param name="viewSize">Size of the view.</param>
/// <returns></returns>
private Point TranslateLocation(Point location, Size viewSize)
{
return new Point(
(location.X / viewSize.Width) * _frameSize.Value.Width,
(location.Y / viewSize.Height) * _frameSize.Value.Height);
}
/// <summary>
/// Sends a key down command to the remote PPC.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="ctrlDown">if set to <c>true</c> [control down].</param>
/// <param name="shitDown">if set to <c>true</c> [shit down].</param>
/// <param name="altDown">if set to <c>true</c> [alt down].</param>
public async void KeyboardDown(Key key, bool ctrlDown, bool shitDown, bool altDown)
{
if (!InSession || _frameSize == null) return;
if (!AuthenticationProvider.CurrentUser.HasPermission(Permissions.FSE_RemoteDesktopControl)) return;
if (key == Key.LeftCtrl || key == Key.LeftShift || key == Key.LeftAlt) return;
try
{
var request = new KeyboardStateRequest()
{
EventType = KeyboardEventType.Down,
Key = key,
IsCtrlDown = ctrlDown,
IsShiftDown = shitDown,
IsAltDown = altDown,
};
if (IsWebRtcActive)
{
SendWebRtcObject(request);
}
else
{
await _machineProvider.MachineOperator.SendGenericRequest<KeyboardStateRequest, KeyboardStateResponse>(request);
}
}
catch (Exception ex)
{
LogManager.Log(ex, "Error sending remote desktop key down command.");
}
}
/// <summary>
/// Sends a key up command to the remote PPC.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="ctrlDown">if set to <c>true</c> [control down].</param>
/// <param name="shitDown">if set to <c>true</c> [shit down].</param>
/// <param name="altDown">if set to <c>true</c> [alt down].</param>
public async void KeyboardUp(Key key, bool ctrlDown, bool shitDown, bool altDown)
{
if (!InSession || _frameSize == null) return;
if (!AuthenticationProvider.CurrentUser.HasPermission(Permissions.FSE_RemoteDesktopControl)) return;
if (key == Key.LeftCtrl || key == Key.LeftShift || key == Key.LeftAlt) return;
try
{
var request = new KeyboardStateRequest()
{
EventType = KeyboardEventType.Up,
Key = key,
IsCtrlDown = ctrlDown,
IsShiftDown = shitDown,
IsAltDown = altDown,
};
if (IsWebRtcActive)
{
SendWebRtcObject(request);
}
else
{
await _machineProvider.MachineOperator.SendGenericRequest<KeyboardStateRequest, KeyboardStateResponse>(request);
}
}
catch (Exception ex)
{
LogManager.Log(ex, "Error sending remote desktop key up command.");
}
}
#endregion
#region Commands
/// <summary>
/// Sends the specified predefined remote desktop command.
/// </summary>
/// <param name="command">The command.</param>
public async void SendCommand(RemoteDesktopCommand command)
{
AuthenticationProvider.ThrowIfNoPermission(Permissions.FSE_RemoteDesktopControl);
try
{
await _machineProvider.MachineOperator.SendGenericRequest<RemoteDesktopCommandRequest, RemoteDesktopCommandResponse>(new RemoteDesktopCommandRequest());
}
catch (Exception ex)
{
LogManager.Log(ex, $"Error sending remote desktop command '{command}'.");
}
}
#endregion
#region WebRTC
/// <summary>
/// Starts the WebRTC channel.
/// </summary>
private async void StartWebRTC()
{
try
{
LogManager.Log("Starting Remote desktop WebRTC channel...");
_webRtcClient = new WebRtcClient();
_webRtcClient.NewIceCandidate += _webRtcClient_NewIceCandidate;
_webRtcClient.FrameReceived += _webRtcClient_FrameReceived;
_webRtcClient.Disconnected += _webRtcClient_Disconnected;
LogManager.Log("Initializing WebRTC client...");
await _webRtcClient.Init();
LogManager.Log("Creating WebRTC offer...");
var offer = await _webRtcClient.CreateOffer();
LogManager.Log("Sending WebRTC offer...");
var response = await _machineProvider.MachineOperator.SendGenericRequest<WebRtcOfferRequest, WebRtcOfferResponse>(new WebRtcOfferRequest() { Offer = offer }, new TransportRequestConfig()
{
Timeout = TimeSpan.FromSeconds(30)
});
LogManager.Log("Remote desktop WebRTC offer sent and responded with an answer. Setting WebRTC answer...");
_webRtcClient.SetAnswer(response.Answer);
_answerReceived = true;
foreach (var ice in _iceCandidates.ToList())
{
LogManager.Log("Sending any existing ice candidate...");
try
{
await _machineProvider.MachineOperator.SendGenericRequest<WebRtcIceCandidateRequest, WebRtcIceCandidateResponse>(new WebRtcIceCandidateRequest() { IceCandidate = ice }, new TransportRequestConfig()
{
Timeout = TimeSpan.FromSeconds(30),
});
}
catch (Exception ex)
{
LogManager.Log(ex, "Error sending existing ice candidate. Ignoring...");
}
}
}
catch (Exception ex)
{
LogManager.Log(ex, "Error starting WebRTC.");
}
}
/// <summary>
/// Disposes the WebRTC channel.
/// </summary>
private void DisposeWebRtc()
{
if (_webRtcClient != null)
{
LogManager.Log("Disposing remote desktop WebRTC channel...");
_webRtcClient.NewIceCandidate -= _webRtcClient_NewIceCandidate;
_webRtcClient.FrameReceived -= _webRtcClient_FrameReceived;
_webRtcClient.Disconnected -= _webRtcClient_Disconnected;
if (_webRtcClient != null)
{
try
{
_webRtcClient.Dispose();
_webRtcClient = null;
LogManager.Log("Remote desktop WebRTC channel disposed properly.");
}
catch (Exception ex)
{
LogManager.Log(ex, "Error occurred while disposing remote desktop WebRTC channel.");
}
}
}
}
/// <summary>
/// Handles the <see cref="WebRtcClient.Disconnected"/> event.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
private void _webRtcClient_Disconnected(object sender, EventArgs e)
{
LogManager.Log("The remote desktop WebRTC channel has disconnected.");
IsWebRtcActive = false;
}
/// <summary>
/// Handles the <see cref="WebRtcClient.NewIceCandidate"/> event.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="NewIceCandidateEventArgs"/> instance containing the event data.</param>
private async void _webRtcClient_NewIceCandidate(object sender, NewIceCandidateEventArgs e)
{
try
{
if (_answerReceived)
{
LogManager.Log("New remote desktop WebRTC candidate available. Sending ice to remote peer...");
await _machineProvider.MachineOperator.SendGenericRequest<WebRtcIceCandidateRequest, WebRtcIceCandidateResponse>(new WebRtcIceCandidateRequest() { IceCandidate = e.IceCandidate }, new TransportRequestConfig()
{
Timeout = TimeSpan.FromSeconds(30),
ShouldLog = true
});
}
else
{
LogManager.Log("New remote desktop WebRTC candidate available. Will be sent after an answer is received...");
_iceCandidates.Add(e.IceCandidate);
}
}
catch (Exception ex)
{
LogManager.Log(ex, "Error sending remote desktop ice candidate to remote peer.");
}
}
/// <summary>
/// Handles the <see cref="WebRTC.VideoFrameReceivedEventArgs"/> event.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="VideoFrameReceivedEventArgs"/> instance containing the event data.</param>
private void _webRtcClient_FrameReceived(object sender, VideoFrameReceivedEventArgs e)
{
try
{
RasterFrame frame = new RasterFrame(e.Bitmap);
OnFrameReceived(frame.ToBitmapSource(), DesktopFrameReceivedEventArgs.FrameOrigin.WebRTC);
frame.Dispose();
}
catch (Exception ex)
{
LogManager.Log(ex, "Error while processing a remote desktop frame received by WebRTC channel.");
}
}
/// <summary>
/// Sends a serialized JSON object via the WebRTC data channel.
/// </summary>
/// <param name="obj">The object.</param>
private void SendWebRtcObject(object obj)
{
_webRtcClient.SendText(JsonConvert.SerializeObject(obj, _jsonSettings));
}
#endregion
#region OnFailed
/// <summary>
/// Called when the current remote desktop channel has completely failed.
/// </summary>
/// <param name="exception">The exception.</param>
private void OnFailed(Exception exception)
{
LogManager.Log(exception, "The current remote desktop session has failed.");
InSession = false;
OnFrameReceived(null);
DisposeWebRtc();
if (!(exception is TransporterDisconnectedException))
{
NotificationProvider.PushSnackbarItem(MessageType.Error, "Remote desktop session terminated unexpectedly.", true, null, TimeSpan.FromSeconds(5));
}
}
#endregion
}
}
|