예제 #1
0
파일: TRegex.cs 프로젝트: szliyang/Toolbox
        public void IsMatch()
        {
            var test   = "ReGeX reGgaE";
            var actual = TRegex.IsMatch(test, "regex");

            Assert.IsTrue(actual);
        }
예제 #2
0
        bool cmdRKill(VPServices app, Avatar who, string data)
        {
            if (data != app.Bot.Name)
            {
                return(true);
            }

            if (!config.GetBoolean("Enabled", false))
            {
                app.Warn(who.Session, msgDisabled);
                return(true);
            }

            var permitted = config.Get("Users", "");

            if (!TRegex.IsMatch(who.Name, permitted))
            {
                app.Warn(who.Session, msgUnauth);
                return(true);
            }

            // Perform the kill
            System.Environment.Exit(0);
            return(true);
        }
예제 #3
0
        bool cmdHelp(VPServices app, Avatar who, string data)
        {
            var helpUrl = app.PublicUrl + "help";

            if (data != "")
            {
                // If given data, try to find specific command and print help in console for
                // that user
                foreach (var cmd in app.Commands)
                {
                    if (TRegex.IsMatch(data, cmd.Regex))
                    {
                        app.Bot.ConsoleMessage(who.Session, ChatEffect.BoldItalic, VPServices.ColorInfo, "", msgCommandTitle, cmd.Name);
                        app.Bot.ConsoleMessage(who.Session, ChatEffect.Italic, VPServices.ColorInfo, "", msgCommandRgx, cmd.Regex);
                        app.Bot.ConsoleMessage(who.Session, ChatEffect.Italic, VPServices.ColorInfo, "", msgCommandDesc, cmd.Help);
                        app.Bot.ConsoleMessage(who.Session, ChatEffect.Italic, VPServices.ColorInfo, "", msgCommandExample, cmd.Example);

                        return(true);
                    }
                }

                app.Warn(who.Session, "Could not match any command for '{0}'; try {1}", data, helpUrl);
                return(true);
            }
            else
            {
                // Broadcast help URL for everybody
                app.NotifyAll("Command help can be found at {0}", helpUrl);
                return(true);
            }
        }
예제 #4
0
        private void AnalyzeTField(TField tfield, HtmlNode hn, XmlElement root, XmlDocument xdResult)
        {
            string name   = tfield.Name;
            TConst tconst = tfield.TConst;
            TXPath txpath = tfield.TXPath;
            TRegex tregex = tfield.TRegex;

            if (txpath == null)
            {
                String valConst = AnalyzeTConst(tconst);
                AddElement(name, valConst, root, xdResult);
                return;
            }

            String valXpath = AnalyzeTXPath(txpath, hn);

            if (tregex == null)
            {
                AddElement(name, valXpath, root, xdResult);
                return;
            }

            String valRegex = AnalyzeTRegex(tregex, valXpath);

            AddElement(name, valRegex, root, xdResult);
        }
예제 #5
0
파일: TRegex.cs 프로젝트: szliyang/Toolbox
        public void Match()
        {
            var test   = "ReGeX reGgaE";
            var actual = TRegex.Match(test, "regex");

            Assert.AreEqual(actual.Value, "ReGeX");
        }
예제 #6
0
파일: TRegex.cs 프로젝트: szliyang/Toolbox
        public void TryMatch_Fail()
        {
            string[] actual;
            var      test = "Testing out tryMatch out";

            Assert.IsFalse(TRegex.TryMatch(test, "fail", out actual));
            Assert.IsNull(actual);
        }
예제 #7
0
파일: TRegex.cs 프로젝트: szliyang/Toolbox
        public void Replace_String()
        {
            var test     = "It's a question of LUst, it's a question of TRust";
            var expected = "It's a question of love, it's a question of love";
            var actual   = TRegex.Replace(test, "(l|tr)ust", "love");

            Assert.AreEqual(expected, actual);
        }
예제 #8
0
파일: TRegex.cs 프로젝트: szliyang/Toolbox
        public void TryMatch()
        {
            string[] actual;
            var      test     = "Testing out tryMatch out";
            var      expected = new[] { "out" };

            Assert.IsTrue(TRegex.TryMatch(test, "out", out actual));
            CollectionAssert.AreEqual(expected, actual);
        }
