示例#1
0
        public override void HandleRequest(Request request)
        {
            if (request.RequestFrom.AccessLevel >= AccessLevel.Public)
            {
                Match expressionMatch = _youtubeRegex.Match(request.Message);

                if (expressionMatch.Success)
                {
                    string videoId = expressionMatch.Groups[1].Value;

                    VideoResponse videoResponse = YouTubeService.GetVideo(new VideoRequest() {VideoId = videoId});

                    if(videoResponse.Video != null)
                    {
                        Response response = request.CreateResponse(ResponseType.Public, videoResponse.Video.Title + " (Views: " + videoResponse.Video.ViewCount.ToString("#,##0") + ")");
                        ModuleManagementContainer.HandleResponse(response);
                    }
                    else
                    {
                        Response response = request.CreateResponse(ResponseType.Public, "I had a problem fetching the title of that youtube video, sorry dude.");
                        ModuleManagementContainer.HandleResponse(response);
                    }
                }
            }
        }
        public override void HandleRequest(Request request)
        {
            if (request.RequestFrom.AccessLevel >= AccessLevel.Public && request.Message.StartsWith("~AccessToken", StringComparison.OrdinalIgnoreCase))
            {
                var splitMessage = request.Message.Split(' ');

                // We've got an operation.
                if (splitMessage.Length > 1)
                {
                    // TODO [Kog 07/23/2011] : We need to fix looking up who requested the token. This mechanism is pretty bad.

                    // Look up the user who sent the message.
                    var userToken = AuthenticationManager.ExchangeTokenForConcreteType<IrcUserToken>(request.RequestFrom.User);
                    var user = AuthenticationManager.FindHostByCloak(userToken.HostMask);

                    // Handle a user requesting a new access token.
                    if (splitMessage[1].Equals("request", StringComparison.InvariantCultureIgnoreCase))
                    {
                        // Try and pull the TTL for the token out of the args.
                        var timeToLive = 1;

                        if (splitMessage.Length > 2)
                        {
                            int.TryParse(splitMessage[2], out timeToLive);
                        }

                        var accessTokenExpiration = timeToLive == 0 ? DateTime.MaxValue : DateTime.Now.ToUniversalTime().AddDays(timeToLive);

                        // Generate a new GUID.
                        var accessToken = Guid.NewGuid();
                        var accessTokenCreationTime = DateTime.Now.ToUniversalTime();

                        // Slap it on the user's account.
                        user.AccessToken = accessToken.ToString();
                        user.AccessTokenIssueTime = accessTokenCreationTime;
                        user.AccessTokenExpiration = accessTokenExpiration;

                        // Update the account.
                        AuthenticationManager.UpdateHost(user);

                        // Hand it back.
                        Reply(request, ResponseType.Private, "Your new access token is {0}.", accessToken);
                    }

                    // Handle a user asking for their current access token.
                    if (splitMessage[1].Equals("display", StringComparison.InvariantCultureIgnoreCase))
                    {
                        ModuleManagementContainer.HandleResponse(request.CreateResponse(ResponseType.Private,
                                                                                        user.AccessToken == null ? "You have no access token. Please request one." :
                                                                                        String.Format("Your access token is {0} and was generated at {1} UTC. The token will expire at {2} UTC.",
                                                                                                        user.AccessToken, user.AccessTokenIssueTime, user.AccessTokenExpiration)));
                    }
                }
                else
                {
                    // The user used the command incorrectly.
                    Reply(request, ResponseType.Private, "Invalid access token request, please consult the help for details.");
                }
            }
        }
示例#3
0
        public override void HandleRequest(Request request)
        {
            var messageArray = request.Message.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            if (request.RequestSourceType == RequestSourceType.Private
                && request.RequestFrom.AccessLevel >= AccessLevel.Root
                && messageArray[0].Equals("~puppet", StringComparison.OrdinalIgnoreCase)
                && messageArray.Length >= 4)
            {
                var target = messageArray[2].Trim();
                var message = string.Empty;

                for (var i = 3; i < messageArray.Length; i++)
                {
                    message += messageArray[i];
                    message += " ";
                }

                if (messageArray[1].Equals("say", StringComparison.OrdinalIgnoreCase))
                {
                    var response = request.CreateResponse(ResponseTargetType.Public, ResponseType.Message, false, message);
                    response.Channel = target;
                    ModuleManagementContainer.HandleResponse(response);
                }
                else if (messageArray[1].Equals("do", StringComparison.OrdinalIgnoreCase))
                {
                    var response = request.CreateResponse(ResponseTargetType.Public, ResponseType.Action, false, message);
                    response.Channel = target;
                    ModuleManagementContainer.HandleResponse(response);
                }
            }
        }
