Exemplo n.º 1
0
        public override void HandleCommand(IrcLine line, Nick nick, Channel channel)
        {
            try {
                Seen     seen      = Seen.Fetch(nick);
                DateTime checkTime = DateTime.Now;
                checkTime.AddDays(-7);
                if (seen.FirstSeenAt == DateTime.MinValue || seen.FirstSeenAt > checkTime)
                {
                    conn.SendPrivmsg(nick.Name, String.Format("Sorry, {0}, but you aren't allowed to use the mugshots functions yet. :(", nick.DisplayName));
                    return;
                }

                Regex r = new Regex(@"^!setinfo ?");
                line.Args = r.Replace(line.Args, "").Trim();
                if (line.Args.Length <= 0)   // Whaaaat??
                {
                    conn.SendPrivmsg(nick.Name, "Usage: !setinfo <your message here>");
                }
                else
                {
                    nick.Account.MostRecentNick = nick;

                    Info info = Info.FetchOrCreate(nick.Account);
                    info.InfoTxt   = line.Args;
                    info.IsActive  = true;
                    info.IsDeleted = false;
                    info.Save();

                    conn.SendPrivmsg(nick.Name, "Your info has been saved! :D");
                }
            } catch (Exception e) {
                logger.Error(e);
                conn.SendPrivmsg(nick.Name, "Oof… My neck is killing me, I can't do that right now. :(");
            }
        }
Exemplo n.º 2
0
        public override void HandleCommand(IrcLine line, Nick nick, Channel channel)
        {
            try {
                if (!isOp(nick))
                {
                    conn.SendPrivmsg(nick.Name, String.Format("Sorry, {0}, but that command doesn't exist. Try !help.", nick.DisplayName));
                    return;
                }

                string target = nick.Name;
                if (channel != null && channel.AllowCommandsInChannel)
                {
                    target = channel.Name;
                }

                Regex r = new Regex(@"^!join ?");
                line.Args = r.Replace(line.Args, "").Trim();
                if (line.Args.Length <= 1)   // Whaaaat??
                {
                    conn.SendPrivmsg(target, String.Format("Usage(1): !join <channel>"));
                }
                else
                {
                    r = new Regex(@"^#+[a-zA-Z0-9_`\-]+$");
                    Match m = r.Match(line.Args);
                    if (!m.Success)
                    {
                        conn.SendPrivmsg(target, String.Format("Usage(1): !join <channel> — Channel should start with a # and contain no spaces"));
                    }
                    else
                    {
                        Channel ircChannel = conn.Server.ConnectedChannels.FirstOrDefault(x => x.Name == line.Args.ToLower());
                        if (ircChannel != null)
                        {
                            conn.SendPrivmsg(target, String.Format("Uh… {0}… I'm already /in/ {1}… o.o", nick.DisplayName, line.Args));
                        }
                        else
                        {
                            ircChannel = Channel.FetchOrCreate(line.Args, conn.Server);
                            if (ircChannel != null)
                            {
                                List <Channel> channels = new List <Channel>();
                                logger.Debug("Joining " + ircChannel.Name);
                                conn.SendPrivmsg(target, String.Format("Joining {0}! :D", line.Args));
                                conn.Send("JOIN " + ircChannel.Name);
                                channels.Add(ircChannel);
                                conn.LoadUserDataForJoinedChannels(channels);
                            }
                            else
                            {
                                conn.SendPrivmsg(target, String.Format("Sorry, {0}, but I couldn't join `{1}` as I couldn't fetch it from the database.", nick.DisplayName, line.Args));
                            }
                        }
                    }
                }
            } catch (Exception e) {
                logger.Error(e);
                conn.SendPrivmsg(nick.Name, "¡Ay caray! It's Lupus! D:");
            }
        }
Exemplo n.º 3
0
        public void DoTrackKickPlugin(IrcConnection conn, IrcLine line)
        {
            Regex r = new Regex(@"^(?<channel>#[^ ]+) (?<idiot>.*)$", RegexOptions.ExplicitCapture);
            Match m = r.Match(line.IrcCommandArgsRaw);

            if (m.Success)
            {
                string channelName = m.Groups["channel"].Value;
                string idiot       = m.Groups["idiot"].Value;

                Nick    banner    = conn.Server.ConnectedNicks.FirstOrDefault(x => x.Name == line.Nick.ToLower());
                Nick    idiotNick = conn.Server.ConnectedNicks.FirstOrDefault(x => x.Name == idiot.ToLower());
                Channel channel   = conn.Server.ConnectedChannels.FirstOrDefault(x => x.Name == channelName.ToLower());

                Ban ban = Ban.Fetch(channel, idiotNick);
                if (ban != null)
                {
                    if (ban.BannerAccount == null && banner.Account != null)
                    {
                        ban.BannerAccount = banner.Account;
                    }
                    ban.Nick = idiotNick;
                    if (idiotNick.Account != null)
                    {
                        ban.Account = idiotNick.Account;
                    }
                    ban.Channel    = channel;
                    ban.BanMessage = line.Trail;

                    LumbricusContext.db.SaveChanges();
                }
            }
        }
Exemplo n.º 4
0
 public override void HandleCommand(IrcLine line, Nick nick, Channel channel)
 {
     try {
         Setting helpUriSetting = Setting.Fetch("Help", "Uri");
         if (helpUriSetting == null)
         {
             conn.SendPrivmsg(nick.Name, String.Format("Oh dear… I'm afraid I don't seem to be able to answer that right now, {0}!", nick.DisplayName));
             return;
         }
         if (nick.Account != null && isOp(nick))
         {
             string target = nick.Name;
             if (channel != null && channel.AllowCommandsInChannel)
             {
                 target = channel.Name;
             }
             conn.SendPrivmsg(target, String.Format("Hi, @{0}. Main help is at {1}. You also have access to these op-only commands: !seen, !baninfo, !botban, !restart", nick.DisplayName, helpUriSetting.Value));
         }
         else
         {
             conn.SendPrivmsg(nick.Name, String.Format("Hi, {0}. Help is at {1}.", nick.DisplayName, helpUriSetting.Value));
             if (channel != null && !channel.AllowCommandsInChannel)
             {
                 conn.SendPrivmsg(nick.Name, "Also, please try to only interact with me directly through this window. Bot commands in the main channel are against channel policy, and some people get really annoyed about it. :(");
             }
         }
     } catch (Exception e) {
         logger.Error(e);
         conn.SendPrivmsg(nick.Name, "Oof… I really shouldn't have had that second slice of cake, I can't do that right now. :(");
     }
 }
        public override void HandleCommand(IrcLine line, Nick nick, Channel channel)
        {
            try {
                Seen     seen      = Seen.Fetch(nick);
                DateTime checkTime = DateTime.Now;
                checkTime.AddDays(-7);
                if (seen.FirstSeenAt == DateTime.MinValue || seen.FirstSeenAt > checkTime)
                {
                    conn.SendPrivmsg(nick.Name, String.Format("Sorry, {0}, but you aren't allowed to use the mugshots functions yet. :(", nick.DisplayName));
                    return;
                }

                Mugshot mugshot = Mugshot.Fetch(nick.Account);
                if (mugshot == null)
                {
                    conn.SendPrivmsg(nick.Name, "You don't have a mugshot in the database to clear! :o");
                    return;
                }

                nick.Account.MostRecentNick = nick;

                mugshot.IsDeleted = true;
                mugshot.Save();

                conn.SendPrivmsg(nick.Name, "Your mugshot has been cleared. :(");
            } catch (Exception e) {
                logger.Error(e);
                conn.SendPrivmsg(nick.Name, "Oof… I've got indigestion or something, I can't do that right now. :(");
            }
        }
Exemplo n.º 6
0
        public override void Send(string t)
        {
            var line = IrcLine.Parse(t);

            if ((line.Message.Equals("PRIVMSG", StringComparison.OrdinalIgnoreCase) || line.Message.Equals("NOTICE", StringComparison.OrdinalIgnoreCase)) &&
                (line.Parameters[0] == "#" || IrcStringComparer.RFC1459.Equals(line.Parameters[0], "User")))
            {
                // Emulate a channel message to # or PM to 'User' by sticking it on the console.
                writeMessage(line.Parameters[1]);
            }
        }
Exemplo n.º 7
0
 void Enqueue(IrcLine line)
 {
     if (!queue.ContainsKey(line.Nick))
     {
         queue.Add(line.Nick, new List <IrcLine>());
     }
     if (queue[line.Nick].Count <= 0)
     {
         Send(String.Format("WHO {0} %uhnfa", line.Nick));
     }
     queue[line.Nick].Add(line);
 }
