// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.md in the project root for license information.
using System;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR.Infrastructure;
using Microsoft.AspNet.SignalR.Messaging;
namespace Microsoft.AspNet.SignalR
{
///
/// The default implementation.
///
public class GroupManager : IConnectionGroupManager
{
private readonly IConnection _connection;
private readonly string _groupPrefix;
///
/// Initializes a new instance of the class.
///
/// The this group resides on.
/// The prefix for this group. Either a name or type name.
public GroupManager(IConnection connection, string groupPrefix)
{
if (connection == null)
{
throw new ArgumentNullException("connection");
}
_connection = connection;
_groupPrefix = groupPrefix;
}
///
/// Sends a value to the specified group.
///
/// The name of the group.
/// The value to send.
/// The list of connection ids to exclude
/// A task that represents when send is complete.
public Task Send(string groupName, object value, params string[] excludeConnectionIds)
{
if (string.IsNullOrEmpty(groupName))
{
throw new ArgumentException((Resources.Error_ArgumentNullOrEmpty), "groupName");
}
var qualifiedName = CreateQualifiedName(groupName);
var message = new ConnectionMessage(qualifiedName,
value,
PrefixHelper.GetPrefixedConnectionIds(excludeConnectionIds));
return _connection.Send(message);
}
///
/// Adds a connection to the specified group.
///
/// The connection id to add to the group.
/// The name of the group
/// A task that represents the connection id being added to the group.
public Task Add(string connectionId, string groupName)
{
if (connectionId == null)
{
throw new ArgumentNullException("connectionId");
}
if (groupName == null)
{
throw new ArgumentNullException("groupName");
}
var command = new Command
{
CommandType = CommandType.AddToGroup,
Value = CreateQualifiedName(groupName),
WaitForAck = true
};
return _connection.Send(connectionId, command);
}
///
/// Removes a connection from the specified group.
///
/// The connection id to remove from the group.
/// The name of the group
/// A task that represents the connection id being removed from the group.
public Task Remove(string connectionId, string groupName)
{
if (connectionId == null)
{
throw new ArgumentNullException("connectionId");
}
if (groupName == null)
{
throw new ArgumentNullException("groupName");
}
var command = new Command
{
CommandType = CommandType.RemoveFromGroup,
Value = CreateQualifiedName(groupName),
WaitForAck = true
};
return _connection.Send(connectionId, command);
}
private string CreateQualifiedName(string groupName)
{
return _groupPrefix + "." + groupName;
}
}
}