public static void Handle(TwitchBot twitchBot, ChatMessage chatMessage, string alias) { if (chatMessage.GetMessage().IsMatch(PatternCreator.Create(alias, PrefixHelper.GetPrefix(chatMessage.Channel), @"\s.+"))) { twitchBot.SendCompilerResult(chatMessage); } }
// As a modder, you could also opt to make these overrides also sealed. Up to the modder public override void ModifyWeaponDamage(Item item, Player player, ref float add, ref float mult, ref float flat) { if (upgradeTier > 0) { mult *= PrefixHelper.getDamageMult(upgradeTier); } }
public void TestRemoveFromGroupCommandMessage() { var hubs = new List <string> { }; var parser = new SignalRMessageParser(hubs, _resolver); var groupName = GenerateRandomName(); var command = new Command { CommandType = CommandType.RemoveFromGroup, Value = groupName, WaitForAck = true }; var connectionId = GenerateRandomName(); var message = SignalRMessageUtility.CreateMessage(PrefixHelper.GetConnectionId(connectionId), command); var msgs = parser.GetMessages(message).ToList(); Assert.Single(msgs); var msg = msgs[0].Message as LeaveGroupMessage; Assert.NotNull(msg); Assert.Equal(connectionId, msg.ConnectionId); Assert.Equal(groupName, msg.GroupName); }
private IHub CreateHub(HttpRequest request, HubDescriptor descriptor, string connectionId, bool throwIfFailedToCreate = false) { try { var hub = _manager.ResolveHub(descriptor.Name); if (hub != null) { hub.Context = new HubCallerContext(request, connectionId); hub.Clients = new HubConnectionContext(_pipelineInvoker, Connection, descriptor.Name, connectionId); hub.Groups = new GroupManager(Connection, PrefixHelper.GetHubGroupName(descriptor.Name)); } return(hub); } catch (Exception ex) { Logger.LogInformation(String.Format("Error creating Hub {0}. {1}", descriptor.Name, ex.Message)); if (throwIfFailedToCreate) { throw; } return(null); } }
public async Task HandleCommand(SocketMessage messageParam) { // Don't process the command if it was a System Message var message = messageParam as SocketUserMessage; if (message == null) { return; } // Create a number to track where the prefix ends and the command begins int argPos = 0; // Determine if the message is a command, based on if it starts with '!' or a mention prefix if (!(message.HasStringPrefix(PrefixHelper.Get(message.Channel as SocketGuildChannel), ref argPos) || message.HasMentionPrefix(client.CurrentUser, ref argPos))) { return; } // Create a Command Context var context = new SocketCommandContext(client, message); // Execute the command. (result does not indicate a return value, // rather an object stating if the command executed successfully) var result = await commands.ExecuteAsync(context, argPos, services); if (!result.IsSuccess) { await MessageHelper.Warning(context, "Error", result.ErrorReason); } }
public static void Handle(TwitchBot twitchBot, ChatMessage chatMessage, string alias) { if (chatMessage.GetMessage().IsMatch(PatternCreator.Create(alias, PrefixHelper.GetPrefix(chatMessage.Channel), @"\s\w+"))) { twitchBot.SendLastMessage(chatMessage, chatMessage.GetLowerSplit()[1]); } }
public void TestHubGroupMessage(string input, string hub) { var hubs = new List <string> { "hub1", "hub.hub1", "hub.hub1.h.hub2" }; var parser = new SignalRMessageParser(hubs, _resolver); var groupName = GenerateRandomName(); var fullName = PrefixHelper.GetHubGroupName(hub + "." + groupName); var message = SignalRMessageUtility.CreateMessage(fullName, input); var excludedConnectionIds = new string[] { GenerateRandomName(), GenerateRandomName() }; message.Filter = GetFilter(excludedConnectionIds.Select(s => PrefixHelper.GetConnectionId(s)).ToList()); var msgs = parser.GetMessages(message).ToList(); Assert.Single(msgs); var msg = msgs[0].Message as GroupBroadcastDataMessage; Assert.NotNull(msg); // For group message, it is the full name as the group, e.g. hg-hub.hub1.h.hub2.abcde Assert.Equal(fullName, msg.GroupName); Assert.Equal <string>(excludedConnectionIds, msg.ExcludedList); Assert.Equal(input, msg.Payloads["json"].GetSingleFramePayload()); }
public void TestHubUserMessage(string userName, string input, string hub, Type exceptionType = null) { var hubs = new List <string> { "hub1", "hub.hub1", "hub2.hub1.h.hub2", ".", ".." }; var parser = new SignalRMessageParser(hubs, _resolver); var message = SignalRMessageUtility.CreateMessage(PrefixHelper.GetHubUserId(hub + "." + userName), input); var excludedConnectionIds = new string[] { GenerateRandomName(), GenerateRandomName() }; message.Filter = GetFilter(excludedConnectionIds.Select(s => PrefixHelper.GetConnectionId(s)).ToList()); if (exceptionType != null) { Assert.Throws(exceptionType, () => parser.GetMessages(message).ToList()); return; } var msgs = parser.GetMessages(message).ToList(); Assert.Single(msgs); var msg = msgs[0].Message as UserDataMessage; Assert.NotNull(msg); Assert.Equal(userName, msg.UserId); Assert.Equal(input, msg.Payloads["json"].GetSingleFramePayload()); }
public void TestHubMessage(string connectionId, string input, Type exceptionType = null) { var hubs = new List <string> { "h-", "a", "a.connection1" }; var parser = new SignalRMessageParser(hubs, _resolver); var groupName = GenerateRandomName(); var message = SignalRMessageUtility.CreateMessage(PrefixHelper.GetHubName(connectionId), input); var excludedConnectionIds = new string[] { GenerateRandomName(), GenerateRandomName() }; message.Filter = GetFilter(excludedConnectionIds.Select(s => PrefixHelper.GetConnectionId(s)).ToList()); if (exceptionType != null) { Assert.Throws(exceptionType, () => parser.GetMessages(message).ToList()); return; } var msgs = parser.GetMessages(message).ToList(); Assert.Single(msgs); var msg = msgs[0].Message as BroadcastDataMessage; Assert.NotNull(msg); Assert.Equal <string>(excludedConnectionIds, msg.ExcludedList); Assert.Equal(input, msg.Payloads["json"].GetSingleFramePayload()); }
public void TestHubConnectionMessage(string connectionId, string input, string expectedId, Type exceptionType = null) { var hubs = new List <string> { "hub", "hub1", "hub.hub1", "h", "hub.hub1.h.hub2", "hub.hub1.h" }; var parser = new SignalRMessageParser(hubs, _resolver); var groupName = GenerateRandomName(); var message = SignalRMessageUtility.CreateMessage(PrefixHelper.GetHubConnectionId(connectionId), input); var excludedConnectionIds = new string[] { GenerateRandomName(), GenerateRandomName() }; message.Filter = GetFilter(excludedConnectionIds.Select(s => PrefixHelper.GetConnectionId(s)).ToList()); if (exceptionType != null) { Assert.Throws(exceptionType, () => parser.GetMessages(message).ToList()); return; } var msgs = parser.GetMessages(message).ToList(); Assert.Single(msgs); var msg = msgs[0].Message as ConnectionDataMessage; Assert.NotNull(msg); Assert.Equal(expectedId, msg.ConnectionId); Assert.Equal(input, msg.Payload.First.GetSingleFramePayload()); }
public static void Handle(TwitchBot twitchBot, ChatMessage chatMessage, string alias) { if (chatMessage.GetMessage().IsMatch(PatternCreator.Create(alias, PrefixHelper.GetPrefix(chatMessage.Channel), @"\s\w+(\s\S+)?"))) { twitchBot.SendFuck(chatMessage); } }
protected override IList <string> GetSignals(string userId, string connectionId) { var signals = _hubs.SelectMany(info => { var items = new List <string> { PrefixHelper.GetHubName(info.Name), PrefixHelper.GetHubConnectionId(info.CreateQualifiedName(connectionId)), }; if (!String.IsNullOrEmpty(userId)) { items.Add(PrefixHelper.GetHubUserId(info.CreateQualifiedName(userId))); } return(items); }) .Concat(new[] { PrefixHelper.GetConnectionId(connectionId), PrefixHelper.GetAck(connectionId) }); return(signals.ToList()); }
public static async Task PerformAsync(ShardedCommandContext context, DataBase db) { try { var guild = FindOrCreateGuild.Perform(context.Guild, db); // toList to force enumeration before we shuffle identifier var bannedUsers = context.Guild.Users.Where(x => PrefixHelper.UserBlocked(x.Id, guild)).ToList(); guild.UserIdentifierSeed = new Random().Next(int.MinValue, int.MaxValue); var items = bannedUsers.Select(x => PrefixHelper.GetIdentifierString(x.Id, guild)).Select(x => new BannedIdentifier { Identifier = x }); db.RemoveRange(guild.BannedIdentifiers); items.Select((x) => { guild.BannedIdentifiers.Add(x); return(true); }).ToList(); db.SaveChanges(); await context.Channel.SendMessageAsync(text : "User identifiers have been randomized."); } catch (Exception ex) { Console.WriteLine("error rotating"); Console.WriteLine(ex.ToString()); } }
private IHub CreateHub(IRequest request, HubDescriptor descriptor, string connectionId, StateChangeTracker tracker = null, bool throwIfFailedToCreate = false) { try { var hub = _manager.ResolveHub(descriptor.Name); if (hub != null) { tracker = tracker ?? new StateChangeTracker(); hub.Context = new HubCallerContext(request, connectionId); hub.Clients = new HubConnectionContext(_pipelineInvoker, Connection, descriptor.Name, connectionId, tracker); hub.Groups = new GroupManager(Connection, PrefixHelper.GetHubGroupName(descriptor.Name)); } return(hub); } catch (Exception ex) { Trace.TraceInformation("Error creating Hub {0}. " + ex.Message, descriptor.Name); if (throwIfFailedToCreate) { throw; } return(null); } }
public static void Handle(TwitchBot twitchBot, ChatMessage chatMessage, string alias) { if (chatMessage.GetMessage().IsMatch(PatternCreator.Create(alias, PrefixHelper.GetPrefix(chatMessage.Channel), @"\s\S{3,}"))) { twitchBot.SendSuggestionNoted(chatMessage); } }
private bool IsEnabled() { if (localAttr == null) { return(false); } if (localRowInstance != null) { return(true); } localRowInstance = (ILocalizationRow)Activator.CreateInstance(localAttr.LocalizationRow); rowPrefixLength = PrefixHelper.DeterminePrefixLength(BasedOnRow.EnumerateTableFields(), x => x.Name); localRowPrefixLength = PrefixHelper.DeterminePrefixLength(localRowInstance.EnumerateTableFields(), x => x.Name); mappedIdField = localRowInstance.FindField(localAttr.MappedIdField ?? BasedOnRow.IdField.Name); if (mappedIdField is null) { throw new InvalidOperationException(string.Format("Can't locate localization table mapped ID field for {0}!", localRowInstance.Table)); } return(true); }
public static void Handle(TwitchBot twitchBot, ChatMessage chatMessage, string alias) { if (chatMessage.GetMessage().IsMatch(PatternCreator.Create(alias, PrefixHelper.GetPrefix(chatMessage.Channel), @"\s\S+\s" + Pattern.TimeSplitPattern + @"\s" + Pattern.TimeSplitPattern + @"(\s|$)"))) { twitchBot.SendCreatedNuke(chatMessage, chatMessage.GetLowerSplit()[1], TimeHelper.ConvertStringToSeconds(new() { chatMessage.GetLowerSplit()[2] }), TimeHelper.ConvertStringToMilliseconds(new() { chatMessage.GetLowerSplit()[3] })); } }
public ClientProxy(IConnection connection, IHubPipelineInvoker invoker, string hubName, IList <string> exclude) { _connection = connection; _invoker = invoker; _hubName = hubName; _exclude = exclude; _signal = PrefixHelper.GetHubName(_hubName); }
private Task ProcessRequestPostGroupRead(HostContext context, string groupsToken) { string connectionId = Transport.ConnectionId; // Get the user id from the request string userId = UserIdProvider.GetUserId(context.Request); IList <string> signals = GetSignals(userId, connectionId); IList <string> groups = AppendGroupPrefixes(context, connectionId, groupsToken); Connection connection = CreateConnection(connectionId, signals, groups); Connection = connection; string groupName = PrefixHelper.GetPersistentConnectionGroupName(DefaultSignalRaw); Groups = new GroupManager(connection, groupName); // We handle /start requests after the PersistentConnection has been initialized, // because ProcessStartRequest calls OnConnected. if (IsStartRequest(context.Request) && !(Transport is WebSocketTransport)) { return(ProcessStartRequest(context, connectionId)); } Transport.Connected = () => { return(TaskAsyncHelper.FromMethod(() => OnConnected(context.Request, connectionId).OrEmpty())); }; Transport.Reconnected = () => { return(TaskAsyncHelper.FromMethod(() => OnReconnected(context.Request, connectionId).OrEmpty())); }; Transport.Received = data => { Counters.ConnectionMessagesSentTotal.Increment(); Counters.ConnectionMessagesSentPerSec.Increment(); return(TaskAsyncHelper.FromMethod(() => OnReceived(context.Request, connectionId, data).OrEmpty())); }; Transport.Disconnected = clean => { return(TaskAsyncHelper.FromMethod(() => OnDisconnected(context.Request, connectionId, stopCalled: clean).OrEmpty())); }; if (IsConnectRequest(context.Request) && (Transport is WebSocketTransport)) { return(OnConnected(context.Request, connectionId).OrEmpty() .Then(c => c.ConnectionsConnected.Increment(), Counters).Then(() => Transport.ProcessRequest(connection).OrEmpty() .Catch(Trace, Counters.ErrorsAllTotal, Counters.ErrorsAllPerSec).Then(() => connection.Send(connectionId, "OK") .Catch(Trace, Counters.ErrorsAllTotal, Counters.ErrorsAllPerSec)))); } return(Transport.ProcessRequest(connection).OrEmpty() .Catch(Trace, Counters.ErrorsAllTotal, Counters.ErrorsAllPerSec)); }
public bool ContainsKey(string key) { if (PrefixHelper.HasGroupPrefix(key)) { return(_groupTopics.ContainsKey(key)); } return(_topics.ContainsKey(key)); }
internal static Task Ack(this IMessageBus bus, string acker, string waiter, string commandId) { // Prepare the ack var message = new Message(acker, PrefixHelper.GetAck(waiter), null); message.CommandId = commandId; message.IsAck = true; return(bus.Publish(message)); }
public TableOfContentsViewModel(TableOfContents fromDb, DocsVersion.DocsMode mode) { Mode = mode; this.Key = PrefixHelper.GetCategoryPrefix(fromDb.Category); this.Items = new List <TableOfContentsViewModel>(); this.IsFolder = true; this.Title = fromDb.Category.GetDescription(); this.AddChildren(fromDb.Items); }
public Topic GetOrAdd(string key, Func <string, Topic> factory) { if (PrefixHelper.HasGroupPrefix(key)) { return(_groupTopics.GetOrAdd(key, factory)); } return(_topics.GetOrAdd(key, factory)); }
public bool TryGetValue(string key, out Topic topic) { if (PrefixHelper.HasGroupPrefix(key)) { return(_groupTopics.TryGetValue(key, out topic)); } return(_topics.TryGetValue(key, out topic)); }
/// <summary> /// Returns a dynamic representation of the specified group. /// </summary> /// <param name="groupName">The name of the group</param> /// <param name="excludeConnectionIds">The list of connection ids to exclude</param> /// <returns>A dynamic representation of the specified group.</returns> public dynamic Group(string groupName, params string[] excludeConnectionIds) { if (string.IsNullOrEmpty(groupName)) { throw new ArgumentException(Resources.Error_ArgumentNullOrEmpty, "groupName"); } return(new GroupProxy(_send, groupName, _hubName, PrefixHelper.GetPrefixedConnectionIds(excludeConnectionIds))); }
public static void Handle(TwitchBot twitchBot, ChatMessage chatMessage, string alias) { if (chatMessage.GetMessage().IsMatch(PatternCreator.Create(alias, PrefixHelper.GetPrefix(chatMessage.Channel), @"\s#?\w+"))) { if (chatMessage.Username == Resources.Owner) { twitchBot.JoinChannel(chatMessage.GetLowerSplit()[1]); } } }
static StaticInfo EnsureInfo() { var newInfo = info; if (newInfo != null) { return(newInfo); } var logTableAttr = typeof(TRow).GetCustomAttribute <CaptureLogAttribute>(false); if (logTableAttr == null || logTableAttr.LogTable.IsTrimmedEmpty()) { throw new InvalidOperationException(String.Format("{0} row type has no capture log table attribute defined!", typeof(TRow).Name)); } schemaName = RowRegistry.GetSchemaName(typeof(TRow)); var instance = RowRegistry.GetSchemaRow(schemaName, logTableAttr.LogTable); if (instance == null) { throw new InvalidOperationException(String.Format("Can't locate {0} capture log table in schema {1} for {2} row type!", logTableAttr.LogTable, schemaName, typeof(TRow).Name)); } var captureLogRow = instance as ICaptureLogRow; if (captureLogRow == null) { throw new InvalidOperationException(String.Format("Capture log table {0} doesn't implement ICaptureLogRow interface!", logTableAttr.LogTable, schemaName, typeof(TRow).Name)); } if (!(captureLogRow is IIsActiveRow)) { throw new InvalidOperationException(String.Format("Capture log table {0} doesn't implement IIsActiveRow interface!", logTableAttr.LogTable, schemaName, typeof(TRow).Name)); } newInfo = new StaticInfo(); newInfo.logRowInstance = instance; newInfo.captureLogInstance = captureLogRow; newInfo.rowInstance = new TRow(); newInfo.rowFieldPrefixLength = PrefixHelper.DeterminePrefixLength(newInfo.rowInstance.EnumerateTableFields(), x => x.Name); newInfo.logFieldPrefixLength = PrefixHelper.DeterminePrefixLength(instance.EnumerateTableFields(), x => x.Name); newInfo.mappedIdField = ((Row)captureLogRow).FindField(logTableAttr.MappedIdField) as IIdField; if (newInfo.mappedIdField == null) { throw new InvalidOperationException(String.Format("Can't locate capture log table mapped ID field for {0}!", ((Row)captureLogRow).Table)); } info = newInfo; return(newInfo); }
public bool TryRemove(string key) { Topic topic; if (PrefixHelper.HasGroupPrefix(key)) { return(_groupTopics.TryRemove(key, out topic)); } return(_topics.TryRemove(key, out topic)); }
private IList <string> GetDefaultSignals(string userId, string connectionId) { // The list of default signals this connection cares about: // 1. The default signal (the type name) // 2. The connection id (so we can message this particular connection) return(new string[] { DefaultSignal, PrefixHelper.GetConnectionId(connectionId) }); }
public Task Invoke(string method, params object[] args) { var invocation = new ClientHubInvocation { Hub = _hubName, Method = method, Args = args }; return(_send(PrefixHelper.GetHubName(_hubName), invocation, _exclude)); }