Code refactoring for cleaner view model design

This commit is contained in:
watsonb8
2019-11-29 12:37:57 -05:00
parent 3398d145ac
commit 85ab39defd
15 changed files with 351 additions and 123 deletions

View File

@ -4,6 +4,8 @@ using System.Threading;
using Grpc.Core;
using Aurora.Models.Media;
using Aurora.Proto.Sync;
using Aurora.Proto.Events;
using Aurora.Proto.Party;
using LibVLCSharp.Shared;
namespace Aurora.Services.PlayerService
@ -110,14 +112,14 @@ namespace Aurora.Services.PlayerService
RemoteAudio media = _currentMedia as RemoteAudio;
if (!media.FromHost)
{
RemoteSyncService.RemoteSyncServiceClient _remoteSyncClient = media.RemoteSyncClient;
RemoteSyncService.RemoteSyncServiceClient remoteSyncClient = media.RemoteSyncClient;
//Sync playback in a separate task
//Task completes when host stops syncing (when a song is complete)
Task syncTask = new Task(async () =>
{
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
using (AsyncServerStreamingCall<Sync> syncStream = _remoteSyncClient
using (AsyncServerStreamingCall<Sync> syncStream = remoteSyncClient
.GetMediaSync(new Proto.General.Empty()))
{
try
@ -154,6 +156,7 @@ namespace Aurora.Services.PlayerService
});
syncTask.Start();
// Task syncTask = Task.Run(() => Sync(remoteSyncClient));
}
}
@ -163,6 +166,50 @@ namespace Aurora.Services.PlayerService
}
}
/// <summary>
/// Async method to synchronize music playback with host
/// </summary>
/// <param name="remoteSyncClient"></param>
/// <returns></returns>
private async Task Sync(RemoteSyncService.RemoteSyncServiceClient remoteSyncClient)
{
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
using (AsyncServerStreamingCall<Sync> syncStream = remoteSyncClient
.GetMediaSync(new Proto.General.Empty()))
{
try
{
while (await syncStream.ResponseStream.MoveNext(cancellationTokenSource.Token))
{
Sync sync = new Sync(syncStream.ResponseStream.Current);
if (sync != null)
{
//Adjust position based on sync
DateTime localTime = Utils.TimeUtils.GetNetworkTime();
//Get offset converted to milliseconds
float offset = ((localTime.Ticks - sync.ServerTime) * 100) / (1000 * 1000);
float length = CurrentMediaLength;
float newPosition = (sync.TrackTime + offset) / length;
//Adjust position if greater than 10 percent difference
float oldPosition = _mediaPlayer.Position;
if (newPosition - oldPosition > 0.001 ||
newPosition - oldPosition < -0.001)
{
_mediaPlayer.Position = newPosition;
Console.WriteLine("Audio synced");
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Exception caught while attempting to sync: " + ex.Message);
}
}
}
/// <summary>
/// Pause currently loaded media.
/// </summary>
@ -191,7 +238,6 @@ namespace Aurora.Services.PlayerService
{
PlaybackStateChanged.Invoke(this, new PlaybackStateChangedEventArgs(oldState, _state));
}
}
public void Enqueue(BaseMedia song)