aurora/Aurora/Design/Views/Party/PartyViewModel.cs

515 lines
15 KiB
C#
Raw Normal View History

using System;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using System.Linq;
2019-06-26 01:17:52 +00:00
using Xamarin.Forms;
using Aurora.Services;
using Aurora.Proto.General;
using Aurora.Proto.Party;
using Aurora.Proto.Events;
2019-11-02 19:47:41 +00:00
using Aurora.Services.ClientService;
using Aurora.Services.ClientService.Events;
2019-11-04 04:17:34 +00:00
using Aurora.Services.PlayerService;
using Aurora.Services.EventManager;
using Aurora.Models.Media;
2019-12-07 18:47:45 +00:00
using Aurora.Design.Views.Party.NewPartyDialog;
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,
}
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 = "";
2019-07-05 21:37:10 +00:00
private ObservableCollection<PartyMember> _members;
2019-11-04 04:17:34 +00:00
private ObservableCollection<BaseMedia> _queue;
2019-11-09 01:25:36 +00:00
private BaseMedia _selectedMedia;
private ClientService _client;
private int _selectedTabIndex;
public PartyViewModel()
{
_members = new ObservableCollection<PartyMember>();
2019-11-04 04:17:34 +00:00
_queue = new ObservableCollection<BaseMedia>();
2019-06-26 01:17:52 +00:00
SetState(PartyState.SelectingHost);
2019-11-02 19:47:41 +00:00
PlayCommand = new Command(OnDoubleClickExecute, CanDoubleClickExecute);
LeavePartyCommand = new Command(OnLeavePartyExecute, CanLeaveParty);
_client = ClientService.Instance;
_client.OnMediaPaused += this.OnMediaPaused;
_client.OnMediaResumed += this.OnMediaResumed;
_client.OnNewMediaPlaying += this.OnNewMediaPlaying;
_client.OnPartyMemberJoined += this.OnPartyMemberJoined;
_client.OnPartyMemberLeft += this.OnPartyMemberLeft;
}
~PartyViewModel()
{
2019-11-02 19:47:41 +00:00
//Task.Run(ServerService.Instance.Stop);
}
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>
2019-07-05 21:37:10 +00:00
public ObservableCollection<PartyMember> 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 _client.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:
{
OnHostExecute();
break;
}
case ConnectionType.Join:
{
OnJoinExecute();
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()
{
_client.StopEvents();
return Task.FromResult<object>(null);
}
/// <summary>
/// Remote media paused event
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
public void OnMediaPaused(object sender, MediaPausedEventArgs args)
{
StopPlaying();
}
/// <summary>
/// Remote playing new media event
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
public void OnNewMediaPlaying(object sender, NewMediaPlayingEventArgs args)
{
PlayFromBeginning(GetMediaFromQueue(args.Event.Media.Id));
}
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 OnMediaResumed(object sender, MediaResumedEventArgs args)
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(object sender, PartyMemberJoinedEventArgs args)
{
PartyMember member = new PartyMember
2019-11-02 19:47:41 +00:00
{
UserName = args.Event.Member.UserName,
Id = args.Event.Member.Id,
IpAddress = args.Event.Member.IpAddress,
Port = args.Event.Member.Port
};
2019-11-02 19:47:41 +00:00
Members.Add(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(object sender, PartyMemberLeftEventArgs args)
{
var found = Members.Where(x => x.Id == args.Event.Member.Id);
foreach (PartyMember 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
2019-11-02 19:47:41 +00:00
private async void OnJoinExecute()
2019-06-26 01:17:52 +00:00
{
SetState(PartyState.Connecting);
2019-12-10 20:10:27 +00:00
_client.Start(_hostname, SettingsService.Instance.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 _client.GetEvents().ConfigureAwait(true);
}
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
}
private bool CanJoinExecute()
{
return true;
}
2019-11-02 19:47:41 +00:00
private async void OnHostExecute()
2019-06-26 01:17:52 +00:00
{
//Change state
SetState(PartyState.Connecting);
ServerService.Instance.Start();
string localHost = ServerService.GetLocalIPAddress();
_client.IsHost = true;
_client.Start(localHost, SettingsService.Instance.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);
await _client.GetEvents().ConfigureAwait(true);
}
catch (Exception ex)
{
Console.WriteLine("Exception occurred while receiviing events: ", ex.Message);
}
2019-06-26 01:17:52 +00:00
}
private bool CanHostExecute()
{
return true;
}
private async void OnLeavePartyExecute()
{
await _client.RemotePartyClient.LeavePartyAsync(new LeavePartyRequest());
}
private bool CanLeaveParty()
{
return (this._state == PartyState.InParty || this._state == PartyState.Hosting) ? true : false;
}
public override void OnPlayButtonExecute()
{
if (base.IsPlaying())
{
//Fire play stopped event
AudioMetadata meta = _selectedMedia.Metadata as AudioMetadata;
MediaPausedEvent mediaPaused = new MediaPausedEvent();
EventManager.Instance.FireEvent(new BaseEvent()
{
MediaPausedEvent = mediaPaused
});
}
else
{
//Fire play resume event
AudioMetadata meta = _selectedMedia.Metadata as AudioMetadata;
MediaResumedEvent mediaResumed = new MediaResumedEvent();
EventManager.Instance.FireEvent(new BaseEvent()
{
MediaResumedEvent = mediaResumed
});
}
}
public override bool CanPlayButtonExecute()
{
return this._state == PartyState.Hosting;
}
public override bool CanNextButtonExecute()
{
return this._state == PartyState.Hosting;
}
public override bool CanPreviousButtonExecute()
{
return this._state == PartyState.Hosting;
}
/// <summary>
/// On double click execute, fire media playing event
/// </summary>
public void OnDoubleClickExecute()
{
//Fire Playing event
AudioMetadata meta = _selectedMedia.Metadata as AudioMetadata;
NewMediaPlayingEvent mediaPlaying = new NewMediaPlayingEvent()
{
Media = new RemoteMediaData()
{
Id = _selectedMedia.Id,
Title = meta.Title,
Artist = meta.Artist,
Album = meta.Album,
}
};
EventManager.Instance.FireEvent(new BaseEvent()
{
NewMediaPlayingEvent = mediaPlaying
});
}
public bool CanDoubleClickExecute()
{
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
{
JoinPartyResponse resp = await _client.RemotePartyClient.JoinPartyAsync(new JoinPartyRequest
2019-11-02 19:47:41 +00:00
{
UserName = SettingsService.Instance.Username,
});
2019-11-02 19:47:41 +00:00
SettingsService.Instance.ClientId = resp.ClientId;
2019-11-02 19:47:41 +00:00
RefreshMembers();
//Subscribe to events
await SubscribeToEvents();
2019-12-10 20:10:27 +00:00
Queue.Clear();
QueueResponse queueResponse = _client.RemotePartyClient.GetQueue(new Empty());
2019-12-10 20:10:27 +00:00
2019-11-04 04:17:34 +00:00
//Convert received data to remote audio models
foreach (RemoteMediaData data in queueResponse.MediaList)
{
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.Id,
asHost,
2019-11-04 04:17:34 +00:00
meta,
_client.RemotePlaybackClient,
_client.RemoteSyncClient);
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
LeavePartyRequest leaveReq = new LeavePartyRequest();
await _client.RemotePartyClient.LeavePartyAsync(leaveReq);
}
private async Task SubscribeToEvents()
{
SubscribeRequest req = new SubscribeRequest();
req.EventTypes.Add(EventType.PartyMemberJoined);
req.EventTypes.Add(EventType.PartyMemberLeft);
req.EventTypes.Add(EventType.MediaPlaying);
req.EventTypes.Add(EventType.MediaStopped);
if (!string.IsNullOrWhiteSpace(SettingsService.Instance.ClientId))
{
req.ClientId = SettingsService.Instance.ClientId;
}
Console.WriteLine(string.Format("CLIENT {0} - SubscribeToEvents called from client with id", SettingsService.Instance.ClientId));
await _client.RemoteEventClient.SubscribeToEventsAsync(req);
}
private async Task UnsubscribeFromEvents()
{
UnsubscribeAllRequest unsubscribeReq = new UnsubscribeAllRequest();
await _client.RemoteEventClient.UnsubscribeFromAllAsync(unsubscribeReq);
}
/// <summary>
/// Refresh members list.
/// </summary>
private void RefreshMembers()
{
Members.Clear();
MembersResponse response = _client.RemotePartyClient.GetPartyMembers(new Empty());
//Add members
foreach (PartyMember 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);
}
#endregion Private Methods
}
}