示例#4
0
        public override void HandleRequest(Request request)
        {
            var message = request.Message.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            if (request.RequestFrom.AccessLevel >= AccessLevel.Root
                && message[0].Equals("~logging", StringComparison.OrdinalIgnoreCase)
                && message.Length == 2)
            {
                var levelName = message[1].ToLower();

                if (_loggingLevels.ContainsKey(levelName))
                {
                    var loggingLevel = _loggingLevels[levelName];

                    LoggerManager.GetAllRepositories().ForEach(x =>
                    {
                        x.Threshold = loggingLevel;
                        x.GetCurrentLoggers().ForEach(y => ((Logger)y).Level = loggingLevel);
                    });

                    ((Hierarchy)log4net.LogManager.GetRepository()).Root.Level = loggingLevel;
                    XmlConfigurator.Configure(new FileInfo("log4net.xml"));

                    // You may not actually catch this if you've just set the level to WARN, but if you're doing that type of filtering chances are you don't care anyway.
                    _logger.InfoFormat("Set logging level to {0}.", loggingLevel.DisplayName);
                }
            }
        }
        public override void HandleRequest(Request request)
        {
            if (request.RequestFrom.AccessLevel >= AccessLevel.Public &&
                request.Message.StartsWith("~email", StringComparison.OrdinalIgnoreCase))
            {
                var splitMessage = request.Message.Split(' ');

                // We've got an operation.
                if (splitMessage.Length > 1)
                {
                    // Look up the user who sent the message.
                    var userToken = AuthenticationManager.ExchangeTokenForConcreteType<IrcUserToken>(request.RequestFrom.User);
                    var user = AuthenticationManager.FindHostByCloak(userToken.HostMask);

                    // Handle the case when the user wants to set their email.
                    if (splitMessage[1].Equals("set", StringComparison.InvariantCultureIgnoreCase))
                    {
                        // Make sure the user has given us an email.
                        if (splitMessage.Length > 2)
                        {
                            var email = splitMessage[2];

                            try
                            {
                                user.EmailAddress = email;
                                AuthenticationManager.UpdateHost(user);

                                Reply(request, ResponseType.Private, "Your email has been set to {0}", email);
                            }
                            catch (Exception ex)
                            {
                                // Ruh roh, they've violated our unique constraint.
                                Logger.Warn("Caught an exception trying to set someone's email.", ex);
                                Reply(request, ResponseType.Private, "Email {0} is already in use.", email);
                            }

                        }
                        else
                        {
                            // User hasn't given us an email, barf.
                            Reply(request, ResponseType.Private, "No email specified, cannot set email address.");
                        }
                    }

                    // Handle the case when the user wants to check their email.
                    if (splitMessage[1].Equals("display", StringComparison.InvariantCultureIgnoreCase))
                    {
                        ModuleManagementContainer.HandleResponse(request.CreateResponse(ResponseType.Private,
                                                                                        String.IsNullOrEmpty(user.EmailAddress) ? "You have no email address set."
                                                                                            : String.Format("Your currently set email is {0}.", user.EmailAddress)));
                    }
                }
                else
                {
                    // User has given us an invalid request, barf.
                    Reply(request, ResponseType.Private, "Invalid request, please read the help for email.");
                }
            }
        }
示例#6
0
 public override void HandleRequest(Request request)
 {
     if (request.RequestFrom.AccessLevel >= AccessLevel.Public
         && request.Message.Equals("~about", StringComparison.OrdinalIgnoreCase))
     {
         SendResponse(request);
     }
 }