예제 #9
0
        private static TRegex GetTRegex(XmlNode xnField)
        {
            XmlNode xnRegex = xnField.SelectSingleNode(@"./regex");

            if (xnRegex == null)
            {
                return(null);
            }
            TPattern tp = GetTPattern(xnRegex);
            TFormat  tf = GetTFormat(xnRegex);
            TRegex   tr = new TRegex(tp, tf);

            return(tr);
        }
예제 #10
0
        private static TField GetTField(XmlNode xnField)
        {
            XmlNode xnName = xnField.SelectSingleNode(@"./name");

            if (xnName == null)
            {
                throw new Exception("no name tag found");
            }
            string name = xnName.InnerText;
            TXPath tx   = GetTXPath(xnField);
            TRegex tr   = GetTRegex(xnField);
            TConst tc   = GetTConst(xnField);
            TField tf   = new TField(name, tx, tr, tc);

            return(tf);
        }
예제 #11
0
 public static bool TryParseBool(string msg, out bool value)
 {
     if (TRegex.IsMatch(msg, "^(true|1|yes|on)$"))
     {
         value = true;
         return(true);
     }
     else if (TRegex.IsMatch(msg, "^(false|0|no|off)$"))
     {
         value = false;
         return(true);
     }
     else
     {
         value = false;
         return(false);
     }
 }
예제 #12
0
파일: TRegex.cs 프로젝트: szliyang/Toolbox
        public void Replace_Eval()
        {
            var test     = "It's a question of LUst, it's a question of TRust";
            var expected = "It's a question of trust, it's a question of lust";
            var actual   = TRegex.Replace(test, "(l|tr)ust", m => {
                if (m.Value == "LUst")
                {
                    return("trust");
                }
                else if (m.Value == "TRust")
                {
                    return("lust");
                }
                else
                {
                    return("???");
                }
            });

            Assert.AreEqual(expected, actual);
            StringAssert.DoesNotMatch(actual, new Regex(@"\?\?\?"));
        }
예제 #13
0
        void onChat(Instance bot, Avatar user, string message)
        {
            lock ( mutex )
            {
                string[] match;
                string[] wrongMatch;

                if (!TRegex.TryMatch(message, entryInPlay.Answer, out match))
                {
                    return;
                }

                if (entryInPlay.Wrong != null && TRegex.TryMatch(message, entryInPlay.Wrong, out wrongMatch))
                {
                    Log.Debug(tag, "Given answer '{0}' by {1} matched, but turned out to be wrong; rejecting", wrongMatch[0], user.Name);
                    return;
                }

                gameEnd();

                var welldone = welldones.Skip(VPServices.Rand.Next(welldones.Length)).Take(1).Single();

                if (match[0].IEquals(entryInPlay.CanonicalAnswer))
                {
                    app.Bot.ConsoleBroadcast(ChatEffect.Bold, VPServices.ColorInfo, "Triviamaster",
                                             msgAccepted, entryInPlay.CanonicalAnswer, welldone, user.Name);
                }
                else
                {
                    app.Bot.ConsoleBroadcast(ChatEffect.Bold, VPServices.ColorInfo, "Triviamaster",
                                             msgAcceptedFrom, entryInPlay.CanonicalAnswer, match[0], welldone, user.Name);
                }

                Log.Debug(tag, "Correct answer '{0}' by {1}", match[0], user.Name);
                awardPoint(user.Name);
            }
        }
예제 #14
0
        private string AnalyzeTRegex(TRegex tregex, string valXpath)
        {
            Regex  regex  = tregex.TPattern.Regex;
            string format = tregex.TFormat == null ? "" : tregex.TFormat.Format;

            Match m = regex.Match(valXpath);

            if (format == null)
            {
                return(m.Groups[1].Value);
            }

            List <string> valGroup = new List <string>();

            for (int i = 1; i < m.Groups.Count; i++)
            {
                string gv = m.Groups[i].Value;
                valGroup.Add(gv);
            }

            string value = Format(format, valGroup);

            return(value);
        }
