This repository has been archived on 2020-12-20. You can view files and clone it, but cannot push or open issues or pull requests.
aurora-sharp-desktop/Aurora/Design/Views/Party/PartyViewModel.cs

577 lines
18 KiB
C#
Raw Normal View History

using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;
using System.Linq;
2019-06-26 01:17:52 +00:00
using Xamarin.Forms;
using Aurora.Proto.Party;
using Aurora.Models.Media;
using Aurora.Services.Client;
2019-12-07 18:47:45 +00:00
using Aurora.Design.Views.Party.NewPartyDialog;
2020-02-01 01:41:45 +00:00
using Aurora.Services.Settings;
using Aurora.Services.Server;
using Aurora.Services.EventManager;
using Grpc.Core;
2019-07-05 18:17:09 +00:00
namespace Aurora.Design.Views.Party
{
//TODO refactor
2019-06-26 01:17:52 +00:00
enum PartyState
{
SelectingHost,
InParty,
Hosting,
2019-06-26 01:17:52 +00:00
Connecting,
}
2020-02-02 22:28:34 +00:00
delegate void EventHandler(BaseEvent e);
public class PartyViewModel : BaseViewModel
{
2019-06-26 01:17:52 +00:00
private PartyState _state;
2019-12-10 20:10:27 +00:00
private string _hostname = "";
private ObservableCollection<Member> _members;
2019-11-04 04:17:34 +00:00
private ObservableCollection<BaseMedia> _queue;
2019-11-09 01:25:36 +00:00
private BaseMedia _selectedMedia;
2020-02-01 01:41:45 +00:00
private ISettingsService _settingsService;
private IClientService _clientService;
private IServerService _serverService;
private IEventManager _eventManager;
private CancellationTokenSource _eventCancellationTokenSource;
private Dictionary<BaseEvent.DerivedEventOneofCase, EventHandler> _eventHandlers;
private int _selectedTabIndex;
public PartyViewModel(
ISettingsService settingsService,
IServerService serverService,
2020-02-02 22:28:34 +00:00
IEventManager eventManager,
IClientService clientService)
{
_members = new ObservableCollection<Member>();
2019-11-04 04:17:34 +00:00
_queue = new ObservableCollection<BaseMedia>();
2019-06-26 01:17:52 +00:00
2020-02-01 01:41:45 +00:00
this._settingsService = settingsService;
this._serverService = serverService;
this._eventManager = eventManager;
2020-02-02 22:28:34 +00:00
this._clientService = clientService;
2020-02-01 01:41:45 +00:00
SetState(PartyState.SelectingHost);
2019-11-02 19:47:41 +00:00
2020-01-18 23:07:31 +00:00
PlayCommand = new Command(OnDoubleClickCommandExecute, CanDoubleClickCommandExecute);
2020-01-18 23:07:31 +00:00
LeavePartyCommand = new Command(OnLeavePartyCommandExecute, CanLeavePartyCommandExecute);
//Setup event handlers
_eventHandlers = new Dictionary<BaseEvent.DerivedEventOneofCase, EventHandler>()
{
{BaseEvent.DerivedEventOneofCase.MediaPausedEvent, this.OnRemoteMediaPaused},
{BaseEvent.DerivedEventOneofCase.MediaResumedEvent, this.OnRemoteMediaResumed},
{BaseEvent.DerivedEventOneofCase.NewMediaPlayingEvent, this.OnNewRemoteMediaPlaying},
{BaseEvent.DerivedEventOneofCase.MemberCreatedEvent, this.OnPartyMemberJoined},
{BaseEvent.DerivedEventOneofCase.MemberDeletedEvent, this.OnPartyMemberLeft}
};
}
2019-06-26 01:17:52 +00:00
#region Properties
public int SelectedTabIndex
{
get { return _selectedTabIndex; }
set { SetProperty(ref _selectedTabIndex, value); }
}
/// <summary>
/// Publc property for the members list
/// </summary>
/// <value></value>
public ObservableCollection<Member> Members
{
2019-07-05 21:37:10 +00:00
get
{
return _members;
}
set
{
SetProperty(ref _members, value);
}
}
2019-06-26 01:17:52 +00:00
/// <summary>
/// Public property for queue item source
/// </summary>
/// <value></value>
2019-11-04 04:17:34 +00:00
public ObservableCollection<BaseMedia> Queue
{
get
{
return _queue;
}
set
{
if (value != _queue)
{
SetProperty(ref _queue, value);
}
}
}
/// <summary>
/// Public property for the currently selected song.
/// </summary>
/// <value></value>
2019-11-04 04:17:34 +00:00
public BaseMedia SelectedSong
{
2019-11-09 01:25:36 +00:00
get { return _selectedMedia; }
set { SetProperty(ref _selectedMedia, value); }
2019-11-04 04:17:34 +00:00
}
/// <summary>
/// Public property for playing media
/// </summary>
/// <value></value>
2019-11-04 04:17:34 +00:00
public Command PlayCommand { get; private set; }
public Command LeavePartyCommand { get; private set; }
2019-06-26 01:17:52 +00:00
#endregion Properties
2019-11-02 19:47:41 +00:00
#region Events
/// <summary>
/// Called by framework when view becomes active
/// </summary>
/// <returns></returns>
public override async Task OnActive()
{
OnPropertyChanged("SelectedTabIndex");
if (this._state == PartyState.Hosting ||
this._state == PartyState.InParty)
{
await this.GetEvents().ConfigureAwait(false);
}
2019-12-07 18:47:45 +00:00
else
{
2019-12-10 20:10:27 +00:00
//Open host selection modal
2019-12-19 03:32:08 +00:00
NewPartyDialogViewModel vm = new NewPartyDialogViewModel();
ConnectionDetails details = new ConnectionDetails();
vm.Finish = () =>
2019-12-10 20:10:27 +00:00
{
2019-12-19 03:32:08 +00:00
this.HideModal();
details = vm.ReturnObject as ConnectionDetails;
2019-12-10 20:10:27 +00:00
_hostname = details.HostName;
switch (details.ConnectionType)
{
case ConnectionType.Host:
{
2020-01-18 23:07:31 +00:00
OnHostCommandExecute();
2019-12-10 20:10:27 +00:00
break;
}
case ConnectionType.Join:
{
2020-01-18 23:07:31 +00:00
OnJoinCommandExecute();
2019-12-10 20:10:27 +00:00
break;
}
}
2019-12-19 03:32:08 +00:00
};
this.ShowModal(typeof(NewPartyDialog.NewPartyDialog), vm);
2019-12-07 18:47:45 +00:00
}
}
/// <summary>
/// Called by framework when view becomes inactive
/// </summary>
/// <returns></returns>
public override Task OnInactive()
{
2020-12-19 22:10:40 +00:00
if(this._eventCancellationTokenSource != null){
this._eventCancellationTokenSource.Cancel();
}
return Task.FromResult<object>(null);
}
/// <summary>
/// Remote media paused event
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
public void OnRemoteMediaPaused(BaseEvent e)
{
StopPlaying();
}
/// <summary>
/// Remote playing new media event
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
public void OnNewRemoteMediaPlaying(BaseEvent e)
{
PlayFromBeginning(GetMediaFromQueue(e.NewMediaPlayingEvent.Media.Name));
}
2019-11-02 19:47:41 +00:00
/// <summary>
/// Remote resumed playing event
2019-11-02 19:47:41 +00:00
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
public void OnRemoteMediaResumed(BaseEvent e)
2019-11-02 19:47:41 +00:00
{
PlayResume();
}
/// <summary>
/// Member joined party event
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
public void OnPartyMemberJoined(BaseEvent e)
{
Members.Add(e.MemberCreatedEvent.Member);
}
2019-11-02 19:47:41 +00:00
/// <summary>
/// Member left party event
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
public void OnPartyMemberLeft(BaseEvent e)
{
var found = Members.Where(x => x.Name == e.MemberDeletedEvent.MemberName);
foreach (Member member in found)
{
_members.Remove(member);
2019-11-02 19:47:41 +00:00
}
}
#endregion Events
2019-06-26 01:17:52 +00:00
#region Commands
2020-01-18 23:07:31 +00:00
private async void OnJoinCommandExecute()
2019-06-26 01:17:52 +00:00
{
SetState(PartyState.Connecting);
_clientService.Start(_hostname, this._settingsService.DefaultPort.ToString());
await JoinParty(false);
2019-07-06 19:52:28 +00:00
2019-11-10 20:33:06 +00:00
//TODO add cancellation token
try
{
SetState(PartyState.InParty);
await GetEvents().ConfigureAwait(true);
2019-11-10 20:33:06 +00:00
}
catch (Exception ex)
{
Console.WriteLine("Exception occurred while receiviing events: ", ex.Message);
2019-11-10 20:33:06 +00:00
}
2019-06-26 01:17:52 +00:00
}
2020-01-18 23:07:31 +00:00
private bool CanJoinCommandExecute()
2019-06-26 01:17:52 +00:00
{
return true;
}
2020-01-18 23:07:31 +00:00
private async void OnHostCommandExecute()
2019-06-26 01:17:52 +00:00
{
//Change state
SetState(PartyState.Connecting);
_serverService.Start("test", "asdf");
string localHost = ServerService.GetLocalIPAddress();
_clientService.Start(localHost, this._settingsService.DefaultPort.ToString());
await JoinParty(true);
2019-11-02 19:47:41 +00:00
//TODO add cancellation token
try
{
2019-11-09 01:25:36 +00:00
SetState(PartyState.Hosting);
2020-02-02 22:28:34 +00:00
await GetEvents().ConfigureAwait(false);
}
catch (Exception ex)
{
Console.WriteLine("Exception occurred while receiviing events: ", ex.Message);
}
2019-06-26 01:17:52 +00:00
}
2020-01-18 23:07:31 +00:00
private bool CanHostCommandExecute()
2019-06-26 01:17:52 +00:00
{
return true;
}
2020-01-18 23:07:31 +00:00
private async void OnLeavePartyCommandExecute()
{
await _clientService.RemotePartyServiceClient.DeleteMemberAsync(new DeleteMemberRequest()
{
Name = _settingsService.ClientName
});
}
2020-01-18 23:07:31 +00:00
private bool CanLeavePartyCommandExecute()
{
return (this._state == PartyState.InParty || this._state == PartyState.Hosting) ? true : false;
}
2020-01-18 23:07:31 +00:00
public override void OnPlayButtonCommandExecute()
{
if (base.IsPlaying())
{
//Fire play stopped event
AudioMetadata meta = _selectedMedia.Metadata as AudioMetadata;
MediaPausedEvent mediaPaused = new MediaPausedEvent();
_eventManager.FireEvent(new BaseEvent()
{
MediaPausedEvent = mediaPaused
});
}
else
{
//Fire play resume event
AudioMetadata meta = _selectedMedia.Metadata as AudioMetadata;
MediaResumedEvent mediaResumed = new MediaResumedEvent();
_eventManager.FireEvent(new BaseEvent()
{
MediaResumedEvent = mediaResumed
});
}
}
2020-01-18 23:07:31 +00:00
public override bool CanPlayButtonCommandExecute()
{
return this._state == PartyState.Hosting;
}
2020-01-18 23:07:31 +00:00
public override bool CanNextButtonCommandExecute()
{
return this._state == PartyState.Hosting;
}
2020-01-18 23:07:31 +00:00
public override bool CanPreviousButtonCommandExecute()
{
return this._state == PartyState.Hosting;
}
/// <summary>
/// On double click execute, fire media playing event
/// </summary>
2020-01-18 23:07:31 +00:00
public void OnDoubleClickCommandExecute()
{
//Fire Playing event
AudioMetadata meta = _selectedMedia.Metadata as AudioMetadata;
NewMediaPlayingEvent mediaPlaying = new NewMediaPlayingEvent()
{
Media = new Media()
{
//TODO need full resource name
Name = _selectedMedia.Id,
Title = meta.Title,
Artist = meta.Artist,
Album = meta.Album,
}
};
_eventManager.FireEvent(new BaseEvent()
{
NewMediaPlayingEvent = mediaPlaying
});
}
2020-01-18 23:07:31 +00:00
public bool CanDoubleClickCommandExecute()
{
return this._state == PartyState.Hosting;
}
2019-06-26 01:17:52 +00:00
#endregion Commands
#region Private Methods
/// <summary>
/// Join the remote party.
/// </summary>
/// <returns></returns>
private async Task JoinParty(bool asHost)
{
2019-11-02 19:47:41 +00:00
try
2019-07-06 19:52:28 +00:00
{
Member resp = await _clientService.RemotePartyServiceClient.CreateMemberAsync(new CreateMemberRequest
2019-11-02 19:47:41 +00:00
{
Member = new Member()
{
UserName = this._settingsService.Username,
}
2019-11-02 19:47:41 +00:00
});
this._settingsService.ClientName = resp.Name;
await RefreshMembers();
2019-11-02 19:47:41 +00:00
//Subscribe to events
await SubscribeToEvents();
2019-12-10 20:10:27 +00:00
Queue.Clear();
ListMediaResponse mediaResponse = await _clientService.RemotePartyServiceClient.ListMediaAsync(new ListMediaRequest()
{
PageSize = 50,
Parent = "TODO"
});
2019-12-10 20:10:27 +00:00
2019-11-04 04:17:34 +00:00
//Convert received data to remote audio models
foreach (Media data in mediaResponse.Media)
{
2019-11-04 04:17:34 +00:00
//Assign received metadata (since this can't be aquired from a file)
AudioMetadata meta = new AudioMetadata();
meta.Title = data.Title;
meta.Album = data.Album;
meta.Artist = data.Artist;
meta.Duration = data.Duration;
RemoteAudio remote = new RemoteAudio(data.Name,
asHost,
2019-11-04 04:17:34 +00:00
meta,
_clientService.RemotePartyServiceClient);
2019-11-04 04:17:34 +00:00
Queue.Add(remote);
2019-12-19 01:23:59 +00:00
OnPropertyChanged("Queue");
}
}
catch (Exception ex)
{
Console.WriteLine("Error subscribing to events: " + ex.Message);
}
}
private async Task LeaveParty()
{
//Stop receiving events
// _client.StopEvents();
//Unsubscribe
await UnsubscribeFromEvents();
//Leave party
DeleteMemberRequest req = new DeleteMemberRequest()
{
Name = _settingsService.ClientName
};
await _clientService.RemotePartyServiceClient.DeleteMemberAsync(req);
}
private async Task SubscribeToEvents()
{
CreateEventSubscriptionListRequest req = new CreateEventSubscriptionListRequest();
req.Parent = this._settingsService.ClientName;
req.EventSubscriptions.Add(new EventSubscription() { Type = EventType.MemberCreated });
req.EventSubscriptions.Add(new EventSubscription() { Type = EventType.MemberDeleted });
req.EventSubscriptions.Add(new EventSubscription() { Type = EventType.MediaPlaying });
req.EventSubscriptions.Add(new EventSubscription() { Type = EventType.MediaStopped });
Console.WriteLine(string.Format("CLIENT {0} - SubscribeToEvents called from client with id", this._settingsService.ClientName));
await _clientService.RemotePartyServiceClient.CreateEventSubscriptionListAsync(req);
}
private async Task UnsubscribeFromEvents()
{
DeleteAllEventSubscriptionsRequest unsubscribeReq = new DeleteAllEventSubscriptionsRequest();
await _clientService.RemotePartyServiceClient.DeleteAllEventSubscriptionsAsync(unsubscribeReq);
}
/// <summary>
/// Refresh members list.
/// </summary>
private async Task RefreshMembers()
{
Members.Clear();
ListMembersResponse response = await _clientService.RemotePartyServiceClient.ListMembersAsync(
new ListMembersRequest()
{
Parent = "TODO",
PageSize = 50,
});
//Add members
foreach (Member member in response.Members)
{
Members.Add(member);
}
}
private void SetState(PartyState state)
{
_state = state;
OnPropertyChanged("IsSelectingHost");
OnPropertyChanged("IsNotSelectingHost");
}
private BaseMedia GetMediaFromQueue(string Id)
{
if (_queue.Any((BaseMedia media) => media.Id == Id))
{
BaseMedia media = _queue.First((BaseMedia med) => med.Id == Id);
return media;
}
else
2019-11-09 01:25:36 +00:00
{
return null;
2019-11-09 01:25:36 +00:00
}
}
private void PlayFromBeginning(BaseMedia args)
{
base.ChangePlayerState(args, Main.PlayAction.Play);
}
private void PlayResume()
{
base.ChangePlayerState(null, Main.PlayAction.Resume);
}
private void StopPlaying()
2019-11-04 04:17:34 +00:00
{
base.ChangePlayerState(null, Main.PlayAction.Pause);
}
/// <summary>
/// Asynchronous function for processing events off of the event stream.
/// </summary>
/// <returns></returns>
public async Task GetEvents()
{
_eventCancellationTokenSource = new CancellationTokenSource();
string clientName = this._settingsService.ClientName;
Console.WriteLine(string.Format("CLIENT {0} - GetEvents called from client with id", clientName));
using (AsyncServerStreamingCall<BaseEvent> eventStream = _clientService.RemotePartyServiceClient
.GetEvents(new GetEventsRequest { Parent = this._settingsService.ClientName }))
{
try
{
while (!_eventCancellationTokenSource.Token.IsCancellationRequested &&
await eventStream.ResponseStream.MoveNext(_eventCancellationTokenSource.Token))
{
try
{
BaseEvent e = new BaseEvent(eventStream.ResponseStream.Current);
_eventHandlers.TryGetValue(e.DerivedEventCase, out EventHandler handler);
if (handler != null && handler != null)
{
handler.Invoke(e);
}
}
catch (Exception ex)
{
Console.WriteLine("Exception while parsing event ---" + ex.Message);
}
}
}
catch (Exception ex)
{
Console.WriteLine(string.Format("EXCEPTION while parsing events --- " + ex.Message));
}
}
}
#endregion Private Methods
}
}