示例#7
0
        /// <summary>
        /// Handles responding to a user IFF they have proper access, and the trigger is ~name.
        /// </summary>
        /// 
        /// <param name="request">A <see cref="Request"/> representing a message sent to the bot.</param>
        public override void HandleRequest(Request request)
        {
            string[] messageArray = request.Message.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            if (request.RequestFrom.AccessLevel >= AccessLevel.Public
                && request.RequestType == RequestType.Public
                && messageArray[0].Equals("~"+Name, StringComparison.OrdinalIgnoreCase))
            {
                ModuleManagementContainer.HandleResponse(request.CreateResponse(ResponseType.Public, Phrase));
            }
        }
示例#8
0
        /// <summary>
        /// Sends a help response for a given module.
        /// </summary>
        /// 
        /// <param name="module">The module to send information about.</param>
        /// <param name="request">The incoming message to respond to.</param>
        private void SendHelpResponses(IModule module, Request request)
        {
            Response response = request.CreateResponse(ResponseType.Private);

            response.Message = "Module Name: " + module.Name;
            ModuleManagementContainer.HandleResponse(response);

            response.Message = "Module Description: " + module.Description;
            ModuleManagementContainer.HandleResponse(response);

            response.Message = "Module Instructions: " + module.Instructions;
            ModuleManagementContainer.HandleResponse(response);
        }
示例#9
0
        public override void HandleRequest(Request request)
        {
            string[] message = request.Message.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            // The user must be root, the request must be a 1:1 PRIVMSG and it's gotta be of a known form factor.
            if (request.RequestFrom.AccessLevel >= AccessLevel.Root
                && request.RequestType == RequestType.Private
                && message[0].Equals("~users", StringComparison.OrdinalIgnoreCase)
                && (message.Length >= 2 && message.Length <= 5))
            {
                // users list
                if (message[1].Equals("list", StringComparison.OrdinalIgnoreCase) && message.Length == 2)
                {
                    ListUsers(request);
                }

                // users add hostmask level
                if (message[1].Equals("add", StringComparison.OrdinalIgnoreCase) && message.Length == 4)
                {
                    AddUser(message[2], message[3], request);
                }

                // users del hostmask
                if (message[1].Equals("del", StringComparison.OrdinalIgnoreCase) && message.Length == 3)
                {
                    DeleteUser(message[2], request);
                }

                // TODO: Kog 1/13/2010 - We can probably replace this with something like a nested collection of funcs. Make it funky now.

                // users metadata ..
                if (message[1].Equals("metadata", StringComparison.OrdinalIgnoreCase) && message.Length == 5)
                {
                   // If they're trying to del the tag, do so.
                   if (message[2].Equals("del", StringComparison.OrdinalIgnoreCase))
                   {
                       DeleteMetaDatumForUser(message[3], message[4], request);
                   }
                   else
                   {
                       // if they give a key and a value, create or update the tag accordingly.
                       CreateOrUpdateMetaDatumForUser(message[2], message[3], message[4], request);
                   }
                }
            }
        }
示例#10
0
        /// <summary>
        /// Attempts to process our search request.
        /// </summary>
        /// 
        /// <param name="request">Our incoming message.</param>
        public override void HandleRequest(Request request)
        {
            if (request.RequestType == RequestType.Public)
            {
                string[] messageArray = request.Message.Split(' ');

                if (request.Message.StartsWith("~")
                    && request.RequestFrom.AccessLevel >= AccessLevel.Public
                    && messageArray.Length >= 2
                    && messageArray[0].ToLower() == SearchTrigger)
                {
                    string searchTerms = string.Empty;

                    for (int i = 1; i < messageArray.Length; i++)
                    {
                        searchTerms += messageArray[i] + " ";
                    }

                    Logger.DebugFormat("{0} - HandleRequest called on for {1} by {2}", Name, request.Message,
                                       request.Addressee ?? request.Nick);

                    SearchProvider.ExecuteSearch(searchTerms, SearchUrl, x => HandleResults(x, request, searchTerms));
                }

                else if (messageArray[0].StartsWith(NetworkConnectionInformation.BotNickname))
                {
                    if (request.RequestFrom.AccessLevel >= AccessLevel.Public
                        && messageArray.Length >= 3
                        && messageArray[1].ToLower() == SearchTrigger.Substring(1))
                    {
                        string searchTerms = string.Empty;

                        for (int i = 2; i < messageArray.Length; i++)
                        {
                            searchTerms += messageArray[i] + " ";
                        }

                        Logger.DebugFormat("{0} - HandleRequest called on for {1} by {2}", Name, request.Message,
                                           request.Addressee ?? request.Nick);

                        SearchProvider.ExecuteSearch(searchTerms, SearchUrl,
                                                     x => HandleResults(x, request, searchTerms));
                    }
                }
            }
        }