Exemplo n.º 8
0
        public override void HandleCommand(IrcLine line, Nick nick, Channel channel)
        {
            try {
                if (!isOp(nick))
                {
                    conn.SendPrivmsg(nick.Name, String.Format("Sorry, {0}, but that command doesn't exist. Try !help.", nick.DisplayName));
                    return;
                }

                string target = nick.Name;
                if (channel != null && channel.AllowCommandsInChannel)
                {
                    target = channel.Name;
                }

                Regex r = new Regex(@"^!part ?");
                line.Args = r.Replace(line.Args, "").Trim();
                if (line.Args.Length <= 1)   // Whaaaat??
                {
                    conn.SendPrivmsg(target, String.Format("Usage(1): !part <channel>"));
                }
                else
                {
                    r = new Regex(@"^#+[a-zA-Z0-9_`\-]+$");
                    Match m = r.Match(line.Args);
                    if (!m.Success)
                    {
                        conn.SendPrivmsg(target, String.Format("Usage(1): !part <channel> — Channel should start with a # and contain no spaces"));
                    }
                    else
                    {
                        Channel ircChannel = conn.Server.ConnectedChannels.FirstOrDefault(x => x.Name == line.Args.ToLower());
                        if (ircChannel == null)
                        {
                            conn.SendPrivmsg(target, String.Format("Uh… {0}… I'm not /in/ {1}… o.o", nick.DisplayName, line.Args));
                        }
                        else
                        {
                            conn.SendPrivmsg(target, String.Format("Parting {0}. :(", line.Args));
                            logger.Debug("Parting " + ircChannel.Name);
                            conn.Send("PART " + ircChannel.Name);
                        }
                    }
                }
            } catch (Exception e) {
                logger.Error(e);
                conn.SendPrivmsg(nick.Name, "¡Ay caray! It's Lupus! D:");
            }
        }
Exemplo n.º 9
0
        public void DoAutoRejoinPlugin(IrcConnection conn, IrcLine line)
        {
            IrcCommand ircCommand = (IrcCommand)Enum.Parse(typeof(IrcCommand), line.IrcCommand);

            if (ircCommand == IrcCommand.KICK && line.IrcCommandArgs.GetValue(1).ToString() == conn.Server.BotNick)
            {
                logger.Info("{0} kicked me from {1}, so rejoining it!", line.Nick, line.IrcCommandArgs.GetValue(0));
                conn.Send(string.Format("JOIN {0}", line.IrcCommandArgs.GetValue(0)));
            }
            else if (ircCommand == IrcCommand.PART && line.Nick == conn.Server.BotNick)
            {
                logger.Info("I parted from {0}, so rejoining it!", line.IrcCommandArgs.GetValue(0));
                conn.Send(string.Format("JOIN {0}", line.IrcCommandArgs.GetValue(0)));
            }
        }
