2019-11-05 17:00:36 +01:00
|
|
|
|
using System;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
using Microsoft.AspNetCore.SignalR.Client;
|
2019-10-31 17:00:52 +01:00
|
|
|
|
using Microsoft.Extensions.DependencyInjection;
|
2019-11-06 17:02:06 +01:00
|
|
|
|
using Squirrowse.Core.Models;
|
2019-10-31 17:00:52 +01:00
|
|
|
|
|
2019-11-06 17:02:06 +01:00
|
|
|
|
namespace Squirrowse.Core.Services
|
2019-10-31 17:00:52 +01:00
|
|
|
|
{
|
|
|
|
|
public class ConnectionManager : IConnectionManager
|
|
|
|
|
{
|
|
|
|
|
private readonly HubConnection _connection;
|
2019-11-05 17:00:36 +01:00
|
|
|
|
private bool Connected;
|
2019-10-31 17:00:52 +01:00
|
|
|
|
|
|
|
|
|
public ConnectionManager(string url, int port)
|
|
|
|
|
{
|
|
|
|
|
_connection = new HubConnectionBuilder()
|
|
|
|
|
.WithUrl($"{url}:{port}/StreamHub")
|
|
|
|
|
.AddMessagePackProtocol()
|
|
|
|
|
.WithAutomaticReconnect()
|
|
|
|
|
.Build();
|
|
|
|
|
}
|
|
|
|
|
|
2019-11-05 17:00:36 +01:00
|
|
|
|
public async Task<HubConnection> GetConnection()
|
2019-11-04 09:29:37 +01:00
|
|
|
|
{
|
2019-11-06 13:47:00 +01:00
|
|
|
|
if (Connected) return _connection;
|
2019-11-06 11:49:39 +01:00
|
|
|
|
|
|
|
|
|
throw new Exception();
|
|
|
|
|
}
|
|
|
|
|
|
2019-11-06 17:02:06 +01:00
|
|
|
|
public async Task InitConnection(ConnectionType type)
|
2019-11-06 11:49:39 +01:00
|
|
|
|
{
|
2019-11-06 13:47:00 +01:00
|
|
|
|
if (_connection.State == HubConnectionState.Connected) return;
|
2019-11-05 17:00:36 +01:00
|
|
|
|
await _connection.StartAsync();
|
2019-11-06 17:02:06 +01:00
|
|
|
|
await RegisterOnHub(type);
|
2019-11-05 17:00:36 +01:00
|
|
|
|
Connected = true;
|
2019-11-06 11:49:39 +01:00
|
|
|
|
}
|
|
|
|
|
|
2019-11-06 17:02:06 +01:00
|
|
|
|
|
2019-11-06 11:49:39 +01:00
|
|
|
|
public async Task Disconnect()
|
|
|
|
|
{
|
|
|
|
|
if (_connection.State == HubConnectionState.Disconnected) throw new Exception();
|
|
|
|
|
await _connection.StopAsync();
|
|
|
|
|
Connected = false;
|
2019-11-04 09:29:37 +01:00
|
|
|
|
}
|
2019-11-05 17:00:36 +01:00
|
|
|
|
|
2019-11-06 17:02:06 +01:00
|
|
|
|
private async Task RegisterOnHub(ConnectionType type)
|
2019-11-05 17:00:36 +01:00
|
|
|
|
{
|
2019-11-06 17:02:06 +01:00
|
|
|
|
await _connection.SendAsync("AddUser", Environment.UserName,type);
|
2019-11-05 17:00:36 +01:00
|
|
|
|
}
|
2019-10-31 17:00:52 +01:00
|
|
|
|
}
|
|
|
|
|
}
|