示例#11
0
        /// <summary>
        /// Checks to see if the user has called for a shutdown, and if so what their access level is. If they have the proper permissions we then attempt to parse an 
        /// optional quit message.
        /// </summary>
        /// 
        /// <param name="request">Our incoming message.</param>
        public override void HandleRequest(Request request)
        {
            // The user has permission and is indeed requesting a shutdown.
            if (request.RequestFrom.AccessLevel >= AccessLevel.Root && request.Message.StartsWith("~shutdown", StringComparison.OrdinalIgnoreCase))
            {
                // Parse off our quit message.
                string message = "No quit message specified.";
                int offset = request.Message.IndexOf("~shutdown") + 9;

                if (request.Message.Length > offset)
                {
                    message = request.Message.Substring(offset).Trim();
                }

                BotContext.Shutdown(message);
            }
        }
示例#12
0
        /// <summary>
        /// See if we want to digest this message, and if so take action.
        /// </summary>
        /// 
        /// <param name="request">A message</param>
        public override void HandleRequest(Request request)
        {
            if (request.RequestFrom.AccessLevel >= AccessLevel.Public)
            {
                Match expressionMatch = _karmaRegex.Match(request.Message);

                if (expressionMatch.Success)
                {
                    String nick = expressionMatch.Groups[1].Value;
                    String op = expressionMatch.Groups[2].Value;

                    Response response;

                    // Make sure the sender isn't messing with their own karma.
                    if (nick.Equals(request.Nick, StringComparison.OrdinalIgnoreCase) && !String.IsNullOrEmpty(op))
                    {
                        response = request.CreateResponse(ResponseType.Public, string.Format("{0}, toggling your own karma is very uncool.", request.Nick));
                        ModuleManagementContainer.HandleResponse(response);
                    }
                    else
                    {
                        // Attempt to look the user up.
                        KarmaItem karma = KarmaDao.FindKarma(nick.ToLower()) ?? new KarmaItem {KarmaLevel = 0, UserName = nick.ToLower()};

                        // If they're doing anything more than looking...
                        if (!String.IsNullOrEmpty(op))
                        {
                            if (op.Equals("--"))
                            {
                                karma.KarmaLevel--;
                            }
                            else if (op.Equals("++"))
                            {
                                karma.KarmaLevel++;
                            }

                            KarmaDao.SaveKarma(karma);
                        }

                        response = request.CreateResponse(ResponseType.Public, String.Format("{0} has a karma of {1}", nick, karma.KarmaLevel));
                        ModuleManagementContainer.HandleResponse(response);
                    }
                }
            }
        }
示例#13
0
        private void SendResponse(Request request)
        {
            string message = string.Format("{0} (V{1}) is the ##csharp irc bot on freenode.net",
                                           NetworkConnectionInformation.BotNickname,
                                           Assembly.GetEntryAssembly().GetName().Version.ToString(2));
            Response response = request.CreateResponse(ResponseType.Private, message);
            ModuleManagementContainer.HandleResponse(response);

            response.Message = "====================================";
            ModuleManagementContainer.HandleResponse(response);
            response.Message = "IRC: To get help with the bot type '~Help' in private message with the bot.";
            ModuleManagementContainer.HandleResponse(response);
            response.Message = "Wiki: http://wiki.freenode-csharp.net/wiki/";
            ModuleManagementContainer.HandleResponse(response);
            response.Message = "====================================";
            ModuleManagementContainer.HandleResponse(response);
            response.Message = "But there's no sense crying over every mistake. You just keep on trying till you run out of cake.";
            ModuleManagementContainer.HandleResponse(response);
        }
