using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using Microsoft.AspNet.SignalR; using Now.Web.Tickers; namespace Now.Web.Hubs { [Authorize] public class DistributionCenterReceivingHub : Hub { private static readonly ConcurrentDictionary _groupMembers = new ConcurrentDictionary(); private readonly DistributionCenterReceivingTicker _distributionCenterReceivingTicker; private readonly static ConnectionMapping _connections = new ConnectionMapping(); public DistributionCenterReceivingHub() : this(DistributionCenterReceivingTicker.Instance) { } public DistributionCenterReceivingHub(DistributionCenterReceivingTicker distributionCenterReceivingTicker) { _distributionCenterReceivingTicker = distributionCenterReceivingTicker; } internal static string[] GetGroups() { try { return _groupMembers.Values.GroupBy(g => g).Select(country => country.Key).ToArray(); } catch { return null; } } public void JoinLocation(string locationCode) { var country = string.IsNullOrEmpty(locationCode) ? "All" : locationCode; if (_groupMembers.ContainsKey(Context.ConnectionId)) { string prevCountry; if (_groupMembers.TryGetValue(Context.ConnectionId, out prevCountry) && country != prevCountry) { Groups.Remove(Context.ConnectionId, prevCountry); _groupMembers.TryRemove(Context.ConnectionId, out prevCountry); } } Groups.Add(Context.ConnectionId, country); _groupMembers.TryAdd(Context.ConnectionId, country); } public override Task OnConnected() { string name = Context.User.Identity.Name; var lc = Context.QueryString["locationCode"]; JoinLocation(lc); _connections.Add(name, Context.ConnectionId); return base.OnConnected(); } public override Task OnDisconnected(bool stopCalled) { if (Context.User != null) { string name = Context.User.Identity.Name; _connections.Remove(name, Context.ConnectionId); } string country; _groupMembers.TryRemove(Context.ConnectionId, out country); return base.OnDisconnected(stopCalled); } public override Task OnReconnected() { string name = Context.User.Identity.Name; if (!_connections.GetConnections(name).Contains(Context.ConnectionId)) { _connections.Add(name, Context.ConnectionId); } return base.OnReconnected(); } } }