Exemplo n.º 10
0
        bool HandleUserAuthResponse(IrcLine line)
        {
            Regex r = new Regex(@":(?<server>[a-z0-9]+(\.[a-z0-9]+)+) 354 ([^ ]+) (?<user>[^ ]+) (?<host>[^ ]+) (?<nick>[^ ]+) (?<status>[^ ]+) (?<account>[^ ]+)\s*$", RegexOptions.ExplicitCapture);
            Match m = r.Match(line.RawLine);

            if (m.Success)
            {
                line.AccountName = m.Groups["account"].Value;
                line.Nick        = m.Groups["nick"].Value;
                line.User        = m.Groups["user"].Value;
                line.Host        = m.Groups["host"].Value;

                Handle354(line);
                return(true);
            }
            return(false);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Initializes a new instance of the WhoLine class.
        /// </summary>
        /// <param name="line">The line that is the base of the WhoLine.</param>
        public WhoLine(IrcLine line)
            : base(line)
        {
            if (line.Numeric != 352)
            {
                throw new ArgumentOutOfRangeException("line", "RPL_WHOREPLY 352 expected");
            }

            if (Parameters.Length < 8)
            {
                throw new ArgumentOutOfRangeException("line", "Need a minimum of 8 parameters");
            }

            user = new UserInfo(Parameters[5], Parameters[2], Parameters[3], Client);
            List<Mode> modes = new List<Mode>();
            int i = 1;

            isAway = Parameters[6][0] == 'G';
            isOper = Parameters[6][i] == '*';

            if (IsOper)
            {
                i++;
            }

            for (; i < Parameters[6].Length; i++)
            {
                FlagDefinition flag = Client.Standard.GetUserPrefixFlag(Parameters[6][i]);
                if (flag != null)
                {
                    modes.Add(new Mode(flag, FlagArt.Set, User.NickName));
                }
            }

            this.modes = modes.ToArray();

            realName = Parameters[7];

            if (!int.TryParse(realName.Substring(1, realName.IndexOf(" ")), out hopCount))
            {
                throw new ArgumentOutOfRangeException("line", "Invalid hop count, integer expected");
            }

            realName = realName.Substring(realName.IndexOf(" ") + 1);
        }
Exemplo n.º 12
0
        public override void Send(string t)
        {
            if (this.State != IrcClientState.Online)
            {
                return;
            }
            ConsoleUtils.WriteLine("%cDKGRAY{0} %cDKRED<<%cDKGRAY {1}%r", this.Address, t.Replace("%", "%%"));

            var line = IrcLine.Parse(t);

            if ((line.Message.Equals("PRIVMSG", StringComparison.OrdinalIgnoreCase) || line.Message.Equals("NOTICE", StringComparison.OrdinalIgnoreCase)) && (line.Parameters[0] == "#" ||
                                                                                                                                                              IrcStringComparer.RFC1459.Equals("#Lobby", line.Parameters[0]) ||
                                                                                                                                                              IrcStringComparer.RFC1459.Equals("#BattleRoom", line.Parameters[0]) ||
                                                                                                                                                              IrcStringComparer.RFC1459.Equals(this.Target.Nickname, line.Parameters[0])))
            {
                // Emulate a channel message or PM to the target by sending it over DCC.
                this.SendSub(line.Parameters[1].Replace("\u000F", "\u000F\u000312,99"));
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Initializes a new instance of the ChannelListLine class.
        /// </summary>
        /// <param name="line">The line, the ChannelListLine bases on.</param>
        public ChannelListLine(IrcLine line)
            : base(line)
        {
            if (line.Numeric != 332)
            {
                throw new ArgumentOutOfRangeException("line", "CHANNELLIST_RPL 322 expected");
            }

            if (Parameters.Length < 3)
            {
                throw new ArgumentOutOfRangeException("line", "Need a minimum of 3 parameters");
            }

            if (!int.TryParse(Parameters[2], out userCount))
            {
                throw new ArgumentOutOfRangeException("line", "Invalid user count, integer expected");
            }

            if (Parameters.Length > 3)
            {
                Regex modeTopicRegex = new Regex(@"(?:\[\+([^ \]]*)] )?(.*)");
                Match m = modeTopicRegex.Match(Parameters[3]);
                if (m.Success)
                {
                    modes = m.Groups[1].Value;
                    topic = m.Groups[2].Value;
                }
                else
                {
                    modes = string.Empty;
                    topic = string.Empty;
                }
            }
            else
            {
                modes = string.Empty;
                topic = string.Empty;
            }
        }
Exemplo n.º 14
0
        public void DoSeenPlugin(IrcConnection conn, IrcLine line)
        {
            // :[email protected] JOIN #channel
            // :Nick!~User@unaffiliated/Nick JOIN #channel
            // :Nick!~User@unaffiliated/Nick PART #channel
            // :Nick!~User@unaffiliated/Nick PART #channel :"screw you"
            // :[email protected] QUIT :Quit: Quit!
            // :[email protected] NICK :FourHalfWorms
            // :[email protected] PRIVMSG Lumbricus :!info Nick2
            Channel    channel    = null;
            IrcCommand ircCommand = (IrcCommand)Enum.Parse(typeof(IrcCommand), line.IrcCommand);

            switch (ircCommand)
            {
            case IrcCommand.JOIN:
            case IrcCommand.PART:
            case IrcCommand.PRIVMSG:
                if (line.IrcCommandArgsRaw.StartsWith("#"))
                {
                    channel = conn.GetChannel(line.IrcCommandArgsRaw);
                }
                goto case IrcCommand.NICK;

            case IrcCommand.NICK:
            case IrcCommand.NOTICE:
            case IrcCommand.QUIT:
                Nick nick = Nick.FetchOrCreate(line.Nick, conn.Server);
                if (nick == null)
                {
                    throw new Exception(String.Format("Unable to fetch or create nick `{0}`", nick));
                }

                Seen.Update(conn.Server, nick, nick.Account, channel);

                break;
            }
        }
Exemplo n.º 15
0
        public override void HandleCommand(IrcLine line, Nick nick, Channel channel)
        {
            try {
                if (nick.Account == null)
                {
                    conn.SendPrivmsg(nick.Name, String.Format("Sorry, {0}, but you need to be identified with services to clear your info.", nick.DisplayName));
                    return;
                }

                Seen     seen      = Seen.Fetch(nick);
                DateTime checkTime = DateTime.Now;
                checkTime.AddDays(-7);
                if (seen.FirstSeenAt == DateTime.MinValue || seen.FirstSeenAt > checkTime)
                {
                    conn.SendPrivmsg(nick.Name, String.Format("Sorry, {0}, but you aren't allowed to use the mugshots functions yet. :(", nick.DisplayName));
                    return;
                }

                Info info = Info.Fetch(nick.Account);
                if (info == null)
                {
                    conn.SendPrivmsg(nick.Name, "You don't have any info in the database to clear! :o");
                    return;
                }

                nick.Account.MostRecentNick = nick;

                info.IsDeleted = true;
                info.Save();

                conn.SendPrivmsg(nick.Name, "Your info has been cleared. :(");
            } catch (Exception e) {
                logger.Error(e);
                conn.SendPrivmsg(nick.Name, "Oof… I banged my knee and it don't half hurt, I can't do that right now. :(");
            }
        }
Exemplo n.º 16
0
        public void DoLogPlugin(IrcConnection conn, IrcLine line)
        {
            Nick    nick       = conn.Server.ConnectedNicks.FirstOrDefault(x => x.Name == line.Nick.ToLower());
            Channel ircChannel = conn.Server.ConnectedChannels.FirstOrDefault(x => x.Name == line.IrcCommandArgsRaw.ToLower());

            Log log = Log.Create(conn.Server);

            if (nick != null)
            {
                log.NickId = nick.Id;
            }
            if (nick?.Account != null)
            {
                log.AccountId = nick?.Account.Id;
            }
            if (ircChannel != null)
            {
                log.ChannelId = ircChannel.Id;
            }
            log.IrcCommand = line.IrcCommand.ToEnum <IrcCommand>();
            log.Trail      = line.Trail;
            log.Line       = line.RawLine;
            log.Save();
        }
Exemplo n.º 17
0
        public void DoTrackUserPlugin(IrcConnection conn, IrcLine line)
        {
            Channel    c = null;
            Nick       nick;
            IrcCommand ircCommand = line.IrcCommand.ToEnum <IrcCommand>();

            switch (ircCommand)
            {
            case IrcCommand.JOIN:
                nick = conn.FetchOrCreateIrcNick(line.Nick);
                c    = conn.Server.ConnectedChannels.FirstOrDefault(x => x.Name == line.IrcCommandArgsRaw);
                if (c != null)
                {
                    c.AddNick(nick);
                    nick.UserName = line.User;
                    nick.Host     = line.Host;
                    if (nick.Account != null)
                    {
                        conn.Server.AddAccount(nick.Account);
                    }
                    if (line.Nick != conn.Server.BotNick && nick.Account == null)
                    {
                        conn.Send(String.Format("WHO {0} %uhnfa", line.Nick));
                    }
                }
                break;

            case IrcCommand.PART:
                nick = conn.FetchIrcNick(line.Nick);
                c    = conn.Server.ConnectedChannels.FirstOrDefault(x => x.Name == line.IrcCommandArgsRaw);
                if (c != null)
                {
                    c.RemoveNick(nick);
                }
                if (nick.ConnectedChannels.Count <= 0)
                {
                    nick.Dispose();
                }
                break;

            case IrcCommand.QUIT:
                nick = conn.FetchIrcNick(line.Nick);
                nick.Dispose();
                break;

            case IrcCommand.NICK:
                nick = conn.FetchIrcNick(line.Nick);
                Nick newNick = conn.FetchOrCreateIrcNick(line.Trail);
                if (newNick != null)
                {
                    foreach (Channel channel in nick.ConnectedChannels)
                    {
                        newNick.AddChannel(channel);
                    }
                    newNick.UserName = line.User;
                    newNick.Host     = line.Host;
                    conn.Server.AddNick(newNick);
                    Setting notifyOfAccountChangesSetting = Setting.Fetch("ops", "notify_account_changes");
                    if (notifyOfAccountChangesSetting != null && notifyOfAccountChangesSetting.Value == "true")
                    {
                        if (nick.Account != null && newNick.Account != null && nick.Account.Id != newNick.Account.Id)
                        {
                            Setting notifyTargetSetting = Setting.Fetch("ops", "notify_account_changes_target");
                            if (notifyTargetSetting != null && notifyTargetSetting.Value.Length > 0)
                            {
                                conn.SendPrivmsg(notifyTargetSetting.Value, String.Format("\x02`{0}`\x0f ($a:\x02{1}\x0f) changed their nick to \x02`{2}`\x0f ($a:\x02{3}\x0f).", nick.Name, nick.Account.Name, newNick.Name, newNick.Account.Name));
                            }
                        }
                    }
                    if (newNick.Account != null)
                    {
                        conn.Server.AddAccount(newNick.Account);
                    }
                    else
                    {
                        conn.Send(String.Format("WHO {0} %uhnfa", line.Nick));
                    }
                }
                nick.Dispose();
                break;
            }
        }
Exemplo n.º 18
0
 /// <summary>
 /// Initializes a new instance of the LinksEndEventArgs class.
 /// </summary>
 /// <param name="line">The line, that marks the links block end.</param>
 /// <param name="linksLines">All lines of the links block.</param>
 public LinksEndEventArgs(IrcLine line, IrcLine[] linksLines)
     : base(line)
 {
     this.linksLines = linksLines;
 }
Exemplo n.º 19
0
 /// <summary>
 /// Initializes a new instance of the MotdBeginEventArgs class.
 /// </summary>
 /// <param name="line">The line, that marks the motd end.</param>
 public MotdBeginEventArgs(IrcLine line)
     : base(line)
 {
 }
Exemplo n.º 20
0
 /// <summary>
 /// Initializes a new instance of the InfoEndEventArgs class.
 /// </summary>
 /// <param name="line">The line, that marks the info block end.</param>
 /// <param name="infoLines">All lines of the info block.</param>
 public InfoEndEventArgs(IrcLine line, IrcLine[] infoLines)
     : base(line)
 {
     this.infoLines = infoLines;
 }
Exemplo n.º 21
0
        public override void HandleCommand(IrcLine line, Nick nick, Channel channel)
        {
            try {
                Setting largeImageBasePath = Setting.Fetch("Mugshots", "LargeImageBasePath");
                Setting originalBasePath   = Setting.Fetch("Mugshots", "OriginalBasePath");
                Setting thumbnailBasePath  = Setting.Fetch("Mugshots", "ThumbnailBasePath");

                Setting maxLargeHeightSetting = Setting.Fetch("Mugshots", "MaxLargeHeight");
                Setting maxLargeWidthSetting  = Setting.Fetch("Mugshots", "MaxLargeWidth");
                Setting thumbWidthSetting     = Setting.Fetch("Mugshots", "ThumbWidth");
                Setting thumbHeightSetting    = Setting.Fetch("Mugshots", "ThumbHeight");

                if (largeImageBasePath == null)
                {
                    throw new Exception("Mugshots/LargeImageBasePath is missing from Settings table");
                }
                if (originalBasePath == null)
                {
                    throw new Exception("Mugshots/OriginalBasePath is missing from Settings table");
                }
                if (thumbnailBasePath == null)
                {
                    throw new Exception("Mugshots/ThumbnailBasePath is missing from Settings table");
                }

                if (maxLargeHeightSetting == null)
                {
                    throw new Exception("Mugshots/MaxLargeHeight is missing from Settings table");
                }
                if (maxLargeWidthSetting == null)
                {
                    throw new Exception("Mugshots/MaxLargeWidth is missing from Settings table");
                }
                if (thumbWidthSetting == null)
                {
                    throw new Exception("Mugshots/ThumbWidth is missing from Settings table");
                }
                if (thumbHeightSetting == null)
                {
                    throw new Exception("Mugshots/ThumbHeight is missing from Settings table");
                }

                int maxLargeHeight = Int32.Parse(maxLargeHeightSetting.Value);
                int maxLargeWidth  = Int32.Parse(maxLargeWidthSetting.Value);
                int thumbHeight    = Int32.Parse(thumbHeightSetting.Value);
                int thumbWidth     = Int32.Parse(thumbWidthSetting.Value);

                if (maxLargeHeight < 1)
                {
                    throw new Exception("Mugshots/MaxLargeHeight in Settings table must be > 0");
                }
                if (maxLargeWidth < 1)
                {
                    throw new Exception("Mugshots/MaxLargeWidth in Settings table must be > 0");
                }
                if (thumbWidth < 1)
                {
                    throw new Exception("Mugshots/ThumbWidth in Settings table must be > 0");
                }
                if (thumbHeight < 1)
                {
                    throw new Exception("Mugshots/ThumbHeight in Settings table must be > 0");
                }

                if (!Directory.Exists(originalBasePath.Value))
                {
                    throw new Exception($"Directory `{originalBasePath.Value}` does not exist");
                }
                if (!Directory.Exists(largeImageBasePath.Value))
                {
                    throw new Exception($"Directory `{largeImageBasePath.Value}` does not exist");
                }
                if (!Directory.Exists(thumbnailBasePath.Value))
                {
                    throw new Exception($"Directory `{thumbnailBasePath.Value}` does not exist");
                }

                Seen     seen      = Seen.Fetch(nick);
                DateTime checkTime = DateTime.Now;
                checkTime.AddDays(-7);
                if (seen.FirstSeenAt == DateTime.MinValue || seen.FirstSeenAt > checkTime)
                {
                    conn.SendPrivmsg(nick.Name, String.Format("Sorry, {0}, but you aren't allowed to use the mugshots functions yet. :(", nick.DisplayName));
                    return;
                }

                Regex  r        = new Regex(@"^!setmugshot ?");
                string imageUri = r.Replace(line.Args, "").Trim();
                if (imageUri.Length <= 0)   // Whaaaat??
                {
                    conn.SendPrivmsg(nick.Name, "Usage: !setmugshot <image_url_here>");
                    return;
                }

                r = new Regex(@"^https?://.*\.(png|gif|jpe?g)");
                Match m = r.Match(imageUri);
                if (!m.Success)
                {
                    conn.SendPrivmsg(nick.Name, "Usage: !setmugshot <image_url_here> - the image must be a PNG, GIF, or JPEG file.");
                    return;
                }

                r = new Regex(@"^https?://(www.)?dropbox.com/.*\?dl=0");
                m = r.Match(imageUri);
                if (m.Success)
                {
                    imageUri = imageUri.Replace("?dl=0", "?dl=1");
                }

                Image original = GetImageFromUrl(imageUri);
                if (original == null)
                {
                    throw new Exception(String.Format("Unable to get image from URI `{0}`", imageUri));
                }

                float fileRatio = ((float)original.Width) / ((float)original.Height);
                logger.Trace("Got image! {0}x{1}, {2}", original.Width, original.Height, fileRatio);

                float maxRatio = thumbWidth / thumbHeight;
                int   width    = 0;
                int   height   = 0;
                if (fileRatio < maxRatio)
                {
                    height = maxLargeHeight;
                    width  = (int)Math.Ceiling(height * fileRatio);
                }
                else
                {
                    width  = maxLargeWidth;
                    height = (int)Math.Ceiling(width / fileRatio);
                }
                logger.Trace("Calculate resize dimensions: {0}x{1}", width, height);

                var rect  = new Rectangle(0, 0, width, height);
                var image = new Bitmap(width, height);
                try {
                    image.SetResolution(original.HorizontalResolution, original.VerticalResolution);
                } catch (Exception e) {
                    logger.Debug("image.SetResolution failed.");
                    logger.Trace(e);
                }
                using (var graphics = Graphics.FromImage(image))
                {
                    graphics.CompositingMode    = CompositingMode.SourceCopy;
                    graphics.CompositingQuality = CompositingQuality.HighQuality;
                    graphics.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                    graphics.SmoothingMode      = SmoothingMode.HighQuality;
                    graphics.PixelOffsetMode    = PixelOffsetMode.HighQuality;

                    using (var wrapMode = new ImageAttributes())
                    {
                        wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                        graphics.DrawImage(original, rect, 0, 0, original.Width, original.Height, GraphicsUnit.Pixel, wrapMode);
                    }
                }

                r = new Regex(@"\.([a-z0-9]{3})$");
                string newFileName = r.Replace(Path.GetRandomFileName(), ".png");
                Image  thumb       = original.GetThumbnailFixedSize(thumbWidth, thumbHeight, true);

                ImageCodecInfo info    = GetEncoderInfo("image/png");
                Encoder        encoder = Encoder.Quality;

                EncoderParameters encoderParams = new EncoderParameters(1);
                encoderParams.Param[0] = new EncoderParameter(encoder, 100);

                thumb.Save(Path.Combine(thumbnailBasePath.Value, newFileName), info, encoderParams);
                image.Save(Path.Combine(largeImageBasePath.Value, newFileName), info, encoderParams);
                original.Save(Path.Combine(originalBasePath.Value, newFileName), info, encoderParams);

                nick.Account.MostRecentNick = nick;

                Mugshot mugshot = Mugshot.FetchOrCreate(nick.Account);
                mugshot.FileName         = newFileName;
                mugshot.OriginalImageUri = imageUri;
                mugshot.IsActive         = true;
                mugshot.IsDeleted        = false;
                mugshot.LastModifiedAt   = DateTime.Now;
                mugshot.Save();

                conn.SendPrivmsg(nick.Name, "Your mugshot has been set! :D");
            } catch (SetMugshotException e) {
                logger.Error(e);
                conn.SendPrivmsg(nick.Name, "Sorry, but I was unable to download your mugshot photo from the URL you provided. Please try another URL, or poke TwoWholeWorms if this error continues.");
            } catch (Exception e) {
                logger.Error(e);
                conn.SendPrivmsg(nick.Name, "Oof… I shouldn't have eaten that pie, I can't do that right now. :(");
            }
        }
Exemplo n.º 22
0
        void HandleInput()
        {
            while (socket.Connected)
            {
                string line = GetLineFromSocket();

                try {
                    // PING :asimov.freenode.net
                    if (line.StartsWith("PING :"))
                    {
                        Send("PONG" + line.Substring(4));
                        continue;
                    }

                    IrcLine ircLine = new IrcLine();

                    // This /almost/ matches the entire spec. Will update it to properly track IRC Command arguments at some point, and probably change the names of variables a bit.
                    Regex r = new Regex(@"^(:((?<fullhost>(?<nick>[^!]+)!(?<user>[^@]+)@(?<host>[^ ]+))|(?<server>([^ ]+))) )?(?<irccommand>[A-Z]+|[0-9]+)( (?<irccommandargs>[^:]+))?( :(?<trail>.*))?$", (RegexOptions.ExplicitCapture | RegexOptions.Compiled | RegexOptions.IgnoreCase));
                    Match m = r.Match(line);
                    if (m.Success)
                    {
                        ircLine.RawLine = line;

                        ircLine.FullHost          = m.Groups["fullhost"].Value;
                        ircLine.Nick              = m.Groups["nick"].Value;
                        ircLine.User              = m.Groups["user"].Value;
                        ircLine.Host              = m.Groups["host"].Value;
                        ircLine.ServerHost        = m.Groups["server"].Value;
                        ircLine.IrcCommand        = m.Groups["irccommand"].Value;
                        ircLine.IrcCommandArgs    = m.Groups["ircommandargs"].Value.Split(' ');
                        ircLine.IrcCommandArgsRaw = m.Groups["ircommandargs"].Value;
                        ircLine.Trail             = m.Groups["trail"].Value;

                        if (!string.IsNullOrWhiteSpace(ircLine.Trail))
                        {
                            r = new Regex(@"^[ ]*(?<fullcommand>(?<command>![^ ]+)( (?<args>.*))?)$", (RegexOptions.ExplicitCapture | RegexOptions.Compiled | RegexOptions.IgnoreCase));
                            m = r.Match(ircLine.Trail);
                            if (m.Success)
                            {
                                ircLine.FullCommand = m.Groups["fullcommand"].Value;
                                ircLine.Command     = m.Groups["command"].Value;
                                ircLine.Args        = m.Groups["args"].Value;
                            }
                        }

                        foreach (ProcessIrcLineDelegate ircLineProcessor in ProcessIrcLine.GetInvocationList())
                        {
                            try {
                                ircLineProcessor(this, ircLine);
                            } catch (Exception e) {
                                logger.Error(e);
                            }
                        }

                        lastLine = ircLine;
                        if (!string.IsNullOrWhiteSpace(ircLine.Command))
                        {
                            Enqueue(ircLine);
                            continue;
                        }

                        // Handles responses to WHO <nick> %na requests
                        if (HandleUserAuthResponse(ircLine))
                        {
                            continue;
                        }
                    }

                    // Create or update tracking rows in the DB for users in each channel
                    if (HandleUserBootstrapLine(line))
                    {
                        continue;
                    }
                } catch (MySqlException e) {
                    logger.Error(e);
                } catch (Exception e) {
                    logger.Error(e);
                }
            }
        }
Exemplo n.º 23
0
        public override void HandleCommand(IrcLine line, Nick nick, Channel channel)
        {
            try {
                if (!isOp(nick))
                {
                    conn.SendPrivmsg(nick.Name, String.Format("Sorry, {0}, but that command doesn't exist. Try !help.", nick.DisplayName));
                    return;
                }

                string target = nick.Name;
                if (channel != null && channel.AllowCommandsInChannel)
                {
                    target = channel.Name;
                }

                Regex r = new Regex(@"^!botban ?");
                line.Args = r.Replace(line.Args, "").Trim();
                if (line.Args.Length <= 0)   // Whaaaat??
                {
                    conn.SendPrivmsg(target, "Usage(1): !botban <add|remove> <nick|$a:account|mask:*!*@*.*> [ban message]");
                }
                else
                {
                    string[] argBits = line.Args.Split(" ".ToCharArray(), 3);
                    if (argBits.Length > 3)
                    {
                        conn.SendPrivmsg(target, "Usage(2): !botban <add|remove> <nick|$a:account|mask:*!*@*.*> [ban message]");
                        return;
                    }

                    string banMessage = null;
                    if (argBits.Length == 3)
                    {
                        banMessage = argBits[2];
                    }

                    string mode = argBits[0];
                    switch (mode)
                    {
                    case "add":
                    case "remove":
                        break;

                    //                        case "remove":
                    //                            if (banMessage != null) {
                    //                                conn.SendPrivmsg(target, "Ban message can't be set when removing a ban, you DERP!");
                    //                                return;
                    //                            }
                    //                            break;

                    default:
                        conn.SendPrivmsg(target, "Usage(3): !botban <add|remove> <nick|$a:account|mask:*!*@*.*> [ban message]");
                        break;
                    }

                    argBits = argBits[1].Split(':');
                    string search     = argBits[0];
                    string searchType = "nick";
                    if (argBits.Length > 2 || (argBits.Length == 2 && argBits[0] != "$a" && argBits[0] != "mask"))
                    {
                        conn.SendPrivmsg(target, "Usage(4): !botban <add|remove> <nick|$a:account|mask:*!*@*.*> [ban message]");
                        return;
                    }
                    if (argBits.Length == 2)
                    {
                        if (argBits[0] == "mask")
                        {
                            search     = argBits[1];
                            searchType = "mask";
                        }
                        else if (argBits[0] == "$a")
                        {
                            search     = argBits[1];
                            searchType = "account";
                        }
                        else
                        {
                            conn.SendPrivmsg(target, "Usage(5): !botban <add|remove> <nick|$a:account|mask:*!*@*.*> [ban message]");
                            return;
                        }
                    }

                    Ban     ircBan     = null;
                    Nick    ircNick    = null;
                    Account ircAccount = null;
                    switch (searchType)
                    {
                    case "nick":
                        ircNick = Nick.Fetch(search, conn.Server);
                        if (ircNick == null)
                        {
                            conn.SendPrivmsg(target, String.Format("{0}{2}{1}: Nick `{3}` does not exist in the database.", "\x02", "\x0f", nick.DisplayName, search));
                            return;
                        }
                        ircAccount = ircNick.Account;
                        ircBan     = Ban.Fetch(ircNick, ircAccount);
                        break;

                    case "account":
                        ircAccount = Account.Fetch(search, conn.Server);
                        if (ircAccount == null)
                        {
                            conn.SendPrivmsg(target, String.Format("{0}{2}{1}: Account `{3}` does not exist in the database.", "\x02", "\x0f", nick.DisplayName, search));
                            return;
                        }
                        ircNick = ircAccount.MostRecentNick;
                        ircBan  = Ban.Fetch(ircNick, ircAccount);
                        break;

                    case "mask":
                        ircBan = Ban.Fetch(conn.Server, search);

                        if (ircBan != null)
                        {
                            if (ircBan.Nick != null)
                            {
                                ircNick = ircBan.Nick;
                            }
                            if (ircBan.Account != null)
                            {
                                ircAccount = ircBan.Account;
                            }
                        }

                        break;

                    default:
                        conn.SendPrivmsg(target, "This what you're seeing here is a big fat error happening. Poke TwoWholeWorms.");
                        break;
                    }

                    if (ircBan == null)
                    {
                        if (mode == "remove")
                        {
                            conn.SendPrivmsg(target, String.Format("{0}{2}{1}: {3} `{4}` is not currently banned.", "\x02", "\x0f", nick.DisplayName, searchType.Capitalise(), search));
                            return;
                        }
                        ircBan = new Ban();
                    }
                    else if (mode == "add" && ircBan.IsMugshotBan)
                    {
                        Account banner = ircBan.BannerAccount;
                        if (banner != null)
                        {
                            conn.SendPrivmsg(target, String.Format("{0}{2}{1}: {3} `{4}` was already banned from accessing {8} by $a:{5} on {6}: {7}", "\x02", "\x0f", nick.DisplayName, searchType.Capitalise(), search, banner.Name, ircBan.CreatedAt.ToString("u"), (ircBan.BanMessage ?? "No message"), conn.Server.BotNick));
                        }
                        else
                        {
                            conn.SendPrivmsg(target, String.Format("{0}{2}{1}: {3} `{4}` was already banned from accessing {7} on {5}: {6}", "\x02", "\x0f", nick.DisplayName, searchType.Capitalise(), search, ircBan.CreatedAt.ToString("u"), (ircBan.BanMessage ?? "No message"), conn.Server.BotNick));
                        }
                        return;
                    }

                    if (ircNick == null && ircAccount != null && ircAccount.MostRecentNick != null)
                    {
                        ircNick = ircAccount.MostRecentNick;
                    }
                    if (ircAccount == null && ircNick != null && ircNick.Account != null)
                    {
                        ircAccount = ircNick.Account;
                    }

                    ircBan.Server       = conn.Server;
                    ircBan.Nick         = ircNick;
                    ircBan.Account      = ircAccount;
                    ircBan.IsMugshotBan = (mode == "add");
                    if (ircBan.IsActive && ircBan.Channel == null)
                    {
                        ircBan.IsActive = false;
                    }
                    if (mode == "add")
                    {
                        ircBan.BanMessage      = banMessage;
                        ircBan.BannerAccount   = nick.Account;
                        ircBan.UnbanMessage    = null;
                        ircBan.UnbannerAccount = null;
                        ircBan.UnbannedAt      = null;
                    }
                    else if (mode == "remove")
                    {
                        ircBan.UnbanMessage    = banMessage;
                        ircBan.UnbannerAccount = nick.Account;
                        ircBan.UnbannedAt      = DateTime.Now;
                    }
                    if (searchType == "mask")
                    {
                        ircBan.Mask = search;
                    }
                    ircBan.Save();

                    if (mode == "add")
                    {
                        conn.SendPrivmsg(target, String.Format("{0}{2}{1}: {3} `{4}` has been banned from accessing {5} features, and their existing mugshot has been hidden from the site.", "\x02", "\x0f", nick.DisplayName, searchType.Capitalise(), search, conn.Server.BotNick));
                    }
                    else
                    {
                        conn.SendPrivmsg(target, String.Format("{0}{2}{1}: {3} `{4}` ban on accessing {5} has been deactivated.", "\x02", "\x0f", nick.DisplayName, searchType.Capitalise(), search, conn.Server.BotNick));
                    }
                    return;
                }
            } catch (Exception e) {
                logger.Error(e);
                conn.SendPrivmsg(nick.Name, "Aieee! The bees! The BEEES! They're chasing me away!!! (Get TwoWholeWorms!)");
            }
        }
Exemplo n.º 24
0
 /// <summary>
 /// Initializes a new instance of the LinksBeginEventArgs class.
 /// </summary>
 /// <param name="line">The line, what raised the event.</param>
 public LinksBeginEventArgs(IrcLine line)
     : base(line)
 {
 }
Exemplo n.º 25
0
        public override void HandleCommand(IrcLine line, Nick nick, Channel channel)
        {
            try {
                if (!isOp(nick))
                {
                    conn.SendPrivmsg(nick.Name, String.Format("Sorry, {0}, but that command doesn't exist. Try !help.", nick.DisplayName));
                    return;
                }

                string target = nick.Name;
                if (channel != null && channel.AllowCommandsInChannel)
                {
                    target = channel.Name;
                }

                Regex r = new Regex(@"^!searchlog ?");
                line.Args = r.Replace(line.Args, "").Trim();
                if (line.Args.Length <= 0)   // Whaaaat??
                {
                    conn.SendPrivmsg(target, String.Format("Usage(1): !searchlog <search> - search examples: id:1 nick:{0} $a:{1}, #lumbricus, \"Magnus Magnusson\"", nick.DisplayName, nick.Account.Name));
                }
                else
                {
                    string[] argBits;
                    string   search     = line.Args;
                    string   searchType = "string";
                    long     searchId   = 0;

                    if (line.Args.StartsWith("id:"))
                    {
                        if (line.Args.Contains(" "))
                        {
                            conn.SendPrivmsg(target, String.Format("\x02{0}\x0f: ID searches cannot contain spaces.", nick.DisplayName));
                            return;
                        }
                        argBits = line.Args.Split(':');
                        search  = argBits[1];
                        Int64.TryParse(search, out searchId);
                        if (searchId < 1)
                        {
                            conn.SendPrivmsg(target, String.Format("\x02{0}\x0f: ID must be > 0.", nick.DisplayName));
                            return;
                        }
                        searchType = "id";
                    }

                    if (line.Args.StartsWith("nick:"))
                    {
                        if (line.Args.Contains(" "))
                        {
                            conn.SendPrivmsg(target, String.Format("\x02{0}\x0f: Nick searches cannot contain spaces.", nick.DisplayName));
                            return;
                        }
                        argBits    = line.Args.Split(':');
                        search     = argBits[1];
                        searchType = "nick";
                    }

                    if (line.Args.StartsWith("$a:"))
                    {
                        if (line.Args.Contains(" "))
                        {
                            conn.SendPrivmsg(target, String.Format("\x02{0}\x0f: Account searches cannot contain spaces.", nick.DisplayName));
                            return;
                        }
                        argBits    = line.Args.Split(':');
                        search     = argBits[1];
                        searchType = "account";
                    }

                    if (line.Args.StartsWith("#"))
                    {
                        if (line.Args.Contains(" "))
                        {
                            conn.SendPrivmsg(target, String.Format("\x02{0}\x0f: Channel searches cannot contain spaces.", nick.DisplayName));
                            return;
                        }
                        search     = line.Args;
                        searchType = "channel";
                    }

                    if (searchType == "string")
                    {
                        if (!line.Args.StartsWith("\"") || !line.Args.EndsWith("\"") || line.Args.Count(f => f == '\"') != 2)
                        {
                            conn.SendPrivmsg(target, String.Format("Usage(2): !searchlog <search> - search examples: id:1 nick:{0} $a:{1}, #lumbricus, \"Magnus Magnusson\"", nick.DisplayName, nick.Account.Name));
                            return;
                        }

                        if (line.Args.Trim().Replace("%", "").Length < 7)
                        {
                            conn.SendPrivmsg(target, String.Format("\x02{0}\x0f: Text searches must be at least 5 characters long, not including wildcards.", nick.DisplayName));
                            return;
                        }

                        search = line.Args.Substring(1, (line.Args.Length - 2));
                    }

                    Log ignoreLogLine = Log.Fetch(nick);

                    long    totalLines    = 0;
                    Log     logLine       = null;
                    Account searchAccount = null;
                    Nick    searchNick    = null;
                    Channel searchChannel = null;
                    switch (searchType)
                    {
                    case "id":
                        logLine    = Log.Fetch(searchId);
                        totalLines = (logLine == null ? 0 : 1);
                        if (logLine != null)
                        {
                            if (logLine.Channel != null)
                            {
                                searchChannel = Channel.Fetch(logLine.Channel.Id);
                            }
                        }
                        else
                        {
                            conn.SendPrivmsg(target, String.Format("\x02{0}\x0f: Log entry id `{1}` does not exist.", nick.DisplayName, searchId));
                            return;
                        }
                        break;

                    case "string":
                        if (search.Contains("\""))
                        {
                            search = search.Replace("\"", "");
                        }
                        totalLines = Log.FetchTotal(search);
                        logLine    = Log.Fetch(search, ignoreLogLine, channel);
                        if (logLine != null)
                        {
                            if (logLine.Channel != null)
                            {
                                searchChannel = Channel.Fetch(logLine.Channel.Id);
                            }
                        }
                        else
                        {
                            conn.SendPrivmsg(target, String.Format("\x02{0}\x0f: No results for search `{1}`.", nick.DisplayName, search));
                            return;
                        }
                        break;

                    case "account":
                        searchAccount = Account.Fetch(search.ToLower(), conn.Server);
                        if (searchAccount == null)
                        {
                            conn.SendPrivmsg(target, String.Format("\x02{0}\x0f: There is no account `{1}` in the database", nick.DisplayName, search));
                            return;
                        }
                        if (searchAccount.MostRecentNick != null)
                        {
                            searchNick = searchAccount.MostRecentNick;
                            totalLines = Log.FetchTotal(searchNick);
                            logLine    = Log.Fetch(searchNick, ignoreLogLine, channel);
                        }
                        else
                        {
                            totalLines = Log.FetchTotal(searchAccount);
                            logLine    = Log.Fetch(searchAccount, ignoreLogLine, channel);
                        }
                        if (logLine != null)
                        {
                            if (logLine.Channel != null)
                            {
                                searchChannel = Channel.Fetch(logLine.Channel.Id);
                            }
                        }
                        else
                        {
                            conn.SendPrivmsg(target, String.Format("\x02{0}\x0f: $a:{1} is not in the log (?!)", nick.DisplayName, searchAccount.Name));
                            return;
                        }
                        break;

                    case "nick":
                        searchNick = Nick.Fetch(search.ToLower(), conn.Server);
                        if (searchNick == null)
                        {
                            conn.SendPrivmsg(target, String.Format("\x02{0}\x0f: There is no nick `{1}` in the database", nick.DisplayName, search));
                            return;
                        }
                        if (searchNick.Account != null)
                        {
                            searchAccount = searchNick.Account;
                        }
                        totalLines = Log.FetchTotal(searchNick);
                        logLine    = Log.Fetch(searchNick, ignoreLogLine, channel);
                        if (logLine != null)
                        {
                            if (logLine.Channel != null)
                            {
                                searchChannel = Channel.Fetch(logLine.Channel.Id);
                            }
                        }
                        else
                        {
                            conn.SendPrivmsg(target, String.Format("\x02{0}\x0f: nick:{1} is not in the log (?!)", nick.DisplayName, searchNick.DisplayName));
                            return;
                        }
                        break;

                    case "channel":
                        searchChannel = Channel.Fetch(search.ToLower(), conn.Server);
                        if (searchChannel == null)
                        {
                            conn.SendPrivmsg(target, String.Format("\x02{0}\x0f: There is no channel `{1}` in the database", nick.DisplayName, search));
                            return;
                        }
                        totalLines = Log.FetchTotal(searchChannel);
                        logLine    = Log.Fetch(searchChannel, ignoreLogLine);
                        if (logLine == null)
                        {
                            conn.SendPrivmsg(target, String.Format("\x02{0}\x0f: {1} is not in the log (?!)", nick.DisplayName, searchChannel.Name));
                            return;
                        }
                        break;
                    }

                    if (logLine == null)
                    {
                        conn.SendPrivmsg(target, String.Format("\x02{0}\x0f: This message should never appear, what the HELL did you DO to me?! D:", nick.DisplayName));
                        return;
                    }

                    string response = totalLines + " found, latest: " + (searchChannel != null ? searchChannel.Name : conn.Server.BotNick) + " [" + logLine.LoggedAt.ToString("u") + "] " + logLine.Line;
                    conn.SendPrivmsg(target, response);
                }
            } catch (Exception e) {
                logger.Error(e);
                conn.SendPrivmsg(nick.Name, "Oof… My spleen…! I can't do that right now. :(");
            }
        }
Exemplo n.º 26
0
 /// <summary>
 /// Initializes a new instance of the ChannelListEndEventArgs class.
 /// </summary>
 /// <param name="line">The line, that marks the channel list block end.</param>
 /// <param name="channellistLines">All lines of the channel list block.</param>
 public ChannelListEndEventArgs(IrcLine line, IrcLine[] channellistLines)
     : base(line)
 {
     channelListLines = channellistLines;
 }
Exemplo n.º 27
0
 /// <summary>
 /// Initializes a new instance of the InfoBeginEventArgs class.
 /// </summary>
 /// <param name="line">The line, what raised the event.</param>
 public InfoBeginEventArgs(IrcLine line)
     : base(line)
 {
 }
Exemplo n.º 28
0
 /// <summary>
 /// Initializes a new instance of the MotdEndEventArgs class.
 /// </summary>
 /// <param name="line">The line, that marks the motd end.</param>
 /// <param name="motdLines">All lines of the motd.</param>
 public MotdEndEventArgs(IrcLine line, IrcLine[] motdLines)
     : base(line)
 {
     this.motdLines = motdLines;
 }
Exemplo n.º 29
0
        void Handle354(IrcLine line)
        {
            if (line.AccountName == "0")
            {
                if (queue.ContainsKey(line.Nick))
                {
                    SendPrivmsg(line.Nick, "You must be identified with nickserv to use this command.");
                    queue.Remove(line.Nick);
                }
            }
            else
            {
                Channel channel = Server.ConnectedChannels.FirstOrDefault(x => x.Name == line.IrcCommandArgsRaw);
                Nick    ircNick = FetchIrcNick(line.Nick);
                if (ircNick == null)
                {
                    if (queue.ContainsKey(line.Nick))
                    {
                        queue.Remove(line.Nick);
                    }
                    throw new Exception(String.Format("Unable to fetch or create nick `{0}`", line.Nick));
                }

                bool found = false;
                foreach (Channel c in Server.ConnectedChannels)
                {
                    if (c.ConnectedNicks.Contains(ircNick) || ircNick.ConnectedChannels.Contains(c))
                    {
                        found = true;
                        break;
                    }
                }
                if (!found)
                {
                    List <string> channels = new List <string>();
                    foreach (Channel c in Server.ConnectedChannels)
                    {
                        channels.Add(c.Name);
                    }
                    if (queue.ContainsKey(line.Nick))
                    {
                        queue.Remove(line.Nick);
                    }
                    logger.Info("Ignoring {0} because they're not in at least one of the following channels: {1}", line.Nick, string.Join(", ", channels));
                    return;
                }

                Account ircAccount = Account.FetchOrCreate(line.AccountName, Server);
                if (ircAccount == null)
                {
                    if (queue.ContainsKey(line.Nick))
                    {
                        queue.Remove(line.Nick);
                    }
                    throw new Exception(String.Format("Unable to fetch or create account `{0}`", line.AccountName));
                }

                if (ircNick.Account == null)
                {
                    ircNick.Account   = ircAccount;
                    ircNick.AccountId = ircAccount.Id;
                    LumbricusContext.db.SaveChanges();
                }
                else if (ircNick.Account.Id != ircAccount.Id && queue.ContainsKey(line.Nick))
                {
                    SendPrivmsg(line.Nick, "Sorry, but nick `{0}` is not registered to your services account. Please log in on that account and try again.");
                    SendPrivmsg("TwoWholeWorms", String.Format("Services account `{0}` attempted to access features for nick `{1}` but that nick is registered to services account `{2}`.", ircAccount.Name, ircNick.Name, ircNick.Account.Name));
                    if (queue.ContainsKey(line.Nick))
                    {
                        queue.Remove(line.Nick);
                    }
                    return;
                }

                Seen.Update(Server, ircNick, ircAccount, channel);

                if (queue.ContainsKey(line.Nick))
                {
                    if (CheckBans(ircNick, ircAccount, line.User, line.Host))
                    {
                        if (queue.ContainsKey(line.Nick))
                        {
                            queue.Remove(line.Nick);
                        }
                        return;
                    }

                    foreach (IrcLine queuedLine in queue.Single(x => x.Key == line.Nick).Value)
                    {
                        if (!string.IsNullOrWhiteSpace(queuedLine.Command))
                        {
                            if (Commands.ContainsKey(queuedLine.Command))
                            {
                                AbstractCommand command = Commands.Single(x => x.Key == queuedLine.Command).Value;
                                if (command == null)
                                {
                                    SendPrivmsg(queuedLine.Nick, String.Format("Sorry, {0}, but I'm unable to do that at this time. Poke TwoWholeWorms to fix me. :(", queuedLine.Nick));
                                    logger.Error("Command `{0}` is registered with a null handler!", queuedLine.Command);
                                }
                                else
                                {
                                    command.HandleCommand(queuedLine, ircNick, channel);
                                }
                            }
                            else
                            {
                                SendPrivmsg(queuedLine.Nick, String.Format("Sorry, {0}, but that command does not exist. Try !help.", queuedLine.Nick));
                            }
                        }

//                            switch (command) {
//                                case "setmugshot":
//                                    Command.HandleSetMugshot(ircNick, args, this);
//                                    break;
//
//                                case "clearmugshot":
//                                    Command.HandleClearMugshot(ircNick, args, this);
//                                    break;
//
//                                case "setinfo":
//                                    Command.HandleSetInfo(ircNick, args, this);
//                                    break;
//
//                                case "clearinfo":
//                                    Command.HandleClearInfo(ircNick, args, this);
//                                    break;
//
//                                case "seen":
//                                    Command.HandleSeen(ircNick, args, this, c);
//                                    break;
//
//                                case "help":
//                                    Command.HandleHelp(ircNick, args, this, c);
//                                    break;
//
//                                case "baninfo":
//                                    Command.HandleBanInfo(ircNick, args, this, c);
//                                    break;
//
//                                case "botban":
//                                    Command.HandleBotBan(ircNick, args, this, c);
//                                    break;
//
//                                case "searchlog":
//                                    Command.HandleSearchLog(ircNick, args, this, c);
//                                    break;
//
//                                case "restart":
//                                    Command.HandleUnwrittenAdminCommand(ircNick, args, this, c);
//                                    break;
//
                        if (channel != null && !channel.AllowCommandsInChannel && queuedLine.IrcCommandArgsRaw != Server.BotNick)
                        {
                            SendPrivmsg(line.Nick, "Also, please try to only interact with me directly through this window. Bot commands in the channel are against channel policy, and some people get really annoyed about it. :(");
                        }
                    }
                    queue.Remove(line.Nick);
                }
            }
        }
Exemplo n.º 30
0
        public override void HandleCommand(IrcLine line, Nick nick, Channel channel)
        {
            try {
                if (nick.Account == null || !isOp(nick))
                {
                    conn.SendPrivmsg(nick.Name, String.Format("Sorry, {0}, but the !seen command doesn't exist. Try !help.", nick.DisplayName));
                    return;
                }

                string target = nick.Name;
                if (channel != null && channel.AllowCommandsInChannel)
                {
                    target = channel.Name;
                }

                Regex r = new Regex(@"^!seen ?");
                line.Args = r.Replace(line.Args, "").Trim();
                if (line.Args.Length <= 0)   // Whaaaat??
                {
                    conn.SendPrivmsg(target, String.Format("Usage: !seen <search> - use $a:account to search for an account (eg, !seen $a:{0})", nick.Account.Name));
                }
                else
                {
                    string[] argBits = line.Args.Split(' ');
                    if (argBits.Length > 1)
                    {
                        conn.SendPrivmsg(target, String.Format("Usage: !seen <search> - use $a:account to search for an account (eg, !seen $a:{0})", nick.Account.Name));
                        return;
                    }

                    argBits = argBits[0].Split(':');
                    string search     = argBits[0];
                    string searchType = "nick";
                    if (argBits.Length == 2)
                    {
                        if (argBits[0] != "$a")
                        {
                            conn.SendPrivmsg(target, String.Format("Usage: !seen <search> - use $a:account to search for an account (eg, !seen $a:{0})", nick.Account.Name));
                            return;
                        }
                        search     = argBits[1];
                        searchType = "account";
                    }

                    Nick      ircNick    = null;
                    Account   ircAccount = null;
                    Channel   ircChannel = null;
                    SeenModel ircSeen    = null;
                    if (searchType == "account")
                    {
                        ircAccount = Account.Fetch(search.ToLower(), conn.Server);
                        if (ircAccount != null)
                        {
                            ircSeen = SeenModel.FetchByAccountId(ircAccount.Id);
                            if (ircSeen != null)
                            {
                                if (ircSeen.Nick != null)
                                {
                                    ircNick = ircSeen.Nick;
                                }
                                if (ircSeen.Channel != null)
                                {
                                    ircChannel = ircSeen.Channel;
                                }
                            }
                        }
                    }
                    else
                    {
                        ircNick = Nick.Fetch(search.ToLower(), conn.Server);
                        if (ircNick != null)
                        {
                            ircSeen = SeenModel.FetchByNickId(ircNick.Id);
                            if (ircSeen != null)
                            {
                                if (ircSeen.Account != null)
                                {
                                    ircAccount = ircSeen.Account;
                                }
                                if (ircSeen.Channel != null)
                                {
                                    ircChannel = ircSeen.Channel;
                                }
                            }
                        }
                    }

                    if (ircSeen == null)
                    {
                        conn.SendPrivmsg(target, String.Format("There is no seen data in the database about {0} `{1}`.", searchType, search));
                    }
                    else
                    {
                        string seenNick    = (ircNick != null ? ircNick.DisplayName : "Unknown Nick");
                        string seenAccount = (ircAccount != null ? ircAccount.Name : "Unknown Account");
                        string seenChannel = (ircChannel != null ? ircChannel.Name : "a private query window");

                        conn.SendPrivmsg(target, String.Format("{1}{0}{2}{1} ($a:{0}{3}{1}): First seen {0}{4}{1}, last seen {0}{5}{1} in {1}{0}{6}{1}.", "\x02", "\x0f", seenNick, seenAccount, ircSeen.FirstSeenAt.ToString("u"), ircSeen.LastSeenAt.ToString("u"), seenChannel));
                    }
                }
            } catch (Exception e) {
                logger.Error(e);
                conn.SendPrivmsg(nick.Name, "Oof… My spleen…! I can't do that right now. :(");
            }
        }
Exemplo n.º 31
0
 /// <summary>
 /// Initializes a new instance of the WhoEndEventArgs class.
 /// </summary>
 /// <param name="line">The line, that marks the who reply end.</param>
 /// <param name="whoLines">All lines of the who reply.</param>
 public WhoEndEventArgs(IrcLine line, WhoLine[] whoLines)
     : base(line)
 {
     this.whoLines = whoLines;
 }
Exemplo n.º 32
0
        // This needs to be updated to properly parse mode lines.
        public void DoTrackBanPlugin(IrcConnection conn, IrcLine line)
        {
            Regex r = new Regex(@"^(?<banchannel>#[^ ]+) (?<bantype>[\+\-]b) (?<banmask>.*)$", RegexOptions.ExplicitCapture);
            Match m = r.Match(line.IrcCommandArgsRaw);

            if (m.Success)
            {
                string banChannel = m.Groups["banchannel"].Value;
                string banMask    = m.Groups["banmask"].Value;
                string banType    = m.Groups["bantype"].Value;

                Nick    banner  = conn.Server.ConnectedNicks.FirstOrDefault(x => x.Name == line.Nick.ToLower());
                Channel channel = conn.Server.ConnectedChannels.FirstOrDefault(x => x.Name == banChannel.ToLower());
                Ban     ban     = Ban.Fetch(channel, line.FullHost);
                if (ban == null)
                {
                    if (banType == "-b")
                    {
                        return;
                    }
                    ban = new Ban();
                    if (banMask.StartsWith("$a:"))
                    {
                        string[] maskBits      = banMask.Split(" ".ToCharArray(), 2);
                        Account  bannedAccount = Account.Fetch(maskBits[1], conn.Server);
                        if (bannedAccount != null)
                        {
                            ban.Account = bannedAccount;
                        }
                    }
                }
                else
                {
                    if (banType == "+b" && ban.IsActive)
                    {
                        // Don't overwrite an existing ban if it's still active
                        return;
                    }
                    if (banType == "+b" && ban.UnbannerAccount != null)
                    {
                        // Create a new ban if they've been unbanned
                        ban = Ban.Create(conn.Server);
                    }
                }

                if (banType == "-b")
                {
                    ban.IsActive   = false;
                    ban.UnbannedAt = DateTime.Now;
                }
                ban.Server = conn.Server;
                if (banner.Account != null)
                {
                    ban.BannerAccount = banner.Account;
                }
                ban.Channel = channel;
                ban.Mask    = banMask;

                LumbricusContext.db.SaveChanges();
            }
        }
Exemplo n.º 33
0
 /// <summary>
 /// Initializes a new instance of the ChannelListBeginEventArgs class.
 /// </summary>
 /// <param name="line">The line, what raised the event.</param>
 public ChannelListBeginEventArgs(IrcLine line)
     : base(line)
 {
 }
Exemplo n.º 34
0
        /// <summary>
        /// Custom code for checking whether a user has registered with NickServ. Ugly, but it works.
        /// </summary>
        private void ProcessFormattedLine(IrcLine line)
        {
            //TODO: where's the nickserv code gone?
            // This IRC server does not have a NickServ service.

            /*if (line.Command.Equals("401") && ircInterface.HasNickservCall && line.FinalArgument.ToLower().Contains("nickserv: no such nick"))
             * {
             *      ircInterface.DisableNickservCalls();
             *      // Proess reply to WHOIS call.
             * }*/
            if (!ignoredCommands.Contains(line.Command))
            {
                // TODO: handle formatted lines
                switch (line.Command)
                {
                case "001":                         // RPL_WELCOME
                case "002":                         // RPL_YOURHOST
                    Logger.Log(this, $"{line.FinalArgument}", LogLevel.Irc);
                    break;

                case "003":                         // RPL_CREATED
                    Logger.Log(this, $"{line.Sender}: {line.FinalArgument}", LogLevel.Irc);
                    break;

                case "332":                         // RPL_TOPIC
                    Logger.Log(this, $"Topic for {line.Arguments[1]}: {line.FinalArgument}", LogLevel.Irc);
                    break;

                case "333":                         // Ignore names list
                case "366":
                    break;

                case "253":                         // RPL_LUSERUNKNOWN
                    break;

                case "375":                         // RPL_MOTDSTART
                case "376":                         // RPL_ENDOFMOTD
                case "372":                         // RPL_MOTD
                case "451":                         // ERR_NOTREGISTERED
                    Logger.Log(this, $"{line.FinalArgument}", LogLevel.Irc);
                    break;

                case "MODE":
                    // TODO: Figure out the difference between these two and document it. Probably channel/user
                    if (line.FinalArgument != null)
                    {
                        Logger.Log(this, $"{line.Sender} sets mode {line.FinalArgument} for {line.Arguments[0]}", LogLevel.Irc);
                    }
                    else
                    {
                        Logger.Log(this, $"{line.Sender} sets mode {line.Arguments[1]} for {line.Arguments[0]}");
                    }
                    break;

                default:
                    Debugger.Break();
                    Logger.Log(this, line.ToString(), LogLevel.Irc);
                    break;
                }
            }
        }
Exemplo n.º 35
0
 abstract public void HandleCommand(IrcLine line, Nick nick, Channel channel);
Exemplo n.º 36
0
        public override void HandleCommand(IrcLine line, Nick nick, Channel channel)
        {
            try {
                if (!isOp(nick))
                {
                    conn.SendPrivmsg(nick.Name, String.Format("Sorry, {0}, but that command doesn't exist. Try !help.", nick.DisplayName));
                    return;
                }

                string target = nick.Name;
                if (channel != null && channel.AllowCommandsInChannel)
                {
                    target = channel.Name;
                }

                Regex r = new Regex(@"^!baninfo ?");
                line.Args = r.Replace(line.Args, "").Trim();
                if (line.Args.Length <= 0)   // Whaaaat??
                {
                    conn.SendPrivmsg(target, String.Format("Usage(1): !baninfo <search> - Prefix search with $a: to search for an account, or mask: to search for a ban string, eg !baninfo $a:{0} !baninfo mask:*!*@*.no", nick.Account.Name));
                }
                else
                {
                    string[] argBits = line.Args.Split(' ');
                    if (argBits.Length > 1)
                    {
                        conn.SendPrivmsg(target, String.Format("Usage(2): !baninfo <search> - Prefix search with $a: to search for an account, or mask: to search for a ban string, eg !baninfo $a:{0} !baninfo mask:*!*@*.no", nick.Account.Name));
                        return;
                    }

                    argBits = argBits[0].Split(':');
                    string search     = argBits[0];
                    string searchType = "nick";
                    if (argBits.Length > 2 || (argBits.Length == 2 && argBits[0] != "$a" && argBits[0] != "mask"))
                    {
                        conn.SendPrivmsg(target, String.Format("Usage(3): !baninfo <search> - Prefix search with $a: to search for an account, or mask: to search for a ban string, eg !baninfo $a:{0} !baninfo mask:*!*@*.no", nick.Account.Name));
                        return;
                    }
                    if (argBits.Length == 2)
                    {
                        if (argBits[0] == "mask")
                        {
                            search     = argBits[1];
                            searchType = "mask";
                        }
                        else if (argBits[0] == "$a")
                        {
                            search     = argBits[1];
                            searchType = "account";
                        }
                        else
                        {
                            conn.SendPrivmsg(target, String.Format("Usage(4): !baninfo <search> - Prefix search with $a: to search for an account, or mask: to search for a ban string, eg !baninfo $a:{0} !baninfo mask:*!*@*.no", nick.Account.Name));
                            return;
                        }
                    }

                    Account    bannedAccount = null;
                    Nick       bannedNick    = null;
                    List <Ban> ircBans       = new List <Ban>();
                    switch (searchType)
                    {
                    case "account":
                        bannedAccount = Account.Fetch(search.ToLower(), conn.Server);
                        if (bannedAccount == null)
                        {
                            conn.SendPrivmsg(target, String.Format("There is no account `{0}` in the database", search));
                            return;
                        }
                        bannedNick         = bannedAccount.MostRecentNick;
                        bannedNick.Account = bannedAccount;
                        ircBans            = Ban.Fetch(bannedNick).ToList();
                        break;

                    case "nick":
                        bannedNick = Nick.Fetch(search.ToLower(), conn.Server);
                        if (bannedNick == null)
                        {
                            conn.SendPrivmsg(target, String.Format("There is no nick `{0}` in the database", search));
                            return;
                        }
                        bannedAccount = bannedNick.Account;
                        ircBans       = Ban.Fetch(bannedNick).ToList();
                        break;

                    case "mask":
                        Ban ircBan = Ban.Fetch(conn.Server, search);
                        if (ircBan == null)
                        {
                            conn.SendPrivmsg(target, String.Format("There is no ban on mask `{0}` in the database", search));
                            return;
                        }
                        if (ircBan.Account != null)
                        {
                            bannedAccount = ircBan.Account;
                        }
                        if (ircBan.Nick != null)
                        {
                            bannedNick = ircBan.Nick;
                        }

                        if (bannedAccount != null && bannedNick == null && bannedAccount.MostRecentNick != null)
                        {
                            bannedNick = bannedAccount.MostRecentNick;
                        }
                        if (bannedNick != null && bannedAccount == null && bannedNick.Account != null)
                        {
                            bannedAccount = bannedNick.Account;
                        }

                        if (ircBan != null)
                        {
                            ircBans.Add(ircBan);
                        }
                        break;
                    }

                    if (ircBans.Count < 1)
                    {
                        if (bannedNick != null && bannedAccount != null)
                        {
                            conn.SendPrivmsg(target, String.Format("\x02{0}\x0f: {2} ($a:{1}) is not banned.", nick.DisplayName, bannedAccount.Name, bannedNick.DisplayName));
                        }
                        else if (bannedAccount != null)
                        {
                            conn.SendPrivmsg(target, String.Format("\x02{0}\x0f: $a:{1} is not banned.", nick.DisplayName, bannedAccount.Name));
                        }
                        else if (bannedNick != null)
                        {
                            conn.SendPrivmsg(target, String.Format("\x02{0}\x0f: `{1}` is not banned.", nick.DisplayName, bannedNick.DisplayName));
                        }
                        else
                        {
                            conn.SendPrivmsg(target, String.Format("\x02{0}\x0f: This message should never appear, what the HELL did you DO to me?! D:", nick.DisplayName));
                        }
                        return;
                    }

                    int i = 0;
                    foreach (Ban ircBan in ircBans)
                    {
                        string response = String.Format("\x02{0}\x0f: #{1}", nick.DisplayName, ircBan.Id);
                        if (searchType == "account")
                        {
                            response += " $a:" + bannedAccount.Name;
                            if (bannedNick != null)
                            {
                                response += " (" + bannedNick.DisplayName + ")";
                            }
                        }
                        else
                        {
                            response += " " + bannedNick.DisplayName;
                            if (bannedAccount != null)
                            {
                                response += " ($a:" + bannedAccount.Name + ")";
                            }
                        }

                        Channel bannedChannel = ircBan.Channel;
                        response += " " + conn.Server.BotNick + ((ircBan.IsMugshotBan || (bannedChannel != null && ircBan.IsActive)) ? ":" : ":un") + "banned";
                        if (bannedChannel != null)
                        {
                            response += " " + bannedChannel.Name + (!ircBan.IsActive ? ":un" : ":") + "banned";
                        }
                        response += " ban:[" + ircBan.CreatedAt.ToString("u");

                        if (!string.IsNullOrEmpty(ircBan.Mask))
                        {
                            response += " mask:" + ircBan.Mask;
                        }

                        Account cantankerousOp = ircBan.BannerAccount;
                        if (cantankerousOp != null)
                        {
                            if (cantankerousOp.MostRecentNick != null)
                            {
                                response += " op:" + cantankerousOp.MostRecentNick.DisplayName;
                            }
                            else
                            {
                                response += " op:$a:" + cantankerousOp.Name;
                            }
                        }
                        if (!string.IsNullOrWhiteSpace(ircBan.BanMessage))
                        {
                            response += " reason:" + ircBan.BanMessage;
                        }
                        response += "]";

                        if (ircBan.UnbannerAccount != null)
                        {
                            Account unbanner = ircBan.UnbannerAccount;

                            response += " unban:[" + ircBan.UnbannedAt.Value.ToString("u");
                            if (unbanner != null)
                            {
                                if (unbanner.MostRecentNick != null)
                                {
                                    response += " op:" + unbanner.MostRecentNick.DisplayName;
                                }
                                else
                                {
                                    response += " op:$a:" + unbanner.Name;
                                }
                            }
                            if (!string.IsNullOrWhiteSpace(ircBan.UnbanMessage))
                            {
                                response += " msg:" + ircBan.UnbanMessage;
                            }
                            response += "]";
                        }
                        if (i > 2)
                        {
                            Thread.Sleep(2000);        // Wait 2 secs between sending commands after 3, in case there's loads of bans to send
                        }
                        conn.SendPrivmsg(target, response);
                        i++;

                        if (i > 5)
                        {
                            break;
                        }
                    }
                }
            } catch (Exception e) {
                logger.Error(e);
                conn.SendPrivmsg(nick.Name, "Oof… My spleen…! I can't do that right now. :(");
            }
        }