示例#14
0
        public override void HandleRequest(Request request)
        {
            if (request.RequestFrom.AccessLevel >= AccessLevel.Public)
            {
                string[] messageArray = request.Message.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                if (messageArray[0].Equals("~help", StringComparison.OrdinalIgnoreCase))
                {
                    // A user has asked for help, not specifying a module. List what we've got.
                    if (messageArray.Length == 1)
                    {
                        SendHelpResponses(ModuleManagementContainer.Modules.Where(module => module.Name.Equals("Help")).First(), request);
                        SendModulesListResponse(request);
                    }
                    // A user has asked for help regarding a specific module. Attempt to display help for it.
                    else if (messageArray.Length == 2)
                    {
                        string moduleName = messageArray[1];
                        IModule targetModule = ModuleManagementContainer.Modules.Where(module =>
                                                                                       module.Name.Equals(moduleName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();

                        // We know what that module is!
                        if (null != targetModule && targetModule.RequiredAccessLevel <= request.RequestFrom.AccessLevel)
                        {
                            SendHelpResponses(targetModule, request);
                        }
                        // What? What module is that you say? Quick lads, play dumb!
                        else
                        {
                            SendModuleNotFoundResponse(moduleName, request);
                        }
                    }
                    // A user has asked us for something we don't understand. Tell them to try again.
                    else
                    {
                        SendIncorrectRequestSyntaxResponse(request);
                        SendHelpResponses(ModuleManagementContainer.Modules.Where(module => module.Name.Equals("Help")).First(), request);
                        SendModulesListResponse(request);
                    }
                }
            }
        }
示例#15
0
        public override void HandleRequest(Request request)
        {
            if (request.RequestFrom.AccessLevel >= AccessLevel.Public)
            {
                Match expressionMatch = _urbanRegex.Match(request.Message);

                if (expressionMatch.Success)
                {
                    bool urlRequested = expressionMatch.Groups[1].Value.Equals("nu", StringComparison.InvariantCultureIgnoreCase);
                    string term = expressionMatch.Groups[2].Value;

                    UrbanResponse urbanResponse = UrbanService.Search(new UrbanRequest() {Term = term});

                    if(urbanResponse != null)
                    {
                        if(urbanResponse.Definition.HasValue())
                        {
                            Response response = request.CreateResponse(ResponseType.Public, "Definition: " + urbanResponse.Definition.Replace('\r', ' ').Replace('\n', ' '));
                            ModuleManagementContainer.HandleResponse(response);
                        }

                        if(urbanResponse.Example.HasValue())
                        {
                            Response response = request.CreateResponse(ResponseType.Public, "Example: " + urbanResponse.Example.Replace('\r', ' ').Replace('\n', ' '));
                            ModuleManagementContainer.HandleResponse(response);
                        }

                        if (urlRequested && urbanResponse.Url.HasValue())
                        {
                            Response response = request.CreateResponse(ResponseType.Public, "Url: " + urbanResponse.Url);
                            ModuleManagementContainer.HandleResponse(response);
                        }
                    }
                    else
                    {
                        Response response = request.CreateResponse(ResponseType.Public, "I couldn't find anything with the term '" + term + "', sorry dude.");
                        ModuleManagementContainer.HandleResponse(response);
                    }
                }
            }
        }
示例#16
0
        public override void HandleRequest(Request request)
        {
            if (request.RequestFrom.AccessLevel >= AccessLevel.Public)
            {
                Match expressionMatch = _weatherRegex.Match(request.Message);

                if (expressionMatch.Success)
                {
                    string command = expressionMatch.Groups[1].Value;
                    string location = expressionMatch.Groups[2].Value;

                    WeatherResponse weatherResponse = WeatherProvider.WeatherRequest(new WeatherRequest() {Command = command, Location = location});

                    foreach (var message in weatherResponse.Response)
                    {
                        Response response = request.CreateResponse(ResponseType.Public, message);
                        ModuleManagementContainer.HandleResponse(response);
                    }
                }
            }
        }
示例#17
0
        private void SendResponse(Request request)
        {
            var message = string.Format("{0} (V{1}) is the ##csharp irc bot on freenode.net", 
                                           NetworkConnectionInformation.BotNickname, 
                                           Assembly.GetEntryAssembly().GetName().Version.ToString(2));

            var response = request.CreateResponse(ResponseTargetType.Private, message);
            ModuleManagementContainer.HandleResponse(response);
            response.Message = "====================================";
            ModuleManagementContainer.HandleResponse(response);
            response.Message = "IRC: To get help with the bot type '~Help' in private message with the bot.";
            ModuleManagementContainer.HandleResponse(response);
            response.Message = "Wiki: http://wiki.freenode-csharp.net/wiki/";
            ModuleManagementContainer.HandleResponse(response);
            response.Message = "====================================";
            ModuleManagementContainer.HandleResponse(response);
            response.Message = "But there's no sense crying over every mistake. You just keep on trying till you run out of cake.";
            ModuleManagementContainer.HandleResponse(response);
            response.Message = "Go make some new disaster. That's what I'm counting on. You're someone else's problem. Now I only want you gone.";
            ModuleManagementContainer.HandleResponse(response);
        }
示例#18
0
        public override void HandleRequest(Request request)
        {
            string[] messageArray = request.Message.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            if (request.RequestFrom.AccessLevel >= AccessLevel.Public
                && request.RequestType == RequestType.Public
                && messageArray[0].Equals("~tell", StringComparison.OrdinalIgnoreCase))
            {
                string newMessage = string.Empty;

                for (int i = 1; i < messageArray.Length; i++)
                {
                    if (i == 1)
                    {
                        request.Addressee = messageArray[i];
                    }
                    else if (i == 2)
                    {
                        string command;

                        if (!messageArray[i].StartsWith("~"))
                            command = "~" + messageArray[i];
                        else
                            command = messageArray[i];

                        newMessage += command;
                        newMessage += " ";
                    }
                    else if (i > 2)
                    {
                        newMessage += messageArray[i];
                        newMessage += " ";
                    }
                }

                request.Message = newMessage.Trim();

                ModuleManagementContainer.HandleRequest(request);
            }
        }
示例#19
0
        public override void HandleRequest(Request request)
        {
            // The user has permission and is indeed requesting a shutdown.
            if (request.RequestFrom.AccessLevel >= AccessLevel.Root && request.Message.StartsWith("~Channel", StringComparison.OrdinalIgnoreCase))
            {
                // Parse our message and split out a couple of vars... a tad bit nicer than magic numbers.
                string[] splitMessage = request.Message.Split(' ');
                string operationDescription = splitMessage[1];
                string target = splitMessage[2];

                // Do the operation if we know how, else log.
                if (splitMessage.Length == 3 && _supportedOperations.ContainsKey(operationDescription))
                {
                    var operation = _supportedOperations[operationDescription];
                    operation.Invoke(target);
                }
                else
                {
                    Logger.InfoFormat("Caught a channel action request that we don't know how to parse from {0}: {1}", request.Nick, request.Message);
                }
            }
        }
示例#20
0
 /// <summary>
 /// A conveninence method to cut down on the repetitive chatter of sending a response through our module subsystem.
 /// </summary>
 /// 
 /// <param name="message">The message to send back out.</param>
 /// <param name="request">Our incoming <see cref="Request"/> object, which we use for creating our response.</param>
 public void SendResponse(string message, Request request)
 {
     ModuleManagementContainer.HandleResponse(request.CreateResponse(ResponseType.Private, message));
 }
示例#21
0
 /// <summary>
 /// Given from our contract in IModule. This class does not actually provide any implementation
 /// details.
 /// </summary>
 /// 
 /// <param name="request">A message relayed to this module.</param>
 /// 
 /// <remarks>
 /// As filtering on a per-message basis is done by any given module (in theory to allow N consumers),
 /// every module is sent every message, and they can either handle or disregard the message. There is 
 /// currently no mechanism for stopping propagation of the message (IE: we've handled the message). This
 /// may come when we hook up AOP (then we'll expect a 1:1 between message and consumer, sans advice points).
 /// </remarks>
 public abstract void HandleRequest(Request request);
示例#22
0
 /// <summary>
 /// Pretty prints all the users in our system.
 /// </summary>
 /// 
 /// <param name="request">A <see cref="Request"/> object we can use for creating a response to.</param>
 /// 
 /// <remarks>
 /// This may get to be incredibly spammy if you have a number of hosts.
 /// </remarks>
 private void ListUsers(Request request)
 {
     SendResponse(AuthenticationManager.GetHosts().Select(x => TranslateHostToString(x)).Implode(", "), request);
 }
示例#23
0
 /// <summary>
 /// Attempts to delete a given hostmask, assuming it already exists.
 /// </summary>
 /// 
 /// <param name="hostmask">The hostmask to remove.</param>
 /// <param name="request">Our incoming <see cref="Request"/> object, which we use for creating our response.</param>
 private void DeleteUser(string hostmask, Request request)
 {
     if (!AuthenticationManager.KnowsHost(hostmask))
     {
         SendResponse(String.Format("The hostmask {0} already has no current entry.", hostmask), request);
     }
     else
     {
         AuthenticationManager.ForgetHost(hostmask);
         SendResponse(String.Format("The hostmask {0} has been removed.", hostmask), request);
     }
 }
示例#24
0
        // TODO: Kog 1/13/2010 - The thought occurs to me that it would be really nice to have some sort of syntax allowing metadata to be added
        // TODO: Kog 1/13/2010 - or tags to be added with spaces. For now, let's just go with the crude stuff here.
        /// <summary>
        /// Deletes a metadatum for a given "tag" on a known host.
        /// </summary>
        /// 
        /// <param name="host">The literal string of a cloak to modify metadata for.</param>
        /// <param name="tag">The metadatum's "tag" (think of this like a key in a key/value pair). Must have no spaces</param>
        /// <param name="request">Our incoming <see cref="Request"/> object, which we use for creating our response.</param>
        /// 
        /// <remarks>
        /// If the host is not found (via a literal search), or the tag does not exist on the host, the outbound request will notify the calling user. 
        /// </remarks>
        private void DeleteMetaDatumForUser(string host, string tag, Request request)
        {
            var knownHost = AuthenticationManager.FindHostByCloak(host);
            var response = String.Format("Tag {0} successfully removed from {1}.", tag, host);

            // Make sure we have the host...
            if (null != knownHost)
            {
                var metaDatum = knownHost.MetaData.FirstOrDefault(x => x.Tag.Equals(tag, StringComparison.OrdinalIgnoreCase));

                // Make sure we have that tag
                if (null != metaDatum)
                {
                    // TODO: Kog 1/13/2010 - perhaps this should just become one operation on the auth manager. The whole known host bit needs to be refactored most likely anyway.

                    // Tell our persistence layer to do the needful.
                    knownHost.MetaData.Remove(metaDatum);
                    AuthenticationManager.UpdateHost(knownHost);
                }
                else
                {
                    response = String.Format("Could not remove tag {0} from host {1}, no such tag known.", tag, host);
                }
            }
            else
            {
                response = String.Format("Host {0} doesn't exist, can't remove tag {1}", host, tag);
            }

            SendResponse(response, request);
        }
示例#25
0
        /// <summary>
        /// Attempts to either create a new metadatum entry on a known host, or update the value of a currently existing tag. 
        /// </summary>
        /// 
        /// <param name="host">The literal string of a cloak to modify metadata for.</param>
        /// <param name="tag">The metadatum's "tag" (think of this like a key in a key/value pair). Must have no spaces.</param>
        /// <param name="value">The metadatum's "value" (think of this like a value in a key/value pair). Must have no spaces.</param>
        /// <param name="request">Our incoming <see cref="Request"/> object, which we use for creating our response.</param>
        /// 
        /// <remarks>
        /// If the host is not found (via a literal search) the outbound request will notify the calling user.  
        /// </remarks>
        private void CreateOrUpdateMetaDatumForUser(string host, string tag, string value, Request request)
        {
            var knownHost = AuthenticationManager.FindHostByCloak(host);
            var response = String.Format("Tag {0} successfully added to {1}.", tag, host);

            // Make sure we have the host...
            if (null != knownHost)
            {
                // Attempt to find or create our tag.
                var metaDatum = knownHost.MetaData.FirstOrDefault(x => x.Tag.Equals(tag, StringComparison.OrdinalIgnoreCase));

                if (null == metaDatum)
                {
                    // Create our new tag and add it to our mapped collection.
                    metaDatum = new KnownHostMetaDatum {Host = knownHost, Tag = tag};
                    knownHost.MetaData.Add(metaDatum);
                }

                // Slap in our new value.
                metaDatum.Value = value;

                // Tell our persistence layer to do the needful.
                AuthenticationManager.UpdateHost(knownHost);
            }
            else
            {
                response = String.Format("Host {0} doesn't exist, can't remove tag {1}", host, tag);
            }

            SendResponse(response, request);
        }
示例#26
0
        /// <summary>
        /// Attempts to add the given hostmask, if it doesn't already exist.
        /// </summary>
        /// 
        /// <param name="hostmask">The hostmask to add.</param>
        /// <param name="level">The level to add: either <code>ADMIN</code> or <code>PUBLIC</code>. </param>
        /// <param name="request">Our incoming <see cref="Request"/> object, which we use for creating our response.</param>
        /// 
        /// <remarks>
        /// At present we only add <see cref="HostMatchType.Start"/> type users, and if a proper level is not specified, it is assumed that the user wants
        /// a <see cref="AccessLevel.Public"/>. There is also currently no way to add a <see cref="AccessLevel.Root"/> user, which is by design.
        /// </remarks>
        private void AddUser(string hostmask, string level, Request request)
        {
            if (AuthenticationManager.KnowsHost(hostmask))
            {
                SendResponse(String.Format("The hostmask {0} already has an entry.", hostmask), request);
            }
            else
            {
                var host = new KnownHost
                {
                    AccessLevel = GetAccessLevelByName(level),
                    HostMask = hostmask,
                    HostMatchType = HostMatchType.Start,
                };

                AuthenticationManager.RememberHost(host);
                ModuleManagementContainer.HandleResponse(request.CreateResponse(ResponseType.Private, String.Format("Learned host {0}", TranslateHostToString(host))));
            }
        }
示例#27
0
 /// <summary>
 /// Passes our internal message format to all subscribers.
 /// </summary>
 /// 
 /// <param name="request">Our message to pass.</param>
 public void HandleRequestReceived(Request request)
 {
     try
     {
         if (_requestReceived != null)
         {
             _requestReceived(this, new RequestReceivedEventArgs(request));
         }
     }
     catch (Exception ex)
     {
         _logger.WarnFormat("Caught an exception trying to HandleRequestReceived on [channel {0} nick {1} request type {2} message {3}]: {4}",
                            request.Channel ?? "N/A", request.RequestFrom.User.DisplayName, request.RequestType, request.Message, ex);
     }
 }
示例#28
0
        // TODO: Kog 11/23/2009 - Do we want to keep the broadcast nature of our commands? Should we, instead, have a 1-1 mapping established at load time
        // TODO: Kog 11/23/2009 - and cached in a dictionary somewhere?

        // TODO: Kog 11/23/2009 - If we need this for the tell module, can we swap to using some sort of advice? Or, can we have the tell module somehow digest
        // TODO: Kog 11/23/2009 - the message, and then ask the module manager to re-handle? Or does that require mutability of the request?

        /// <summary>
        /// Routes an incoming message to all modules for consumption.
        /// </summary>
        /// 
        /// <param name="request">The message to pass.</param>
        /// 
        /// <remarks>
        /// This method may seem useless, but is currently required for our Tell module.
        /// </remarks>
        public void HandleRequest(Request request)
        {
            Modules.ForEach(module => module.HandleRequest(request));
        }
示例#29
0
 protected void Reply(Request request, ResponseType responseType, string responseMessage)
 {
     ModuleManagementContainer.HandleResponse(request.CreateResponse(ResponseTargetType.Public, responseType, responseMessage));
 }
示例#30
0
 /// <summary>
 /// Provides a utility method for responding to users, cutting down on copy/paste.
 /// </summary>
 /// 
 /// <param name="request">The request that triggered the message.</param>
 /// <param name="responseType">The type of response to return: whether the message is public or private.<see cref="ResponseTargetType"/></param>
 /// <param name="responseMessage">The literal text of the response message.</param>
 /// <param name="formatObjects">An optional set of format objects. Will be passed along to String.format.</param>
 /// 
 /// <returns></returns>
 protected void Reply(Request request, ResponseTargetType responseTargetType, ResponseType responseType, string responseMessage, params object[] formatObjects)
 {
     ModuleManagementContainer.HandleResponse(request.CreateResponse(responseTargetType, responseType, responseMessage, formatObjects));
 }