예제 #15
0
        /// <summary>
        /// Parses incoming chat for a command and runs it
        /// </summary>
        void parseCommand(Instance sender, Avatar user, string message)
        {
            // Accept only commands
            if (!message.StartsWith("!"))
            {
                return;
            }

            var intercept = message
                            .Trim()
                            .Split(new[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries);

            var beginTime     = DateTime.Now;
            var targetCommand = intercept[0].Substring(1).ToLower();
            var data          =
                intercept.Length == 2
                ? intercept[1].Trim()
                : "";

            // Iterate through commands, rejecting invokes if time limited
            foreach (var cmd in Commands)
            {
                if (TRegex.IsMatch(targetCommand, cmd.Regex))
                {
                    var timeSpan = cmd.LastInvoked.SecondsToNow();
                    if (timeSpan < cmd.TimeLimit)
                    {
                        App.Warn(user.Session, "That command was used too recently; try again in {0} seconds.", cmd.TimeLimit - timeSpan);
                        Log.Info("Commands", "User {0} tried to invoke {1} too soon", user.Name, cmd.Name);
                    }
                    else
                    {
                        try
                        {
                            Log.Fine("Commands", "User {0} firing command {1}", user.Name, cmd.Name);
                            cmd.LastInvoked = DateTime.Now;

                            var success = cmd.Handler(this, user, data);
                            if (!success)
                            {
                                App.Warn(user.Session, "Invalid command use; please see example:");
                                Bot.ConsoleMessage(user.Session, ChatEffect.Italic, ColorWarn, "", cmd.Example);
                            }
                        }
                        catch (Exception e)
                        {
                            App.Alert(user.Session, "Sorry, I ran into an issue executing that command. Please notify the host.");
                            App.Alert(user.Session, "Error: {0}", e.Message);

                            Log.Severe("Commands", "Exception firing command {0}", cmd.Name);
                            e.LogFullStackTrace();
                        }
                    }

                    Log.Fine("Commands", "Command {0} took {1} seconds to process", cmd.Name, beginTime.SecondsToNow());
                    return;
                }
            }

            App.Warn(user.Session, "Invalid command; try !help");
            Log.Debug("Commands", "Unknown: {0}", targetCommand);
            return;
        }
예제 #16
0
        void processContext(HttpListenerContext ctx)
        {
            // Ignore favicon requests
            if (ctx.Request.RawUrl.Contains("favicon.ico"))
            {
                ctx.Response.Close();
                return;
            }

            Log.Fine("Web server", "Request for {0} by {1}", ctx.Request.RawUrl, ctx.Request.RemoteEndPoint);
            string response    = null;
            var    intercept   = ctx.Request.RawUrl.Split(new[] { '/' }, 2, StringSplitOptions.RemoveEmptyEntries);
            var    targetRoute = intercept.Length >= 1 ? intercept[0] : null;
            var    data        = intercept.Length == 2 ? intercept[1] : null;

            if (targetRoute == null)
            {
                // Generate command listing
                response = string.Format(HTML_WHOLE,
                                         string.Format(HTML_HEAD, "VPServices web interface"),
                                         string.Format(HTML_BODY, mdGenerateRouteListing(), World, DateTime.Now));
            }
            else
            {
                // Search for route
                foreach (var rt in Routes)
                {
                    if (TRegex.IsMatch(targetRoute, rt.Regex) || rt.Name.Equals(targetRoute, StringComparison.CurrentCultureIgnoreCase))
                    {
                        Log.Debug("Web server", "Routing to {0}", rt.Name);
                        response = string.Format(HTML_WHOLE,
                                                 string.Format(HTML_HEAD, "VPServices: " + rt.Name),
                                                 string.Format(HTML_BODY, rt.Handler(this, data), World, DateTime.Now));

                        break;
                    }
                }

                // 404 handler
                if (response == null)
                {
                    response = string.Format(HTML_WHOLE,
                                             string.Format(HTML_HEAD, "Route not handled"),
                                             string.Format(HTML_BODY,
                                                           string.Format(HTML_NOTHANDLED, targetRoute, PublicUrl),
                                                           World, DateTime.Now));

                    ctx.Response.StatusCode        = 404;
                    ctx.Response.StatusDescription = "Unhandled route";
                }
            }

            using (var outStream = new StreamWriter(ctx.Response.OutputStream))
            {
                try
                {
                    outStream.Write(response);
                    outStream.Flush();
                    ctx.Response.AddHeader("Content-Type", "Content-Type:text/html; charset=utf-8");
                    ctx.Response.Close();
                }
                catch { Log.Info("Web server", "Discarding response for closed connection {0}", ctx.Request.RemoteEndPoint); }
            }
        }