bobbot-cvs Mailing List for BoB (Page 3)
Status: Alpha
Brought to you by:
iainmckay
You can subscribe to this list here.
2004 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
(17) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2005 |
Jan
(66) |
Feb
(31) |
Mar
|
Apr
|
May
|
Jun
|
Jul
(18) |
Aug
|
Sep
|
Oct
(6) |
Nov
|
Dec
|
From: Mr S. C. <mrs...@us...> - 2005-02-15 21:47:41
|
Update of /cvsroot/bobbot/Plugins/Sphere/LogManagement In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv28988/Sphere/LogManagement Added Files: LogEntry.cs LogManager.cs Log Message: - Ban System now registers bans made through scripts & .kick command. - Added <LogDatabase></LogDatabase> to the config. (should be added to bob.exe.config) - Removed test commands. - Added !pages to retrieve the list of pages from the server. (Will cause an exception if not running Sphere56) - Added '!page delete x' to delete a page from IRC. - Added LogManager, which saves particular information from the server and stores it for a week in a database. - Added 'Log...' PrivateCommands, '/msg bot log' for list. - Staff ChannelCommands now require 'StaffChan' property (set as true) on the channel to work. --- NEW FILE: LogManager.cs --- #region LGPL License /* Bastard of a Bot Library Copyright (C) 2004 Bastard of a Bot Team This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion using System; using System.Collections; using System.IO; using System.Text; using System.Xml; using Bot.Core; using Bot.Core.Irc; using Bot.Core.Irc.Messages; using Bot.Plugins.Sphere; using Bot.Plugins.Sphere.Messages; using Bot.Other.Sphere; using Bot.Other.Sphere.Messages; namespace Bot.Plugins.Sphere.LogManagement { public class LogManager { #region Private members private SphereConnection m_Server; private ArrayList m_LogEntries; private string m_LogDatabase; private string m_LastMessage; #endregion #region Public properties public LogEntry[] LogEntries { get { return (LogEntry[])m_LogEntries.ToArray(typeof(LogEntry)); } } #endregion #region Constructor public LogManager(SphereConnection server, string database) { m_Server = server; m_LogDatabase = database; m_LogEntries = new ArrayList(); if (!File.Exists(this.m_LogDatabase)) { Log.WriteLine("Sphere (LogManager)", "Database Not Found. Creating '{0}'", this.m_LogDatabase); StreamWriter newDb = File.CreateText(m_LogDatabase); newDb.WriteLine("<!-- Wireplay Lothlorien Log Manager Entries -->"); newDb.WriteLine("<!-- Database Created at {0}", DateTime.Now.ToString()); newDb.Close(); SaveDatabase(); } if (!LoadDatabase()) Log.WriteLine("Sphere (LogManager)", "Error occured whilst loading the Log Manager Database."); Log.WriteLine("Sphere (LogManager)", "{0} Log Entries Loaded", this.m_LogEntries.Count); SaveDatabase(); server.MessageReceived += new MessageReceivedEventHandler(OnMessageReceived); server.ClientPage += new ClientPageEventHandler(OnClientPage); server.RideLost += new RideLostEventHandler(OnRideLost); server.CustomEvent += new EventHandler(OnCustomEvent); } public string CreateMessage(LogEntry entry) { string handle = ""; if (entry.Handled) handle = String.Format("{0}(Handled by {1}){0}", "", entry.HandledBy); if (entry.Entry is ClientPageMessage) { ClientPageMessage msg = (ClientPageMessage)entry.Entry; return String.Format("{0} {1} Page from {2} [{3}] at {4}: {5}", entry.Time.ToString("[dd/MM/yy - hh:mm]"), handle, msg.Character, msg.Serial, msg.Position.ToString(), msg.Page); } else if (entry.Entry is HouseKillingMessage) { HouseKillingMessage msg = (HouseKillingMessage)entry.Entry; return String.Format("{0} House Killing. {1} Victim={2}(Name={3} Position={4}) Aggressor={5}(Name={6} Position={7})", entry.Time.ToString("[dd/MM/yy - hh:mm]"), handle, msg.VictimUid, msg.VictimName, msg.VictimP, msg.AggressorUid, msg.AggressorName, msg.AggressorP); } else if (entry.Entry is SkillNukeMessage) { SkillNukeMessage msg = (SkillNukeMessage)entry.Entry; return String.Format("{0} Skill Nuke. {1} Player={2}({3}). Skill={4} (Before Nuke: {5})", entry.Time.ToString("[dd/MM/yy - hh:mm]"), handle, msg.Name, msg.Account, msg.SkillName, msg.SkillBefore); } else if (entry.Entry is RideLostMessage) { RideLostMessage msg = (RideLostMessage)entry.Entry; return String.Format("{0} Ride Lost. {1} Type=0{2:x} Serial=0{3:x} Name={4}", entry.Time.ToString("[dd/MM/yy - hh:mm]"), handle, msg.ID, msg.Serial, msg.Name); } return null; } #endregion #region Event handlers private void OnMessageReceived(object sender, MessageReceivedEventArgs args) { m_LastMessage = args.Message; // // Clear up old messages. // for (int i = m_LogEntries.Count - 1; i >= 0; i -= 1) { if (((LogEntry)m_LogEntries[i]).DaysOld > 7) { m_LogEntries.RemoveAt(i); } } } private void OnClientPage(object sender, ClientPageEventArgs args) { m_LogEntries.Add(new LogEntry(args.Message, m_LastMessage)); } private void OnHouseKilling(object sender, HouseKillingEventArgs args) { m_LogEntries.Add(new LogEntry(args.Message, m_LastMessage)); } private void OnRideLost(object sender, RideLostEventArgs args) { m_LogEntries.Add(new LogEntry(args.Message, m_LastMessage)); } private void OnCustomEvent(object sender, EventArgs args) { if (args is HouseKillingEventArgs) OnHouseKilling(sender, (HouseKillingEventArgs) args); } #endregion #region Database Save/Load public bool LoadDatabase() { try { Log.WriteLine("Sphere (LogManager)", "Loading Log Entries from '{0}'...", this.m_LogDatabase); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(this.m_LogDatabase); XmlElement xmlRoot = xmlDoc.DocumentElement; XmlNodeList xmlList = xmlRoot.GetElementsByTagName("LogEntry"); if(xmlList.Count == 0) return true; foreach(XmlElement xmlElement in xmlList) { LogEntry entry = new LogEntry(); if(entry.Load(xmlElement)) m_LogEntries.Add(entry); } return true; } catch(Exception ex) { Log.WriteLine("Sphere (LogManager)", "Failed to load Log Entries file, reason: {0}", ex.ToString()); return false; } } public bool SaveDatabase() { try { Log.WriteLine("Sphere (LogManager)", "Writing database to '{0}'...", this.m_LogDatabase); XmlTextWriter xmlWriter = new XmlTextWriter(this.m_LogDatabase, Encoding.UTF8); xmlWriter.Formatting = Formatting.Indented; xmlWriter.Indentation = 4; XmlDocument xmlDoc = new XmlDocument(); XmlNode xmlRoot = xmlDoc.CreateNode(XmlNodeType.Element, "LogEntries", ""); xmlDoc.AppendChild(xmlRoot); foreach(LogEntry entry in m_LogEntries) { XmlElement xmlElement = xmlDoc.CreateElement("LogEntry"); xmlRoot.AppendChild(xmlElement); (entry).Save(xmlElement); } xmlDoc.Save(xmlWriter); xmlWriter.Flush(); xmlWriter.Close(); return true; } catch(Exception ex) { Log.WriteLine("Sphere (LogManager)", "Failed to write Log Entries file, reason: {0}", ex.Message); return false; } } #endregion #region Public methods public LogEntry[] GetEntriesOfType(Type type) { ArrayList list = new ArrayList(); foreach (LogEntry entry in LogEntries) { if (entry.Type == type) list.Add(entry); } return (LogEntry[])list.ToArray(typeof(LogEntry)); } public LogEntry[] GetEntriesBetweenTimes(DateTime from, DateTime to) { ArrayList list = new ArrayList(); foreach (LogEntry entry in LogEntries) { if (entry.Time >= from && entry.Time <= to) list.Add(entry); } return (LogEntry[])list.ToArray(typeof(LogEntry)); } public bool DeleteEntry(int index) { if (index < 0 || index >= m_LogEntries.Count) return false; m_LogEntries.RemoveAt(index); return true; } #endregion } } --- NEW FILE: LogEntry.cs --- #region LGPL License /* Bastard of a Bot Library Copyright (C) 2004 Bastard of a Bot Team This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion using System; using System.Xml; using Bot.Plugins.Sphere.Messages; using Bot.Other.Sphere; using Bot.Other.Sphere.Messages; namespace Bot.Plugins.Sphere.LogManagement { public class LogEntry { #region Private members protected DateTime m_EntryTime; protected Type m_EntryType; protected object m_Entry; protected string m_EntryRaw; protected bool m_Handled; protected string m_HandledBy; #endregion #region Public properties public DateTime Time { get { return m_EntryTime; } } public double DaysOld { get { return DateTime.Now.Subtract(m_EntryTime).TotalDays; } } public System.Type Type { get { return m_EntryType; } } public object Entry { get { return m_Entry; } } public string RawString { get { return m_EntryRaw; } } public bool Handled { get { return m_Handled; } } public string HandledBy { get { return m_HandledBy; } } #endregion #region Constructor public LogEntry() { m_EntryTime = DateTime.Now; } public LogEntry(object entry) { m_EntryTime = DateTime.Now; m_Entry = entry; m_EntryType = entry.GetType(); } public LogEntry(object entry, string raw) { m_EntryTime = DateTime.Now; m_Entry = entry; m_EntryType = entry.GetType(); m_EntryRaw = raw; } #endregion #region Public methods public void Handle(string user) { m_Handled = true; m_HandledBy = user; } public void UnHandle() { m_Handled = false; m_HandledBy = null; } public bool Load(XmlElement xmlElement) { string time = xmlElement.GetAttribute("time"); if (time == String.Empty) return false; m_EntryTime = DateTime.FromFileTime(long.Parse(time)); m_EntryRaw = xmlElement["Message"].InnerText; if (xmlElement["Handled"].InnerText == bool.TrueString) m_Handled = true; else m_Handled = false; if (m_Handled) m_HandledBy = xmlElement["HandledBy"].InnerText; m_Entry = SphereConnection.Instance.ParseMessage(m_EntryRaw); m_EntryType = m_Entry.GetType(); if (m_Entry == null) return false; return true; } public bool Save(XmlElement xmlElement) { xmlElement.SetAttribute("time", m_EntryTime.ToFileTime().ToString()); XmlNode valueText; XmlElement valueElement; valueText = xmlElement.OwnerDocument.CreateNode(XmlNodeType.Text, "Message", ""); valueText.Value = m_EntryRaw; valueElement = xmlElement.OwnerDocument.CreateElement("Message"); valueElement.AppendChild(valueText); xmlElement.AppendChild(valueElement); valueText = xmlElement.OwnerDocument.CreateNode(XmlNodeType.Text, "Handled", ""); if (m_Handled) valueText.Value = bool.TrueString; else valueText.Value = bool.FalseString; valueElement = xmlElement.OwnerDocument.CreateElement("Handled"); valueElement.AppendChild(valueText); xmlElement.AppendChild(valueElement); if (m_Handled) { valueText = xmlElement.OwnerDocument.CreateNode(XmlNodeType.Text, "HandledBy", ""); valueText.Value = m_HandledBy; valueElement = xmlElement.OwnerDocument.CreateElement("HandledBy"); valueElement.AppendChild(valueText); xmlElement.AppendChild(valueElement); } return true; } #endregion } } |
From: Iain M. <iai...@us...> - 2005-02-15 21:44:19
|
Update of /cvsroot/bobbot/Bob/Core In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv27991/Core Modified Files: Kernel.cs Log Message: AllowConditionTarget.Channel is now handled for ChannelCommand's. Or should be pending testing ;) Index: Kernel.cs =================================================================== RCS file: /cvsroot/bobbot/Bob/Core/Kernel.cs,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** Kernel.cs 16 Jan 2005 20:28:00 -0000 1.11 --- Kernel.cs 15 Feb 2005 21:44:09 -0000 1.12 *************** *** 593,600 **** { bool allConditionsMet = true; ! /*Channel chan = DataStore.GetChannel(args.Message.Channel.Name); if(chan == null) ! continue;*/ if(((ArrayList) m_MethodAllowConditions[attrib.Callback.GetHashCode()]).Count > 0) --- 593,600 ---- { bool allConditionsMet = true; ! Channel chan = DataStore.GetChannel(args.Message.Channel.Name); if(chan == null) ! continue; if(((ArrayList) m_MethodAllowConditions[attrib.Callback.GetHashCode()]).Count > 0) *************** *** 607,612 **** foreach(AllowConditionAttribute conAttrib in ((ArrayList) m_MethodAllowConditions[attrib.Callback.GetHashCode()])) { ! if(HandlerConditionMet(conAttrib, user) == false) allConditionsMet = false; } --- 607,621 ---- foreach(AllowConditionAttribute conAttrib in ((ArrayList) m_MethodAllowConditions[attrib.Callback.GetHashCode()])) { ! AllowConditionTarget target = conAttrib.Target; ! ! if(target == AllowConditionTarget.Default) { ! target = AllowConditionTarget.Channel; ! } ! ! if((target == AllowConditionTarget.Channel) && (HandlerConditionMet(conAttrib, chan) == false)) { allConditionsMet = false; + } else if((target == AllowConditionTarget.User) && (HandlerConditionMet(conAttrib, user) == false)) { + allConditionsMet = false; + } } |
From: Mr S. C. <mrs...@us...> - 2005-02-15 21:35:27
|
Update of /cvsroot/bobbot/Plugins/Sphere/LogManagement In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv25244/LogManagement Log Message: Directory /cvsroot/bobbot/Plugins/Sphere/LogManagement added to the repository |
From: Iain M. <iai...@us...> - 2005-02-07 02:27:08
|
Update of /cvsroot/bobbot/Other/SphereConnection In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv20657/SphereConnection Modified Files: SphereConnection.cs Log Message: Nothing to see here, move along :P Index: SphereConnection.cs =================================================================== RCS file: /cvsroot/bobbot/Other/SphereConnection/SphereConnection.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** SphereConnection.cs 7 Feb 2005 02:12:48 -0000 1.2 --- SphereConnection.cs 7 Feb 2005 02:26:57 -0000 1.3 *************** *** 340,345 **** BaseMessage msg = (BaseMessage) msgObj.Assembly.CreateInstance(msgObj.FullName); ! if(msg.CanParse(rawMessage)) ! return msg; } --- 340,349 ---- BaseMessage msg = (BaseMessage) msgObj.Assembly.CreateInstance(msgObj.FullName); ! if(msg.CanParse(rawMessage) == false) { ! continue; ! } ! ! msg.Parse(rawMessage); ! return msg; } |
From: Iain M. <iai...@us...> - 2005-02-07 02:12:58
|
Update of /cvsroot/bobbot/Other/SphereConnection In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv18169/SphereConnection Modified Files: SphereConnection.cs Log Message: Added SphereConnection.ParseMessage to parse a raw message. Will return either a BaseMessage or null. Index: SphereConnection.cs =================================================================== RCS file: /cvsroot/bobbot/Other/SphereConnection/SphereConnection.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** SphereConnection.cs 4 Jan 2005 23:15:58 -0000 1.1 --- SphereConnection.cs 7 Feb 2005 02:12:48 -0000 1.2 *************** *** 332,335 **** --- 332,349 ---- return m_AccountQueryTempValue; } + + public BaseMessage ParseMessage(string rawMessage) + { + // Needs rethinking, something more efficient. + foreach(Type msgObj in m_MessageParsers) + { + BaseMessage msg = (BaseMessage) msgObj.Assembly.CreateInstance(msgObj.FullName); + + if(msg.CanParse(rawMessage)) + return msg; + } + + return null; + } #endregion *************** *** 543,557 **** internal void OnMessageReceived(object sender, MessageReceivedEventArgs args) { ! // Needs rethinking, something more efficient. ! foreach(Type msgObj in m_MessageParsers) ! { ! BaseMessage msg = (BaseMessage) msgObj.Assembly.CreateInstance(msgObj.FullName); ! ! if(!msg.CanParse(args.Message)) ! continue; ! ! msg.Parse(args.Message); ! msg.Notify(this); ! } if(MessageReceived != null) --- 557,566 ---- internal void OnMessageReceived(object sender, MessageReceivedEventArgs args) { ! BaseMessage msg = ParseMessage(args.Message); ! ! if(msg == null) ! return; ! ! msg.Notify(this); if(MessageReceived != null) |
From: Mr S. C. <mrs...@us...> - 2005-01-21 03:51:52
|
Update of /cvsroot/bobbot/Plugins/Sphere/JailSystem In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv26768/Sphere/JailSystem Removed Files: JailEntry.cs JailSystem.cs Log Message: Removed JailEnter and JailSystem from the JailSystem folder Unable to remove JailSystem folder :@ --- JailEntry.cs DELETED --- --- JailSystem.cs DELETED --- |
From: Mr S. C. <mrs...@us...> - 2005-01-21 03:30:03
|
Update of /cvsroot/bobbot/Plugins/Sphere/PunishSystem In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv22510/Sphere/PunishSystem Added Files: BanEntry.cs BanSystem.cs JailEntry.cs JailSystem.cs Log Message: - Renamed the NameSpace 'JailSystem' to 'PunishSystem' - Added BanSystem class - Bans accounts from the Sphere Server. - Works exactly the same as the JailSystem class, without having sentence lengths. - Added BanEntry class --- NEW FILE: JailEntry.cs --- #region LGPL License /* Bastard of a Bot Library Copyright (C) 2004 Bastard of a Bot Team This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion using System; using System.Xml; using System.Collections; using System.Timers; namespace Bot.Plugins.Sphere.PunishSystem { public class JailEntry { #region Private members protected string m_Account; protected string m_Character; protected string m_GMName; protected DateTime m_JailEnd = DateTime.Now; protected DateTime m_JailStart = DateTime.Now; protected string m_Reason; protected JailSystem m_JailSystem; protected Timer m_JailTimer; #endregion #region Public properties public virtual string Account { get { return m_Account; } set { m_Account = value; } } public virtual string Character { get { return m_Character; } set { m_Character = value; } } public virtual string JailedBy { get { return m_GMName; } set { m_GMName = value; } } public virtual string Reason { get { return m_Reason; } set { m_Reason = value; } } public virtual DateTime JailedOn { get { return m_JailStart; } set { m_JailStart = value; } } public virtual DateTime JailedUntil { get { return m_JailEnd; } set { m_JailEnd = value; } } public virtual string TimeLeft { get { if (m_JailTimer == null || !m_JailTimer.Enabled) return "Sentence Disabled"; TimeSpan sentence = m_JailEnd.Subtract(DateTime.Now); return String.Format("{0} hours left", Convert.ToInt32(sentence.TotalHours)); } } #endregion #region Public methods public void StartSentence() { if (m_JailTimer != null) { m_JailTimer.Stop(); m_JailTimer.Dispose(); } TimeSpan sentence = m_JailEnd.Subtract(DateTime.Now); if (sentence.TotalMilliseconds < 30) m_JailTimer = new Timer(30); else m_JailTimer = new Timer(sentence.TotalMilliseconds); m_JailTimer.AutoReset = false; m_JailTimer.Elapsed += new ElapsedEventHandler(this.OnSentenceServed); m_JailTimer.Start(); } public bool Load(XmlElement xmlElement) { string account = xmlElement.GetAttribute("account"); string jailedon = xmlElement.GetAttribute("jailedon"); if(account == String.Empty) return false; m_Account = account; m_JailStart = DateTime.FromFileTime(long.Parse(jailedon)); m_Character = xmlElement["JailedChar"].InnerText; m_GMName = xmlElement["JailedBy"].InnerText; m_JailEnd = DateTime.FromFileTime(long.Parse(xmlElement["JailedUntil"].InnerText)); m_Reason = xmlElement["Reason"].InnerText; StartSentence(); return true; } public bool Save(XmlElement xmlElement) { xmlElement.SetAttribute("account", m_Account); xmlElement.SetAttribute("jailedon", m_JailStart.ToFileTime().ToString()); XmlNode valueText; XmlElement valueElement; valueText = xmlElement.OwnerDocument.CreateNode(XmlNodeType.Text, "JailedChar", ""); valueText.Value = m_Character; valueElement = xmlElement.OwnerDocument.CreateElement("JailedChar"); valueElement.AppendChild(valueText); xmlElement.AppendChild(valueElement); valueText = xmlElement.OwnerDocument.CreateNode(XmlNodeType.Text, "JailedBy", ""); valueText.Value = m_GMName; valueElement = xmlElement.OwnerDocument.CreateElement("JailedBy"); valueElement.AppendChild(valueText); xmlElement.AppendChild(valueElement); valueText = xmlElement.OwnerDocument.CreateNode(XmlNodeType.Text, "JailedUntil", ""); valueText.Value = m_JailEnd.ToFileTime().ToString(); valueElement = xmlElement.OwnerDocument.CreateElement("JailedUntil"); valueElement.AppendChild(valueText); xmlElement.AppendChild(valueElement); valueText = xmlElement.OwnerDocument.CreateNode(XmlNodeType.Text, "Reason", ""); valueText.Value = m_Reason; valueElement = xmlElement.OwnerDocument.CreateElement("Reason"); valueElement.AppendChild(valueText); xmlElement.AppendChild(valueElement); return true; } #endregion #region Event Handlers private void OnSentenceServed(object sender, ElapsedEventArgs e) { try { if (!m_JailSystem.Release(this)) { Bot.Core.Log.WriteLine("Sphere (JailDB)", "Failed to release '{0}'. Retrying in 5 minutes.", m_Account); m_JailTimer.AutoReset = false; m_JailTimer.Interval = 300000; // Try to release again in 5 minutes. m_JailTimer.Start(); return; } return; } catch (System.Exception ex) { Bot.Core.Log.WriteLine("Sphere (JailDB)", "Account '{0}' isn't released due to an error! - {1}", m_Account, ex.ToString()); m_JailTimer.AutoReset = false; m_JailTimer.Interval = 300000; // Try to release again in 5 minutes. m_JailTimer.Start(); return; } } #endregion #region Constructor public JailEntry(JailSystem system) { m_JailSystem = system; } #endregion } } --- NEW FILE: BanSystem.cs --- #region LGPL License /* Bastard of a Bot Library Copyright (C) 2004 Bastard of a Bot Team This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion using System; using System.IO; using System.Collections; using System.Xml; using System.Text; using Bot.Core; using Bot.Core.Irc; using Bot.Core.Irc.Messages; using Bot.Plugins.Sphere; using Bot.Plugins.Sphere.Messages; using Bot.Plugins.Sphere.Accounting; using Bot.Other.Sphere; using Bot.Other.Sphere.Messages; namespace Bot.Plugins.Sphere.PunishSystem { public class BanSystem { #region Private Members private string BanDatabase = "BanDatabase.xml"; private SphereConnection m_Server; private SpherePlugin m_Parent; private BanEntry[] m_BanEntries { get { return (BanEntry[]) m_BanEntryList.ToArray(typeof(BanEntry)); } } private ArrayList m_BanEntryList; #endregion #region Public Properties public int BannedAccounts { get { return m_BanEntryList.Count; } } #endregion #region Constructor public BanSystem(SpherePlugin parent) { m_Parent = parent; m_Server = m_Parent.InnerConnection; Init(); } public BanSystem(SpherePlugin parent, string database) { m_Parent = parent; m_Server = m_Parent.InnerConnection; this.BanDatabase = database; Init(); } private void Init() { m_BanEntryList = new ArrayList(); if (!File.Exists(this.BanDatabase)) { Log.WriteLine("Sphere (BanDB)", "Database Not Found. Creating '{0}'", this.BanDatabase); StreamWriter newDb = File.CreateText(BanDatabase); newDb.WriteLine("<!-- Wireplay Lothlorien Ban Database -->"); newDb.WriteLine("<!-- Database Created at {0}", DateTime.Now.ToString()); newDb.Close(); SaveDatabase(); } if (!LoadDatabase()) Log.WriteLine("Sphere (BanDB)", "Error occured whilst loading the Ban Database."); Log.WriteLine("Sphere (BanDB)", "{0} Ban Entries Loaded", this.m_BanEntries.Length); SaveDatabase(); m_Server.CustomEvent += new EventHandler(OnCustomEvent); } #endregion #region Database Save/Load public bool LoadDatabase() { try { Log.WriteLine("Sphere (BanDB)", "Loading Ban Database from '{0}'...", this.BanDatabase); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(this.BanDatabase); XmlElement xmlRoot = xmlDoc.DocumentElement; XmlNodeList xmlList = xmlRoot.GetElementsByTagName("BanEntry"); if(xmlList.Count == 0) return true; foreach(XmlElement xmlElement in xmlList) { BanEntry entry = new BanEntry( this ); if(entry.Load(xmlElement)) m_BanEntryList.Add(entry); } return true; } catch(Exception ex) { Log.WriteLine("Sphere (BanDB)", "Failed to load Ban Database file, reason: {0}", ex.ToString()); return false; } } public bool SaveDatabase() { try { Log.WriteLine("Sphere (BanDB)", "Writing database to '{0}'...", this.BanDatabase); XmlTextWriter xmlWriter = new XmlTextWriter(this.BanDatabase, Encoding.UTF8); xmlWriter.Formatting = Formatting.Indented; xmlWriter.Indentation = 4; XmlDocument xmlDoc = new XmlDocument(); XmlNode xmlRoot = xmlDoc.CreateNode(XmlNodeType.Element, "BanDatabase", ""); xmlDoc.AppendChild(xmlRoot); foreach(BanEntry entry in m_BanEntries) { XmlElement xmlElement = xmlDoc.CreateElement("BanEntry"); xmlRoot.AppendChild(xmlElement); (entry).Save(xmlElement); } xmlDoc.Save(xmlWriter); xmlWriter.Flush(); xmlWriter.Close(); return true; } catch(Exception ex) { Log.WriteLine("Sphere (BanDB)", "Failed to write Ban Database file, reason: {0}", ex.Message); return false; } } #endregion #region Public Methods public bool AddEntry(string account, string character, string gm, string reason) { try { if (IsBanned(account)) return false; BanEntry entry = new BanEntry( this ); entry.Account = account; entry.Character = character; entry.BannedBy = gm; entry.BannedOn = DateTime.Now; entry.Reason = reason; m_BanEntryList.Add(entry); return true; } catch { return false; } } public bool DelEntry(string account) { try { if (!IsBanned(account)) return false; for (int i = 0; i < m_BanEntryList.Count; i++) { if (((BanEntry) m_BanEntryList[i]).Account.ToLower() == account.ToLower()) { m_BanEntryList.RemoveAt(i); return true; } } return false; } catch { return false; } } public bool EditEntry(string account, string gm, string reason) { try { if (!IsBanned(account)) return false; BanEntry entry = GetBanEntry(account); if (entry.BannedBy.IndexOf(" (Amended by ") > -1) entry.BannedBy = entry.BannedBy.Substring(0, entry.BannedBy.IndexOf(' ')); if (gm != entry.BannedBy) entry.BannedBy += " (Amended by " + gm + ")"; if (reason != null) entry.Reason = reason; if (!DelEntry(account)) return false; m_BanEntryList.Add(entry); return true; } catch { return false; } } public BanEntry[] GetBanEntryList() { return m_BanEntries; } public BanEntry GetBanEntry(string account) { foreach (BanEntry i in m_BanEntries) { if (i.Account.ToLower() == account.ToLower()) return i; } return null; } public bool Ban(string[] args) { if (args.Length < 5) return false; return Ban(args[0], args[1], args[2], args[3]); } public bool Ban(string account, string character, string gm, string reason) { if (!m_Server.IsConnected) { return false; } try { if (reason == null || reason == "") reason = "None Set"; if (character == null || character == "") character = "All"; m_Server.WriteLine("account {0} block 1", account); if (!AddEntry(account, character, gm, reason)) return false; Log.WriteLine("Sphere (BanDB)", "Account '{0}' is banned by {1}! (Reason: {3})", account, gm, reason); return true; } catch { return false; } } public bool EditBan(string[] args) { if (args.Length < 5) return false; return EditBan(args[0], args[1], args[2]); } public bool EditBan(string account, string gm, string reason) { if (!m_Server.IsConnected) { return false; } try { if (!IsBanned(account)) return false; if (reason == null || reason == "") reason = null; if (!EditEntry(account, gm, reason)) return false; Log.WriteLine("Sphere (BanDB)", "Account Entry '{0}' is edited by {1}! (Reason: {3})", account, gm, (reason == null || reason == ""? "Unedited" : reason )); return true; } catch { return false; } } public bool UnBan(string[] args) { return UnBan(args[0], args[1]); } public bool UnBan(BanEntry entry) { return UnBan(entry.Account, entry.BannedBy); } public bool UnBan(string account, string gm) { if (!m_Server.IsConnected) { return false; } try { if (!IsBanned(account)) return false; m_Server.WriteLine("account {0} block 0", account); if (!DelEntry(account)) return false; Log.WriteLine("Sphere (BanDB)", "Account '{0}' is unbanned by '{1}'!", account, gm); return true; } catch { return false; } } public bool IsBanned(string account) { for (int i = 0; i < m_BanEntryList.Count; i++) { if (((BanEntry) m_BanEntryList[i]).Account.ToLower() == account.ToLower()) return true; } return false; } #endregion private void OnCustomEvent(object sender, EventArgs args) { /* if(args is PlayerBannedEventArgs) OnPlayerBanned(sender, (PlayerBannedEventArgs) args); else if(args is PlayerUnBannedEventArgs) OnPlayerUnBanned(sender, (PlayerUnBannedEventArgs) args);*/ } /* private void OnPlayerBanned(object sender, PlayerBannedEventArgs args) { string account = m_Server.GetItemProperty(args.Message.Player, "account"); string character = m_Server.GetItemProperty(args.Message.Player, "name"); string gm = m_Server.GetItemProperty(args.Message.GM, "name"); if (!Ban(account, character, gm, args.Message.Reason)) Kernel.Instance.Network.SendChannelMessage(m_Parent.InnerConfig.OutputChannel, "Unable to Ban Account '{0}'.", account); } private void OnPlayerUnBanned(object sender, PlayerUnBannedEventArgs args) { string account = m_Server.GetItemProperty(args.Message.Player, "account"); string gm = m_Server.GetItemProperty(args.Message.GM, "name"); if (!UnBan(account, gm)) Kernel.Instance.Network.SendChannelMessage(m_Parent.InnerConfig.OutputChannel, "Unable to UnBan Account '{0}'.", account); } */ } } --- NEW FILE: BanEntry.cs --- #region LGPL License /* Bastard of a Bot Library Copyright (C) 2004 Bastard of a Bot Team This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion using System; using System.Xml; using System.Collections; using System.Timers; namespace Bot.Plugins.Sphere.PunishSystem { public class BanEntry { #region Private members protected string m_Account; protected string m_Character; protected string m_GMName; protected DateTime m_BanTime = DateTime.Now; protected string m_Reason; protected BanSystem m_BanSystem; #endregion #region Public properties public virtual string Account { get { return m_Account; } set { m_Account = value; } } public virtual string Character { get { return m_Character; } set { m_Character = value; } } public virtual string BannedBy { get { return m_GMName; } set { m_GMName = value; } } public virtual string Reason { get { return m_Reason; } set { m_Reason = value; } } public virtual DateTime BannedOn { get { return m_BanTime; } set { m_BanTime = value; } } #endregion #region Public methods public bool Load(XmlElement xmlElement) { string account = xmlElement.GetAttribute("account"); string bannedon = xmlElement.GetAttribute("datetime"); if(account == String.Empty) return false; m_Account = account; m_BanTime = DateTime.FromFileTime(long.Parse(bannedon)); m_Character = xmlElement["BannedChar"].InnerText; m_GMName = xmlElement["BannedBy"].InnerText; m_Reason = xmlElement["Reason"].InnerText; return true; } public bool Save(XmlElement xmlElement) { xmlElement.SetAttribute("account", m_Account); xmlElement.SetAttribute("datetime", m_BanTime.ToFileTime().ToString()); XmlNode valueText; XmlElement valueElement; valueText = xmlElement.OwnerDocument.CreateNode(XmlNodeType.Text, "BannedChar", ""); valueText.Value = m_Character; valueElement = xmlElement.OwnerDocument.CreateElement("BannedChar"); valueElement.AppendChild(valueText); xmlElement.AppendChild(valueElement); valueText = xmlElement.OwnerDocument.CreateNode(XmlNodeType.Text, "BannedBy", ""); valueText.Value = m_GMName; valueElement = xmlElement.OwnerDocument.CreateElement("BannedBy"); valueElement.AppendChild(valueText); xmlElement.AppendChild(valueElement); valueText = xmlElement.OwnerDocument.CreateNode(XmlNodeType.Text, "Reason", ""); valueText.Value = m_Reason; valueElement = xmlElement.OwnerDocument.CreateElement("Reason"); valueElement.AppendChild(valueText); xmlElement.AppendChild(valueElement); return true; } #endregion #region Constructor public BanEntry(BanSystem system) { m_BanSystem = system; } #endregion } } --- NEW FILE: JailSystem.cs --- #region LGPL License /* Bastard of a Bot Library Copyright (C) 2004 Bastard of a Bot Team This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion using System; using System.IO; using System.Collections; using System.Xml; using System.Text; using Bot.Core; using Bot.Core.Irc; using Bot.Core.Irc.Messages; using Bot.Plugins.Sphere; using Bot.Plugins.Sphere.Messages; using Bot.Plugins.Sphere.Accounting; using Bot.Other.Sphere; using Bot.Other.Sphere.Messages; namespace Bot.Plugins.Sphere.PunishSystem { public class JailSystem { #region Private Members private string JailDatabase = "JailDatabase.xml"; private SphereConnection m_Server; private SpherePlugin m_Parent; private JailEntry[] m_JailEntries { get { return (JailEntry[]) m_JailEntryList.ToArray(typeof(JailEntry)); } } private ArrayList m_JailEntryList; #endregion #region Public Properties public int JailedAccounts { get { return m_JailEntryList.Count; } } #endregion #region Constructor public JailSystem(SpherePlugin parent) { m_Parent = parent; m_Server = m_Parent.InnerConnection; Init(); } public JailSystem(SpherePlugin parent, string database) { m_Parent = parent; m_Server = m_Parent.InnerConnection; this.JailDatabase = database; Init(); } private void Init() { m_JailEntryList = new ArrayList(); if (!File.Exists(this.JailDatabase)) { Log.WriteLine("Sphere (JailDB)", "Database Not Found. Creating '{0}'", this.JailDatabase); StreamWriter newDb = File.CreateText(JailDatabase); newDb.WriteLine("<!-- Wireplay Lothlorien Jail Database -->"); newDb.WriteLine("<!-- Database Created at {0}", DateTime.Now.ToString()); newDb.Close(); SaveDatabase(); } if (!LoadDatabase()) Log.WriteLine("Sphere (JailDB)", "Error occured whilst loading the Jail Database."); Log.WriteLine("Sphere (JailDB)", "{0} Jail Entries Loaded", this.m_JailEntries.Length); SaveDatabase(); m_Server.CustomEvent += new EventHandler(OnCustomEvent); } #endregion #region Database Save/Load public bool LoadDatabase() { try { Log.WriteLine("Sphere (JailDB)", "Loading Jail Database from '{0}'...", this.JailDatabase); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(this.JailDatabase); XmlElement xmlRoot = xmlDoc.DocumentElement; XmlNodeList xmlList = xmlRoot.GetElementsByTagName("JailEntry"); if(xmlList.Count == 0) return true; foreach(XmlElement xmlElement in xmlList) { JailEntry entry = new JailEntry( this ); if(entry.Load(xmlElement)) m_JailEntryList.Add(entry); } return true; } catch(Exception ex) { Log.WriteLine("Sphere (JailDB)", "Failed to load Jail Database file, reason: {0}", ex.ToString()); return false; } } public bool SaveDatabase() { try { Log.WriteLine("Sphere (JailDB)", "Writing database to '{0}'...", this.JailDatabase); XmlTextWriter xmlWriter = new XmlTextWriter(this.JailDatabase, Encoding.UTF8); xmlWriter.Formatting = Formatting.Indented; xmlWriter.Indentation = 4; XmlDocument xmlDoc = new XmlDocument(); XmlNode xmlRoot = xmlDoc.CreateNode(XmlNodeType.Element, "JailDatabase", ""); xmlDoc.AppendChild(xmlRoot); foreach(JailEntry entry in m_JailEntries) { XmlElement xmlElement = xmlDoc.CreateElement("JailEntry"); xmlRoot.AppendChild(xmlElement); (entry).Save(xmlElement); } xmlDoc.Save(xmlWriter); xmlWriter.Flush(); xmlWriter.Close(); return true; } catch(Exception ex) { Log.WriteLine("Sphere (JailDB)", "Failed to write Jail Database file, reason: {0}", ex.Message); return false; } } #endregion #region Public Methods public bool AddEntry(string account, string character, string gm, TimeSpan length, string reason) { try { if (IsJailed(account)) return false; JailEntry entry = new JailEntry( this ); entry.Account = account; entry.Character = character; entry.JailedBy = gm; entry.JailedOn = DateTime.Now; entry.JailedUntil = DateTime.Now.Add(length); entry.Reason = reason; entry.StartSentence(); m_JailEntryList.Add(entry); return true; } catch { return false; } } public bool DelEntry(string account) { try { if (!IsJailed(account)) return false; for (int i = 0; i < m_JailEntryList.Count; i++) { if (((JailEntry) m_JailEntryList[i]).Account.ToLower() == account.ToLower()) { m_JailEntryList.RemoveAt(i); return true; } } return false; } catch { return false; } } public bool EditEntry(string account, string gm, TimeSpan length, string reason) { try { if (!IsJailed(account)) return false; JailEntry entry = GetJailEntry(account); if (entry.JailedBy.IndexOf(" (Amended by ") > -1) entry.JailedBy = entry.JailedBy.Substring(0, entry.JailedBy.IndexOf(' ')); if (gm != entry.JailedBy) entry.JailedBy += " (Amended by " + gm + ")"; if (length.TotalMilliseconds > DateTime.Now.Subtract(entry.JailedUntil).TotalMilliseconds) entry.JailedUntil = entry.JailedUntil.Add(length); if (reason != null) entry.Reason = reason; entry.StartSentence(); if (!DelEntry(account)) return false; m_JailEntryList.Add(entry); return true; } catch { return false; } } public JailEntry[] GetJailEntryList() { return m_JailEntries; } public JailEntry GetJailEntry(string account) { foreach (JailEntry i in m_JailEntries) { if (i.Account.ToLower() == account.ToLower()) return i; } return null; } public bool Jail(string[] args) { if (args.Length < 5) return false; return Jail(args[0], args[1], args[2], args[3], args[4]); } public bool Jail(string account, string character, string gm, string length, string reason) { if (!m_Server.IsConnected) { return false; } try { if (reason == null || reason == "") reason = "None Set"; if (character == null || character == "") character = "All"; m_Server.WriteLine("account {0} jail 1", account); Account jailed = AccountRegistration.Instance.GetAccount(account); for (int i = 0; i < jailed.Chars; i++) { m_Server.WriteLine("account {0} char.{1}.send_to_jail={2}", account, i, length); } if (!AddEntry(account, character, gm, TimeSpan.FromHours(double.Parse(length)), reason)) return false; Log.WriteLine("Sphere (JailDB)", "Account '{0}' is jailed by {1}! ({2} hours) (Reason: {3})", account, gm, length, reason); return true; } catch { return false; } } public bool EditJail(string[] args) { if (args.Length < 5) return false; return EditJail(args[0], args[1], args[2], args[3]); } public bool EditJail(string account, string gm, string length, string reason) { if (!m_Server.IsConnected) { return false; } try { if (!IsJailed(account)) return false; if (reason == null || reason == "") reason = null; if (!EditEntry(account, gm, TimeSpan.FromHours(double.Parse(length)), reason)) return false; Log.WriteLine("Sphere (JailDB)", "Account Entry '{0}' is edited by {1}! ({2} hours) (Reason: {3})", account, gm, (double.Parse(length) != 0? length : "Unedited"), (reason == null || reason == ""? "Unedited" : reason )); return true; } catch { return false; } } public bool Release(string[] args) { return Release(args[0], args[1]); } public bool Release(JailEntry entry) { return Release(entry.Account, entry.JailedBy); } public bool Release(string account, string gm) { if (!m_Server.IsConnected) { return false; } try { if (!IsJailed(account)) return false; m_Server.WriteLine("account {0} jail 0", account); Account jailed = AccountRegistration.Instance.GetAccount(account); for (int i = 0; i < jailed.Chars; i++) { m_Server.WriteLine("account {0} char.{1}.release_from_jail", account, i); } if (!DelEntry(account)) return false; Log.WriteLine("Sphere (JailDB)", "Account '{0}' is released from jail!", account); return true; } catch { return false; } } public bool IsJailed(string account) { for (int i = 0; i < m_JailEntryList.Count; i++) { if (((JailEntry) m_JailEntryList[i]).Account.ToLower() == account.ToLower()) return true; } return false; } #endregion private void OnCustomEvent(object sender, EventArgs args) { if(args is PlayerJailedEventArgs) OnPlayerJailed(sender, (PlayerJailedEventArgs) args); else if(args is PlayerReleasedEventArgs) OnPlayerReleased(sender, (PlayerReleasedEventArgs) args); } private void OnPlayerJailed(object sender, PlayerJailedEventArgs args) { string account = m_Server.GetItemProperty(args.Message.Player, "account"); string character = m_Server.GetItemProperty(args.Message.Player, "name"); string gm = m_Server.GetItemProperty(args.Message.GM, "name"); if (!Jail(account, character, gm, args.Message.Length.ToString(), args.Message.Reason)) Kernel.Instance.Network.SendChannelMessage(m_Parent.InnerConfig.OutputChannel, "Unable to Jail Account '{0}'.", account); } private void OnPlayerReleased(object sender, PlayerReleasedEventArgs args) { string account = m_Server.GetItemProperty(args.Message.Player, "account"); string gm = m_Server.GetItemProperty(args.Message.GM, "name"); if (!Release(account, gm)) Kernel.Instance.Network.SendChannelMessage(m_Parent.InnerConfig.OutputChannel, "Unable to Release Account '{0}'.", account); } } } |
From: Mr S. C. <mrs...@us...> - 2005-01-21 03:18:06
|
Update of /cvsroot/bobbot/Plugins/Sphere/PunishSystem In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv20365/PunishSystem Log Message: Directory /cvsroot/bobbot/Plugins/Sphere/PunishSystem added to the repository |
From: Iain M. <iai...@us...> - 2005-01-16 20:28:11
|
Update of /cvsroot/bobbot/Bob/Core In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv20205/Core Modified Files: Kernel.cs Log Message: Debug message taken out. Index: Kernel.cs =================================================================== RCS file: /cvsroot/bobbot/Bob/Core/Kernel.cs,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** Kernel.cs 16 Jan 2005 20:27:14 -0000 1.10 --- Kernel.cs 16 Jan 2005 20:28:00 -0000 1.11 *************** *** 459,464 **** int val = Comparer.DefaultInvariant.Compare(target.GetProperty(condition.Property), condition.Value); - Console.WriteLine("Compare t: {0} a: {1} v: {2}", target.GetProperty(condition.Property), condition.Value, val); - if((val == 0) || (val > 0)) conditionMet = true; --- 459,462 ---- |
From: Iain M. <iai...@us...> - 2005-01-16 20:27:25
|
Update of /cvsroot/bobbot/Bob/Core In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv20080/Core Modified Files: Kernel.cs Log Message: Fixed - AllowConditionAttribute scanning was not working. Index: Kernel.cs =================================================================== RCS file: /cvsroot/bobbot/Bob/Core/Kernel.cs,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** Kernel.cs 16 Jan 2005 03:16:19 -0000 1.9 --- Kernel.cs 16 Jan 2005 20:27:14 -0000 1.10 *************** *** 360,368 **** { if(attrib is ChannelCommandAttribute) ! AddCommandHandler((BaseCommandAttribute) attrib, plugin, method, m_ChannelCommandHandlers,new Type[] { typeof(NetworkChannel), typeof(NetworkUser) }); else if(attrib is PrivateCommandAttribute) ! AddCommandHandler((BaseCommandAttribute) attrib, plugin, method, m_PrivateCommandHandlers,new Type[] { typeof(NetworkUser) }); else if(attrib is RemoteCommandAttribute) ! AddCommandHandler((BaseCommandAttribute) attrib, plugin, method, m_RemoteCommandHandlers,new Type[] { typeof(RemoteConnection) }); } } --- 360,375 ---- { if(attrib is ChannelCommandAttribute) ! AddCommandHandler((BaseCommandAttribute) attrib, plugin, method, m_ChannelCommandHandlers, new Type[] { typeof(NetworkChannel), typeof(NetworkUser) }); else if(attrib is PrivateCommandAttribute) ! AddCommandHandler((BaseCommandAttribute) attrib, plugin, method, m_PrivateCommandHandlers, new Type[] { typeof(NetworkUser) }); else if(attrib is RemoteCommandAttribute) ! AddCommandHandler((BaseCommandAttribute) attrib, plugin, method, m_RemoteCommandHandlers, new Type[] { typeof(RemoteConnection) }); ! else if(attrib is AllowConditionAttribute) ! { ! if(m_MethodAllowConditions[method.GetHashCode()] == null) ! m_MethodAllowConditions[method.GetHashCode()] = new ArrayList(); ! ! ((ArrayList) m_MethodAllowConditions[method.GetHashCode()]).Add(attrib); ! } } } *************** *** 452,455 **** --- 459,464 ---- int val = Comparer.DefaultInvariant.Compare(target.GetProperty(condition.Property), condition.Value); + Console.WriteLine("Compare t: {0} a: {1} v: {2}", target.GetProperty(condition.Property), condition.Value, val); + if((val == 0) || (val > 0)) conditionMet = true; |
From: Mr S. C. <mrs...@us...> - 2005-01-16 20:08:04
|
Update of /cvsroot/bobbot/Plugins/Sphere In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv15947/Sphere Modified Files: SphereAuth.cs SpherePlugin.cs Log Message: Reversed the order of Accounting.AccountPriv enum. Added extra checks in to ensure users are staff. Added AllowCondition attributes to commands Index: SpherePlugin.cs =================================================================== RCS file: /cvsroot/bobbot/Plugins/Sphere/SpherePlugin.cs,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** SpherePlugin.cs 10 Jan 2005 01:41:01 -0000 1.13 --- SpherePlugin.cs 16 Jan 2005 20:07:50 -0000 1.14 *************** *** 1,1121 **** ! #region LGPL License ! /* ! Bastard of a Bot Library ! Copyright (C) 2004 Bastard of a Bot Team ! ! This library is free software; you can redistribute it and/or ! modify it under the terms of the GNU Lesser General Public ! License as published by the Free Software Foundation; either ! version 2.1 of the License, or (at your option) any later version. ! [...1095 lines suppressed...] ! { ! Kernel.Instance.Network.SendChannelMessage(chan, "I am on the following channels:"); ! ! foreach(string channel in Kernel.Instance.Network.Channels.Keys) ! Kernel.Instance.Network.SendChannelMessage(chan, "\t\t{0}", channel); ! } ! ! [ChannelCommand("!peak")] ! private void PeakCommand(NetworkChannel chan, NetworkUser user, string[] args) ! { ! Kernel.Instance.Network.SendChannelMessage(chan, "The peak clients is {0}", m_ClientPeak); ! } ! ! #endregion ! } ! } --- 1,2 ---- ! #region LGPL License /* Bastard of a Bot Library Copyright (C) 2004 Bastard of a Bot Team This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion using System; using System.IO; using System.Net; using System.Collections; using System.Configuration; using System.Timers; using Bot.Core; using Bot.Core.Irc; using Bot.Core.Irc.Messages; using Bot.Core.RemoteAdmin; using Bot.Plugins.Sphere; using Bot.Plugins.Sphere.Messages; using Bot.Plugins.Sphere.JailSystem; using Bot.Plugins.Sphere.Accounting; using Bot.Other.Sphere; using Bot.Other.Sphere.Messages; namespace Bot.Plugins.Sphere { public class SpherePlugin : MarshalByRefObject, IPlugin { #region Private members private SphereConfig m_Config; private SphereAuth m_SphereAuth; private SphereConnection m_Server; private AccountRegistration m_Accounting; private JailSystem.JailSystem m_JailSystem; private int m_KillCount; private int m_PageCount; private int m_ClientPeak; private int m_ConnectCount; private int m_WorldSaveCount; private int m_ClientCommandsCount; private string m_LothBotUid; private Mobile m_LastVictim; private Mobile[] m_LastKillers; private Timer m_Timer; private DateTime m_LogNextOpen; private NetworkUser m_LastUser; private StreamWriter m_CurrentLog; #endregion #region Public properties public SphereConfig InnerConfig { get { return m_Config; } } public SphereConnection InnerConnection { get { return m_Server; } } #endregion #region IPlugin implementation public string Name { get { return "Sphere"; } } public string Author { get { return "Iain Mckay <jo...@wi...>"; } } public void Start() { m_Config = (SphereConfig) ConfigurationSettings.GetConfig("SphereConfig"); m_PageCount = 0; m_ClientPeak = 0; m_ConnectCount = 0; m_WorldSaveCount = 0; m_ClientCommandsCount = 0; m_LothBotUid = ""; if (File.Exists("peak.txt")) { StreamReader peakRead = File.OpenText("peak.txt"); string line = peakRead.ReadLine(); while (line != null) { if (line.StartsWith("PEAK")) { m_ClientPeak = Int32.Parse(line.Remove(0, 5)); } line = peakRead.ReadLine(); } peakRead.Close(); } m_Timer = new Timer(); m_Timer.Interval = m_Config.ResyncPeriod; m_Timer.AutoReset = true; m_Timer.Enabled = true; m_Timer.Elapsed += new ElapsedEventHandler(OnTimerElapsed); m_LogNextOpen = DateTime.Now; m_Server = SphereConnection.Instance; m_Server.CustomLog += new CustomLogEventHandler(OnCustomLog); m_Server.ShowValue += new ShowValueEventHandler(OnShowValue); m_Server.ScriptError += new ScriptErrorEventHandler(OnScriptError); m_Server.WorldSave += new WorldSaveEventHandler(OnWorldSave); m_Server.ClientPage += new ClientPageEventHandler(OnClientPage); m_Server.ClientKilled +=new ClientKilledEventHandler(OnClientKilled); m_Server.Connected += new ConnectedEventHandler(OnConnected); m_Server.Disconnected += new DisconnectedEventHandler(OnDisconnected); m_Server.ConnectionLost += new DisconnectedEventHandler(OnConnectionLost); m_Server.AdminWelcome += new AdminWelcomeEventHandler(OnAdminWelcome); m_Server.ClientCommand += new ClientCommandEventHandler(OnClientCommand); m_Server.ConnectionFailed += new DisconnectedEventHandler(OnConnectionFailed); m_Server.MessageReceived += new MessageReceivedEventHandler(OnMessageReceived); m_Server.AdminBadPassword += new AdminBadPasswordEventHandler(OnAdminBadPassword); m_Server.AdminAccountInUse += new AdminAccountInUseEventHandler(OnAdminAccountInUse); m_LastVictim = new Mobile(MobileType.Player, "Victim"); m_LastKillers = new Mobile[] { new Mobile(MobileType.Npc, "Aggressor") }; m_Server.Password = m_Config.Password; m_Server.Connect(IPAddress.Parse(m_Config.Address), m_Config.Port); m_JailSystem = new JailSystem.JailSystem(this, m_Config.JailDatabase); m_Accounting = new AccountRegistration(m_Server, m_Config.AccountDatabase); m_SphereAuth = new SphereAuth(this); } public void Stop() { if(m_Server != null) { m_Server.Disconnect(); m_Server = null; } } #endregion #region Event handlers private void OnConnected(object sender, ConnectedEventArgs args) { Log.WriteLine("Sphere", "Connected to '{0}'", args.EndPoint.ToString()); Kernel.Instance.Network.SendChannelMessage(m_Config.OutputChannel, String.Format("Connected to '{0}'", args.EndPoint.ToString())); } private void OnDisconnected(object sender, DisconnectedEventArgs args) { Log.WriteLine("Sphere", "Disconnected from '{0}'", args.EndPoint.ToString()); Kernel.Instance.Network.SendChannelMessage(m_Config.OutputChannel, String.Format("Disconnected from '{0}'", args.EndPoint.ToString())); } private void OnConnectionLost(object sender, DisconnectedEventArgs args) { Log.WriteLine("Sphere", "Connection lost to '{0}'", args.EndPoint.ToString()); Kernel.Instance.Network.SendChannelMessage(m_Config.OutputChannel, String.Format("Connection lost to '{0}'", args.EndPoint.ToString())); } private void OnConnectionFailed(object sender, DisconnectedEventArgs args) { Log.WriteLine("Sphere", "Failed to connect to '{0}'", args.EndPoint.ToString()); Kernel.Instance.Network.SendChannelMessage(m_Config.OutputChannel, String.Format("Failed to connect to '{0}'", args.EndPoint.ToString())); } private void OnAdminWelcome(object sender, AdminWelcomeEventArgs args) { Log.WriteLine("Sphere", "Signed onto the administration console"); Kernel.Instance.Network.SendChannelMessage(m_Config.OutputChannel, "Signed onto the administration console"); m_Server.WriteLine("show clients"); m_Server.WriteLine("show var.lothbot_uid"); /*string clicount = (string)m_GetValue.GetProperty("clients"); if (clicount != null) m_ClientCount = Int32.Parse(clicount); string botuid = (string)m_GetValue.GetProperty("var.lothbot_uid"); if (botuid != null && botuid.Trim() != "") m_LothBotUid = botuid;*/ } private void OnAdminBadPassword(object sender, AdminBadPasswordEventArgs args) { Log.WriteLine("Sphere", "Could not sign in, bad password."); Kernel.Instance.Network.SendChannelMessage(m_Config.OutputChannel, "Could not sign in, bad password."); m_Server.Disconnect(); } private void OnAdminAccountInUse(object sender, AdminAccountInUseEventArgs args) { Log.WriteLine("Sphere", "Could not sign in, account in use."); Kernel.Instance.Network.SendChannelMessage(m_Config.OutputChannel, "Could not sign in, account in use."); m_Server.Disconnect(); } private void OnClientPage(object sender, ClientPageEventArgs args) { Log.WriteLine("Sphere", "Page from '{0}': {1}", args.Message.Character, args.Message.Page); string pageStr = String.Format("Page from {0} [{1}] at {2}: {3}", args.Message.Character, args.Message.Serial, args.Message.Position.ToString(), args.Message.Page); Kernel.Instance.Network.SendChannelMessage(m_Config.OutputChannel, pageStr); } private void OnClientKilled(object sender, ClientKilledEventArgs args) { m_KillCount++; m_LastVictim = args.Message.Victim; m_LastKillers = args.Message.Aggressors; } private void OnClientCommand(object sender, ClientCommandEventArgs args) { m_ClientCommandsCount++; } private void OnWorldSave(object sender, WorldSaveEventArgs args) { m_WorldSaveCount++; } private void OnMessageReceived(object sender, MessageReceivedEventArgs args) { // If we have passed midnight or we don't have a logfile open, open new log file. if((m_LogNextOpen <= DateTime.Now) || (m_CurrentLog == null)) { if(m_CurrentLog != null) { m_CurrentLog.Close(); m_CurrentLog = null; } string logFile = Path.Combine(m_Config.LogDirectory, String.Format("{0}-{1}-{2}.log", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day)); try { m_CurrentLog = new StreamWriter(logFile, true); m_CurrentLog.AutoFlush = true; m_CurrentLog.WriteLine("---------------------------------------------------------------"); m_CurrentLog.WriteLine("Log opened at {0} on {1}", DateTime.Now.ToShortTimeString(), DateTime.Now.ToLongDateString()); m_CurrentLog.WriteLine("---------------------------------------------------------------"); Log.WriteLine("Sphere", "Rotated log file"); m_LogNextOpen = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day); m_LogNextOpen = m_LogNextOpen.AddDays(1); } catch(Exception ex) { Log.WriteLine("Sphere", "Could not rotate log file, {0}", ex.Message); } } if(m_CurrentLog != null) m_CurrentLog.WriteLine(args.Message); //Log.WriteLine("Sphere", args.Message); } private void OnShowValue(object sender, ShowValueEventArgs args) { if((args.Message.Property.ToLower() == "var.lothbot_uid") && (args.Message.Value.Trim() != "")) m_LothBotUid = args.Message.Value; } private void OnScriptError(object sender, ScriptErrorEventArgs args) { if (args.Message.Script == "botgmnpc.scp") { Kernel.Instance.Network.SendChannelMessage(m_Config.OutputChannel, args.Message.Error); return; } //Kernel.Instance.Network.SendChannelMessage(m_Config.OutputChannel, "Error! Time:{0} Script:{1} Line:{2} Error:{3}", args.Message.Time.ToString(), args.Message.Script, args.Message.LineNumber.ToString(), args.Message.Error); } private void OnCustomLog(object sender, CustomLogEventArgs args) { if (args.Message.Script == "botgmnpc.scp") { Kernel.Instance.Network.SendChannelMessage(m_Config.OutputChannel, args.Message.Message); return; } } private void OnTimerElapsed(object sender, ElapsedEventArgs e) { if (m_Server.IsConnected) { string botuid = (string) m_Server.GetProperty("var.lothbot_uid"); if (botuid != null && botuid.Trim() != "") m_LothBotUid = botuid; } else m_Server.Connect(IPAddress.Parse(m_Config.Address), m_Config.Port); //if (m_Config.JailAutoSave) //bool properties don't work in the config? :s m_JailSystem.SaveDatabase(); if (File.Exists("peak.txt")) File.Delete("peak.txt"); StreamWriter peakWrite = File.CreateText("peak.txt"); peakWrite.Write("PEAK={0}", m_ClientPeak); peakWrite.Close(); if (m_Timer.Interval == 1) { m_Timer.Stop(); m_Timer.Interval = m_Config.ResyncPeriod; m_Timer.Start(); } } #endregion #region Test/Temp Commands [AllowCondition("LothStaff", AccountPriv.Owner, AllowConditionUsage.Equals)] [PrivateCommand("testval")] private void testvalcommand(NetworkUser user, string[] args) { object o; if (args.Length <= 0) o = m_Server.GetProperty("uid.1.name"); else o = m_Server.GetProperty(args[0]); Kernel.Instance.Network.SendPrivateMessage(user, "Value is '{0}'", (string)o); } [AllowCondition("LothStaff", AccountPriv.Owner, AllowConditionUsage.Equals)] [PrivateCommand("testaccount")] private void testcommand(NetworkUser user, string[] args) { if (args.Length <= 0) m_Server.WriteLine("account blah show {0}", m_Server.ValidAccountProperties[new Random().Next(0, m_Server.ValidAccountProperties.Count)]); else { if (!m_Accounting.AccountExists(args[0])) Kernel.Instance.Network.SendPrivateMessage(user, "Account '{0}' doesn't exist!", args[0]); else { Account temp = m_Accounting.GetAccount(args[0]); if (temp == null) { Kernel.Instance.Network.SendPrivateMessage(user, "Account '{0}' doesn't exist! (Error? :s)", args[0]); return; } Kernel.Instance.Network.SendPrivateMessage(user, "Account: {0} Password: {1}", temp.Name, temp.Password); Kernel.Instance.Network.SendPrivateMessage(user, "Lang: {0} PLevel: {1}", temp.Lang, Account.PrivToString(temp.Plevel)); Kernel.Instance.Network.SendPrivateMessage(user, "FirstIP: {0} FirstDate: {1}", temp.FirstIP, temp.FirstConnectDate); Kernel.Instance.Network.SendPrivateMessage(user, "LastIP: {0} LastDate: {1}", temp.LastIP, temp.LastConnectDate); Kernel.Instance.Network.SendPrivateMessage(user, "Chars: {0} LastChar: 0{1:x}", temp.Chars, temp.LastCharUID); Kernel.Instance.Network.SendPrivateMessage(user, "TotalConnect: {0} LastConnect: {1}", temp.TotalConnectTime, temp.LastConnectTime); Kernel.Instance.Network.SendPrivateMessage(user, "Priv: 0{0:x}", temp.Priv); Kernel.Instance.Network.SendPrivateMessage(user, "Jailed: {0} Blocked: {1}", ((temp.Jailed)? "Yes" : "No"), ((temp.Blocked)? "Yes" : "No")); } return; } } [AllowCondition("LothStaff", AccountPriv.Owner, AllowConditionUsage.Equals)] [PrivateCommand("testitem")] private void testitemcommand(NetworkUser user, string[] args) { if (args.Length != 2) return; user.SendMessage("Value '{0}' for '{1}' is {2}", args[1], args[0], m_Server.GetItemProperty(Int32.Parse(args[0], System.Globalization.NumberStyles.HexNumber), args[1])); } [PrivateCommand("mypriv")] private void myprivcommand(NetworkUser user, string[] args) { user.SendNotice("Your priv is: {0}", Account.PrivToString(m_SphereAuth.GetStaffPriv(user))); return; } [PrivateCommand("liststaff")] private void liststaffcommand(NetworkUser user, string[] args) { foreach (Bot.Core.User staff in m_SphereAuth.StaffMembers()) user.SendNotice("{0}, {1}", staff.Name, Account.PrivToString((AccountPriv)staff.GetProperty("LothStaff"))); } [ChannelCommand("listchan")] private void ListChan(NetworkChannel chan, NetworkUser user, string[] args) { Kernel.Instance.Network.SendChannelMessage(chan, "I am on the following channels:"); foreach(string channel in Kernel.Instance.Network.Channels.Keys) Kernel.Instance.Network.SendChannelMessage(chan, "\t\t{0}", channel); } #endregion #region 'Remote' Commands [AllowCondition("LothStaff", AccountPriv.Admin, AllowConditionUsage.GreaterThanOrEqual)] [RemoteCommand("account")] private static void RemoteAccountCommand(RemoteConnection sender, string[] args) { if (args.Length < 2) { sender.Send("Invalid Command or Format."); return; } if (args[0].ToLower() == "add") switch (args.Length) { case 2: { if (AccountRegistration.Instance.AccountAdd(args[1])) sender.Send("Account {0} created successfully.", args[1]); else sender.Send("Unable to create account!"); return; } case 3: { if (AccountRegistration.Instance.AccountAdd(args[1], args[2])) sender.Send("Account {0} created successfully.", args[1]); else sender.Send("Unable to create account!"); return; } default: { if (AccountRegistration.Instance.AccountAdd(args[1], args[2], Account.StringToPriv(args[3]))) sender.Send("Account {0} created successfully.", args[1]); else sender.Send("Unable to create account!"); return; } } else if (args[1].ToLower() == "delete") { if (AccountRegistration.Instance.AccountDel(args[0])) sender.Send("Account {0} deleted!", args[0]); ! else sender.Send("Unable to delete account!"); return; } else { string[] function = new string[ args.Length - 1 ]; Array.Copy(args, 1, function, 0, function.Length); sender.Send(AccountRegistration.Instance.AccountMod(args[0], function)); } } #endregion #region 'Staff' Commands [AllowCondition("LothStaff", AccountPriv.GM, AllowConditionUsage.GreaterThanOrEqual, AllowConditionTarget.User)] [ChannelCommand("!recon", Channels = new string[] {"#wp.uostaff", "#bob.bot", "#jockers" })] private void ReconCommand(NetworkChannel chan, NetworkUser user, string[] args) { // if (!m_SphereAuth.IsStaff(user)) // return; // if (m_SphereAuth.GetStaffPriv(user) < AccountPriv.GM) // return; if (m_Server.IsConnected) m_Server.Disconnect(); if (args.Length <= 0) m_Server.Connect(IPAddress.Parse(m_Config.Address), m_Config.Port); else m_Server.Connect(IPAddress.Parse(args[0]), m_Config.Port); } [AllowCondition("LothStaff", AccountPriv.GM, AllowConditionUsage.GreaterThanOrEqual, AllowConditionTarget.User)] [ChannelCommand("!discon", Channels = new string[] {"#wp.uostaff", "#bob.bot", "#jockers" })] private void DisconCommand(NetworkChannel chan, NetworkUser user, string[] args) { // if (!m_SphereAuth.IsStaff(user)) // return; // if (m_SphereAuth.GetStaffPriv(user) < AccountPriv.GM) // return; if (m_Server.IsConnected) m_Server.Disconnect(); else Kernel.Instance.Network.SendChannelMessage(chan, "Not Connected To Server."); } [AllowCondition("LothStaff", AccountPriv.Admin, AllowConditionUsage.GreaterThanOrEqual, AllowConditionTarget.User)] [ChannelCommand("!resync", Channels = new string[] {"#wp.uostaff", "#bob.bot", "#jockers" })] private void ResyncCommand(NetworkChannel chan, NetworkUser user, string[] args) { // if (!m_SphereAuth.IsStaff(user)) // return; // if (m_SphereAuth.GetStaffPriv(user) < AccountPriv.Admin) // return; m_Server.WriteLine("r"); m_Server.WriteLine("r"); Kernel.Instance.Network.SendChannelMessage(chan, "Done."); } [AllowCondition("LothStaff", AccountPriv.GM, AllowConditionUsage.GreaterThanOrEqual, AllowConditionTarget.User)] [ChannelCommand("!broadcast", Channels = new string[] {"#wp.uostaff", "#bob.bot", "#jockers" })] private void BroadcastCommand(NetworkChannel chan, NetworkUser user, string[] args) { // if (!m_SphereAuth.IsStaff(user)) // return; // if (m_SphereAuth.GetStaffPriv(user) < AccountPriv.GM) // return; if (args.Length < 1) { Kernel.Instance.Network.SendChannelMessage(chan, "You didn't specify a message to send."); return; } string message = ""; foreach (string i in args) message += " " + i; m_Server.WriteLine("b" + message); Kernel.Instance.Network.SendChannelMessage(m_Config.PublicChannel, "Broadcast: {0}", message); Log.WriteLine("Sphere", "Broadcast:{0}", message); } [AllowCondition("LothStaff", AccountPriv.GM, AllowConditionUsage.GreaterThanOrEqual, AllowConditionTarget.User)] [ChannelCommand("!broadcastirc", Channels = new string[] {"#wp.uostaff", "#bob.bot", "#jockers" })] private void BroadcastIrcCommand(NetworkChannel chan, NetworkUser user, string[] args) { // if (!m_SphereAuth.IsStaff(user)) // return; // if (m_SphereAuth.GetStaffPriv(user) < AccountPriv.GM) // return; if (args.Length < 1) { Kernel.Instance.Network.SendChannelMessage(chan, "You didn't specify a message to send."); return; } string message = ""; foreach (string i in args) message += " " + i; Kernel.Instance.Network.SendChannelMessage(m_Config.PublicChannel, "IRC Broadcast: {0}", message); Log.WriteLine("Sphere", "IRC Broadcast:{0}", message); } [AllowCondition("LothStaff", AccountPriv.GM, AllowConditionUsage.GreaterThanOrEqual, AllowConditionTarget.User)] [ChannelCommand("!go", Channels = new string[] {"#wp.uostaff", "#bob.bot", "#jockers" })] private void GoCommand(NetworkChannel chan, NetworkUser user, string[] args) { // if (!m_SphereAuth.IsStaff(user)) // return; // if (m_SphereAuth.GetStaffPriv(user) < AccountPriv.GM) // return; if (args.Length < 2) { Kernel.Instance.Network.SendChannelMessage(chan, "Usage: !Go <uid> <message>"); return; } string message = ""; foreach (string i in args) { if (i != args[0]) message += " " + i; } m_Server.WriteLine("var.lothbot_target={0}", args[0]); m_Server.WriteLine("uid.{0}.respondtoplayer {1}", m_LothBotUid, message.Trim()); } [AllowCondition("LothStaff", AccountPriv.Admin, AllowConditionUsage.GreaterThanOrEqual, AllowConditionTarget.User)] [ChannelCommand("!resyncbot", Channels = new string[] {"#wp.uostaff", "#bob.bot", "#jockers" })] private void ResyncBotCommand(NetworkChannel chan, NetworkUser user, string[] args) { // if (!m_SphereAuth.IsStaff(user)) // return; // if (m_SphereAuth.GetStaffPriv(user) < AccountPriv.Admin) // return; m_Timer.Stop(); m_Timer.Interval = 1; m_Timer.Start(); } [AllowCondition("LothStaff", AccountPriv.GM, AllowConditionUsage.GreaterThanOrEqual)] [PrivateCommand("admin listlog")] private void AdminListLogCommand(NetworkUser user, string[] args) { // if (!m_SphereAuth.IsStaff(user)) // return; // if (m_SphereAuth.GetStaffPriv(user) < AccountPriv.GM) // return; string[] logFiles = Directory.GetFiles(m_Config.LogDirectory, "*.log"); if(logFiles.Length == 0) { user.SendMessage("There are no log files available."); } else { user.SendMessage("The following log files are available:"); foreach(string log in logFiles) user.SendMessage("\t{0}", log); } } [AllowCondition("LothStaff", AccountPriv.Admin, AllowConditionUsage.GreaterThanOrEqual)] [PrivateCommand("addstaff")] private void AddStaffCommand(NetworkUser user, string[] args) { // if (!m_SphereAuth.IsStaff(user)) // return; // if (m_SphereAuth.GetStaffPriv(user) < AccountPriv.Admin) // return; if (args.Length < 1) { user.SendMessage("You must at least provide an account name."); return; } else if (args.Length > 3) { user.SendMessage("Too many arguments provided! (AddStaff <Account> [<Priv>] [<Password>]"); return; } if (!m_Server.IsConnected) { user.SendMessage("Unable to add accounts whilst not connected to the server!"); return; } switch (args.Length) { case 1: { if (m_Accounting.AccountAdd(args[0], AccountPriv.Counselor)) user.SendMessage("Counselor account '{0}' created successfully! Password is '{1}'", args[0], "blah"); else user.SendMessage("Unable to create account!"); return; } case 2: { if (m_Accounting.AccountAdd(args[0], Account.StringToPriv(args[1]))) user.SendMessage("{1} account '{0}' created successfully! Password is '{2}'", args[0], Account.PrivToString(Account.StringToPriv(args[1])), "blah"); else user.SendMessage("Unable to create account!"); return; } case 3: { if (m_Accounting.AccountAdd(args[0], args[2], Account.StringToPriv(args[1]))) user.SendMessage("{2} account '{0}' created successfully! Password is '{2}'", args[0], Account.PrivToString(Account.StringToPriv(args[1])), args[2]); else user.SendMessage("Unable to create account!"); return; } } } #region Jail Commands [PrivateCommand("jail")] private void JailCommand(NetworkUser user, string[] args) { if (args.Length <= 0) { user.SendNotice("Incorrect Usage. (Jail <command> [<arguments>])"); user.SendNotice("Following commands are available to you"); user.SendNotice("Use 'Jail Help <command>' for more information"); user.SendNotice("------------------------------------------------"); user.SendNotice("Jail Info Displays jail entry information"); user.SendNotice("Jail List Displays full list of jailed accounts."); if (m_SphereAuth.IsStaff(user)) { user.SendNotice("Jail Add Jails an account."); if (m_SphereAuth.GetStaffPriv(user) < AccountPriv.GM) return; user.SendNotice("Jail Del Releases an account from jail."); user.SendNotice("Jail Edit Edits an account entry."); if (m_SphereAuth.GetStaffPriv(user) >= AccountPriv.Admin) user.SendNotice("Jail Save Forces the Jail Database to be saved."); } return; } switch (args[0].ToLower()) { case "add": { if (!m_SphereAuth.IsStaff(user)) { user.SendNotice("You cannot use this command."); return; } if (args.Length < 3) { user.SendNotice("Incorrect Arguments: 'Jail Add <Account> <Length> [<Reason>]'"); return; } if (m_JailSystem.IsJailed(args[1])) { user.SendNotice("Account '{0}' is already jailed!", args[1]); return; } string jailargs = ""; for (int i = 3; i < args.Length; i++) jailargs += " " + args[i]; if (m_JailSystem.Jail(args[1], null, user.Nickname, args[2], jailargs.Trim())) user.SendNotice("'{0}' jailed for {1} hours!", args[1], args[2]); else user.SendNotice("Unable to jail '{0}'", args[1]); return; } case "del": { if (!m_SphereAuth.IsStaff(user) || (m_SphereAuth.GetStaffPriv(user) < AccountPriv.GM)) { user.SendNotice("You cannot use this command."); return; } if (args.Length < 2) { user.SendNotice("Incorrect Arguments: 'Jail Del <Account>'"); return; } if (!m_JailSystem.IsJailed(args[1])) { user.SendNotice("Account '{0}' wasn't jailed!", args[1]); return; } if (m_JailSystem.Release(args[1], user.Nickname)) user.SendNotice("'{0}' released!", args[1]); else user.SendNotice("Unable to release '{0}'", args[1]); return; } case "edit": { if (!m_SphereAuth.IsStaff(user) || (m_SphereAuth.GetStaffPriv(user) < AccountPriv.GM)) { user.SendNotice("You cannot use this command."); return; } if (args.Length < 3) { user.SendNotice("Incorrect Arguments: 'Jail Edit <Account> <Length> [<Reason>]'"); return; } if (!m_JailSystem.IsJailed(args[1])) { user.SendNotice("Account '{0}' wasn't jailed!", args[1]); return; } string jailargs = ""; for (int i = 3; i < args.Length; i++) jailargs += " " + args[i]; if (m_JailSystem.EditJail(args[1], user.Nickname, args[2], jailargs.Trim())) user.SendNotice("'{0}'s jail entry is edited!", args[1]); else user.SendNotice("Unable to edit jail entry '{0}'!", args[1]); return; } case "list": { if (m_JailSystem.JailedAccounts <= 0) { user.SendNotice("No Accounts are Jailed!"); return; } foreach (JailEntry entry in m_JailSystem.GetJailEntryList()) { user.SendNotice("Account: {0} Release Date: {1}", entry.Account, entry.JailedUntil.ToString()); } return; } case "info": { if (args.Length < 2) { user.SendNotice("Incorrect Arguments: 'Jail Info <Account>'"); return; } JailEntry entry = m_JailSystem.GetJailEntry(args[1]); if (entry != null) { user.SendNotice("Account: {0}", entry.Account); user.SendNotice("Character: {0}", entry.Character); user.SendNotice("Jailed By: {0}", entry.JailedBy); user.SendNotice("Jail Date: {0}", entry.JailedOn); user.SendNotice("Release Date: {0} ({1})", entry.JailedUntil, entry.TimeLeft); user.SendNotice("Reason: {0}", entry.Reason); } else user.SendNotice("Account '{0}' Not Jailed!", args[1]); return; } case "save": { if (!m_SphereAuth.IsStaff(user) || (m_SphereAuth.GetStaffPriv(user) < AccountPriv.Admin)) { user.SendNotice("You cannot use this command."); return; } if (m_JailSystem.SaveDatabase()) user.SendNotice("Database Saved Successfully."); else user.SendNotice("Database Failed to Save!"); return; } case "help": { if (args.Length < 2) { user.SendNotice("Incorrect Arguments: 'Jail Help <Command>'"); return; } switch (args[1].ToLower()) { case "add": { if (!m_SphereAuth.IsStaff(user)) { user.SendNotice("No help is available for this command."); return; } user.SendNotice("/msg {0} Jail Add <Account> <Length> [<Reason>]", Kernel.Instance.Network.Nickname); user.SendNotice("Adds a new jail database entry for <Account>. The account will"); user.SendNotice("automatically be jailed ingame."); user.SendNotice("The release date will be set <Length> hours after the jail"); user.SendNotice("time, and will automatically released from jail at that time."); user.SendNotice("The <Reason> argument is saved into the database for all users"); user.SendNotice("to view. This is optional and can be left out if not desired."); user.SendNotice("Example: /msg {0} Jail Add myAccount 24", Kernel.Instance.Network.Nickname); user.SendNotice(" /msg {0} Jail Add myAccount 24 Jailed for bug abuse.", Kernel.Instance.Network.Nickname); return; } case "del": { if (!m_SphereAuth.IsStaff(user) || (m_SphereAuth.GetStaffPriv(user) < AccountPriv.GM)) { user.SendNotice("No help is available for this command."); return; } user.SendNotice("/msg {0} Jail Del <Account>", Kernel.Instance.Network.Nickname); user.SendNotice("Deletes the entry for <Account> from the database. The account"); user.SendNotice("will automatically released ingame."); user.SendNotice("Example: /msg {0} Jail Del myAccount", Kernel.Instance.Network.Nickname); return; } case "edit": { if (!m_SphereAuth.IsStaff(user) || (m_SphereAuth.GetStaffPriv(user) < AccountPriv.GM)) { user.SendNotice("No help is available for this command."); return; } user.SendNotice("/msg {0} Jail Edit <Account> <Length> [<Reason>]", Kernel.Instance.Network.Nickname); user.SendNotice("Edits the entry for <Account> in the database, exchanging the"); user.SendNotice("entry's length to <Length> hours."); user.SendNotice("If [<Reason>] is provided then this will also be amended."); user.SendNotice("The 'Jailed By' property of the jail entry will be amended to "); user.SendNotice("indicate that the entry has been amended by another staff"); user.SendNotice("member if that is the case."); user.SendNotice("Example: /msg {0} Jail Edit myAccount 24", Kernel.Instance.Network.Nickname); user.SendNotice(" /msg {0} Jail Edit myAccount 24 Jailed for bug abuse.", Kernel.Instance.Network.Nickname); return; } case "save": { if (!m_SphereAuth.IsStaff(user) || (m_SphereAuth.GetStaffPriv(user) < AccountPriv.Admin)) { user.SendNotice("No help is available for this command."); return; } user.SendNotice("/msg {0} Jail Save", Kernel.Instance.Network.Nickname); user.SendNotice("Forces the Jail Database to be saved immediately. Unsaved jail"); user.SendNotice("entries will result in players not being released if the Bot"); user.SendNotice("is restarted."); user.SendNotice("Example: /msg {0} Jail Save", Kernel.Instance.Network.Nickname); return; } case "list": { user.SendNotice("/msg {0} Jail List", Kernel.Instance.Network.Nickname); user.SendNotice("Displays a list of all the currently jailed accounts, along with"); user.SendNotice("their release dates. For more information on a jail entry, use"); user.SendNotice("Jail Info"); user.SendNotice("Example: /msg {0} Jail List", Kernel.Instance.Network.Nickname); return; } case "info": { user.SendNotice("/msg {0} Jail Info <Account>", Kernel.Instance.Network.Nickname); user.SendNotice("Displays information on <Account>'s jail entry."); user.SendNotice("Example: /msg {0} Jail Info myAccount", Kernel.Instance.Network.Nickname); return; } default: { user.SendNotice("No help is available for this command."); return; } } } default: { user.SendNotice("Unknown Command '{0}'", args[0]); user.SendNotice("Following commands are available to you"); user.SendNotice("Use 'Jail Help <command>' for more information"); user.SendNotice("------------------------------------------------"); user.SendNotice("Jail Info Displays jail entry information"); user.SendNotice("Jail List Displays full list of jailed accounts."); if (m_SphereAuth.IsStaff(user)) { user.SendNotice("Jail Add Jails an account."); if (m_SphereAuth.GetStaffPriv(user) < AccountPriv.GM) return; user.SendNotice("Jail Del Releases an account from jail."); user.SendNotice("Jail Edit Edits an account entry."); if (m_SphereAuth.GetStaffPriv(user) >= AccountPriv.Admin) user.SendNotice("Jail Save Forces the Jail Database to be saved."); } return; } } } #endregion #endregion #region 'Player' Commands [ChannelCommand("!stats")] private void StatsCommand(NetworkChannel chan, NetworkUser user, string[] args) { user.SendNotice("Peak Clients: {0}", SphereConnection.Instance.ClientCount); user.SendNotice("Players Connected: {0}", m_ConnectCount); user.SendNotice("Players Died: {0}", m_KillCount); user.SendNotice("Pages Received: {0}", m_PageCount); user.SendNotice("Commands Issued: {0}", m_ClientCommandsCount); user.SendNotice("World Saves: {0}", m_WorldSaveCount); } [ChannelCommand("!clients")] private void ClientsCommand(NetworkChannel chan, NetworkUser user, string[] args) { Kernel.Instance.Network.SendChannelMessage(chan, String.Format("The current client count is {0}", SphereConnection.Instance.ClientCount)); } [ChannelCommand("!status")] private void StatusCommand(NetworkChannel chan, NetworkUser user, string[] args) { Kernel.Instance.Network.SendChannelMessage(chan, String.Format("Connection Status: {0} ({1}:{2}) - http://{1}:{2}/status.html", (m_Server.IsConnected) ? "Connected" : "Not Connected", m_Config.Address, m_Config.Port)); } [ChannelCommand("!jail")] private void JailCommand(NetworkChannel chan, NetworkUser user, string[] args) { Kernel.Instance.Network.SendChannelMessage(chan, "The Lothlorien Jail List is: http://central.wireplay.co.uk/bans/index.php?game=52"); } [ChannelCommand("!forum")] private void ForumCommand(NetworkChannel chan, NetworkUser user, string[] args) { Kernel.Instance.Network.SendChannelMessage(chan, "Forums for Lothlorien can be found at http://forums.wireplay.co.uk/forumdisplay.php3?forumid=299"); } [ChannelCommand("!url")] private void UrlCommand(NetworkChannel chan, NetworkUser user, string[] args) { Kernel.Instance.Network.SendChannelMessage(chan, "The Lothlorien website can be found at http://Lothlorien.wireplay.co.uk"); } [ChannelCommand("!uoa")] private void UOACommand(NetworkChannel chan, NetworkUser user, string[] args) { Kernel.Instance.Network.SendChannelMessage(chan, "UO Assist Key: tN2qD8,$MEd8,=je,4XrG,V}}9d,2fK]j,[Tu~,TXYK,+r"); } [ChannelCommand("!lastkill")] private void LastKillCommand(NetworkChannel chan, NetworkUser user, string[] args) { string m_Killers = ""; for (int i = 0; i < m_LastKillers.Length; i++) { m_Killers += String.Format(" 5({0}) {1},", (m_LastKillers[i].Type == MobileType.Player? "Player":"Monster"), m_LastKillers[i].Name); } m_Killers = m_Killers.Substring(0, m_Killers.Length - 1); Kernel.Instance.Network.SendChannelMessage(chan, String.Format("12({0}) {1} was killed by {2}", (m_LastVictim.Type == MobileType.Player)? "Player" : "NPC", m_LastVictim.Name, m_Killers.Trim().Length <= 0? m_LastVictim.Name : m_Killers.Trim())); } [ChannelCommand("!peak")] private void PeakCommand(NetworkChannel chan, NetworkUser user, string[] args) { Kernel.Instance.Network.SendChannelMessage(chan, "The peak clients is {0}", m_ClientPeak); } #endregion } } \ No newline at end of file Index: SphereAuth.cs =================================================================== RCS file: /cvsroot/bobbot/Plugins/Sphere/SphereAuth.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** SphereAuth.cs 3 Jan 2005 07:03:19 -0000 1.1 --- SphereAuth.cs 16 Jan 2005 20:07:50 -0000 1.2 *************** *** 1,2 **** --- 1,4 ---- + #region LGPL License /* Bastard of a Bot Library Copyright (C) 2004 Bastard of a Bot Team This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion + using System; using System.Collections; *************** *** 38,42 **** return false; ! return myUser.HasProperty("LothStaff"); } --- 40,50 ---- return false; ! if (!myUser.HasProperty("LothStaff")) ! return false; ! ! if (((AccountPriv)myUser.GetProperty("LothStaff")) >= AccountPriv.Counselor) ! return true; ! ! return false; } *************** *** 46,50 **** return false; ! return m_DataStore.GetUser(user).HasProperty("LothStaff"); } --- 54,69 ---- return false; ! User myUser = m_DataStore.GetUser(user); ! ! if (myUser == null) ! return false; ! ! if (!myUser.HasProperty("LothStaff")) ! return false; ! ! if (((AccountPriv)myUser.GetProperty("LothStaff")) >= AccountPriv.Counselor) ! return true; ! ! return false; } |
From: Mr S. C. <mrs...@us...> - 2005-01-16 20:08:00
|
Update of /cvsroot/bobbot/Plugins/Sphere/Accounting In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv15947/Sphere/Accounting Modified Files: Account.cs Log Message: Reversed the order of Accounting.AccountPriv enum. Added extra checks in to ensure users are staff. Added AllowCondition attributes to commands Index: Account.cs =================================================================== RCS file: /cvsroot/bobbot/Plugins/Sphere/Accounting/Account.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** Account.cs 2 Jan 2005 02:51:59 -0000 1.1 --- Account.cs 16 Jan 2005 20:07:49 -0000 1.2 *************** *** 26,37 **** public enum AccountPriv { ! Owner, ! Admin, ! DevGM, ! GM, ! Seer, ! Counselor, Player, ! None } --- 26,37 ---- public enum AccountPriv { ! None, Player, ! Counselor, ! Seer, ! GM, ! DevGM, ! Admin, ! Owner } |
From: Iain M. <iai...@us...> - 2005-01-16 03:17:30
|
Update of /cvsroot/bobbot/Bob/Core/Irc/Messages/Commands In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv31466/Core/Irc/Messages/Commands Removed Files: JoinChannelMessage.cs Log Message: Removal of old file. --- JoinChannelMessage.cs DELETED --- |
From: Iain M. <iai...@us...> - 2005-01-16 03:16:33
|
Update of /cvsroot/bobbot/Bob/Core/Irc In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv31224/Core/Irc Modified Files: NetworkChannel.cs NetworkConnection.cs NetworkUser.cs Log Message: Too many changes to list. The most important change is the new style for defining command handlers. A command handler can now have variable arguments and of variable types, the kernel will automatically convert the text arguments to what you expect. Such an example is: public void MyTestCommand(NetworkChannel chan, NetworkUser user, string userName, bool enableAccount); This would cause the kernel to convert the second argument to a bool. You can also have a catchall argument to catch any extra arguments typed by the user, this is just a string array: public void MyTestCommand(NetworkChannel chan, NetworkUser user, string userName, bool enableAccount, string[] args); --------------------------------------- The NetworkConnection now tracks users across joins, parts, etc. It does not however track mode changes at the moment. NetworkUser and NetworkChannel have events associated with them. --------------------------------------- Check the diffs for full change details. Index: NetworkChannel.cs =================================================================== RCS file: /cvsroot/bobbot/Bob/Core/Irc/NetworkChannel.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** NetworkChannel.cs 4 Jan 2005 21:05:32 -0000 1.2 --- NetworkChannel.cs 16 Jan 2005 03:16:21 -0000 1.3 *************** *** 22,27 **** using System; ! using Bot.Core.Irc.Collections; using Bot.Core.Irc.Exceptions; namespace Bot.Core.Irc --- 22,29 ---- using System; ! using Bot.Core.Irc; ! using Bot.Core.Irc.Messages; using Bot.Core.Irc.Exceptions; + using Bot.Core.Irc.Collections; namespace Bot.Core.Irc *************** *** 33,48 **** { #region Public properties public string Name { get { return m_Name; } - set - { - if(!IrcHelper.IsValidChannelName(value)) - throw new InvalidChannelNameException(value); - - m_Name = value; - } } public string Key { --- 35,49 ---- { #region Public properties + /// <summary> + /// Gets the channel name. + /// </summary> public string Name { get { return m_Name; } } + /// <summary> + /// Gets the channel key, if any is set. + /// </summary> public string Key { *************** *** 51,54 **** --- 52,58 ---- } + /// <summary> + /// Gets the list of users currently on this channel. + /// </summary> public UserCollection Users { *************** *** 63,66 **** --- 67,79 ---- #endregion + #region Events + /// <summary>Raised when a name reply is received for this channel.</summary> + public event NameReplyEventHandler NameReply; + /// <summary>Raised when a user joins this channel.</summary> + public event JoinMessageEventHandler UserJoined; + /// <summary>Raised when a user leaves this channel.</summary> + public event PartMessageEventHandler UserParted; + #endregion + #region Constructor internal NetworkChannel(string name) *************** *** 72,79 **** --- 85,99 ---- m_Key = ""; m_Users = new UserCollection(); + + Kernel.Instance.Network.Join += new JoinMessageEventHandler(OnJoinChannel); + Kernel.Instance.Network.Part += new PartMessageEventHandler(OnPartChannel); + Kernel.Instance.Network.NameReply += new NameReplyEventHandler(OnNameReply); } #endregion #region Public methods + /// <summary> + /// Causes the bot to join this channel. + /// </summary> public void Join() { *************** *** 81,84 **** --- 101,107 ---- } + /// <summary> + /// Causes the bot to leave this channel. + /// </summary> public void Part() { *************** *** 86,89 **** --- 109,117 ---- } + /// <summary> + /// Sends a message to the channel. + /// </summary> + /// <param name="format">Message format.</param> + /// <param name="args">Message arguments.</param> public void SendMessage(string format, params object[] args) { *************** *** 91,94 **** --- 119,126 ---- } + /// <summary> + /// Overriden to return the channel name. + /// </summary> + /// <returns></returns> public override string ToString() { *************** *** 96,99 **** --- 128,161 ---- } #endregion + + #region Event handlers + private void OnJoinChannel(NetworkConnection sender, JoinMessageEventArgs args) + { + m_Users.Add(args.Message.From); + + if(UserJoined != null) + UserJoined(sender, args); + } + + private void OnPartChannel(NetworkConnection sender, PartMessageEventArgs args) + { + m_Users.Remove(args.Message.From); + + if(UserParted != null) + UserParted(sender, args); + } + + private void OnNameReply(NetworkConnection sender, NameReplyEventArgs args) + { + foreach(NetworkUser user in args.Message.Users) + { + if(m_Users.Contains(user.Nickname) == false) + m_Users.Add(user); + } + + if(NameReply != null) + NameReply(sender, args); + } + #endregion } } Index: NetworkConnection.cs =================================================================== RCS file: /cvsroot/bobbot/Bob/Core/Irc/NetworkConnection.cs,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** NetworkConnection.cs 12 Jan 2005 01:47:24 -0000 1.8 --- NetworkConnection.cs 16 Jan 2005 03:16:21 -0000 1.9 *************** *** 233,236 **** --- 233,238 ---- public event DisconnectedEventHandler Disconnected; + /// <summary>Raised when a name reply is received.</summary> + public event NameReplyEventHandler NameReply; /// <summary>Raised when we are welcomed onto the server.</summary> public event WelcomeReplyEventHandler Welcome; *************** *** 251,255 **** public event ModeMessageEventHandler ModeChanged; /// <summary>Raised when a user joins a channel.</summary> ! public event JoinChannelMessageEventHandler Join; /// <summary>Raised when we receive a channel message.</summary> public event ChannelMessageEventHandler ChannelMessage; --- 253,257 ---- public event ModeMessageEventHandler ModeChanged; /// <summary>Raised when a user joins a channel.</summary> ! public event JoinMessageEventHandler Join; /// <summary>Raised when we receive a channel message.</summary> public event ChannelMessageEventHandler ChannelMessage; *************** *** 270,282 **** static NetworkConnection() { ! MessageFactory.Instance.Register(typeof(JoinChannelMessage)); MessageFactory.Instance.Register(typeof(PartMessage)); MessageFactory.Instance.Register(typeof(PingMessage)); MessageFactory.Instance.Register(typeof(NickMessage)); ! MessageFactory.Instance.Register(typeof(WelcomeReply)); ! MessageFactory.Instance.Register(typeof(NickInUseReply)); MessageFactory.Instance.Register(typeof(PrivateMessage)); - MessageFactory.Instance.Register(typeof(InternalNoticeMessage)); MessageFactory.Instance.Register(typeof(InternalModeMessage)); } --- 272,287 ---- static NetworkConnection() { ! MessageFactory.Instance.Register(typeof(JoinMessage)); MessageFactory.Instance.Register(typeof(PartMessage)); MessageFactory.Instance.Register(typeof(PingMessage)); MessageFactory.Instance.Register(typeof(NickMessage)); ! MessageFactory.Instance.Register(typeof(QuitMessage)); MessageFactory.Instance.Register(typeof(PrivateMessage)); MessageFactory.Instance.Register(typeof(InternalModeMessage)); + MessageFactory.Instance.Register(typeof(InternalNoticeMessage)); + + MessageFactory.Instance.Register(typeof(NameReply)); + MessageFactory.Instance.Register(typeof(WelcomeReply)); + MessageFactory.Instance.Register(typeof(NickInUseReply)); } *************** *** 583,587 **** throw new ArgumentNullException("key", "key cannot be null"); ! Send(new JoinChannelMessage(dest, key)); } --- 588,592 ---- throw new ArgumentNullException("key", "key cannot be null"); ! Send(new JoinMessage(dest, key)); } *************** *** 607,611 **** throw new ArgumentNullException("key", "key cannot be null"); ! Send(new JoinChannelMessage(dest, key)); } #endregion --- 612,616 ---- throw new ArgumentNullException("key", "key cannot be null"); ! Send(new JoinMessage(dest, key)); } #endregion *************** *** 703,706 **** --- 708,712 ---- private void OnMessageReceivedSync(object sender, MessageReceivedEventArgs args) { + Console.WriteLine(args.Message); if((m_SyncRoot != null) && (m_SyncRoot.InvokeRequired)) m_SyncRoot.BeginInvoke(m_OnMessageReceived, new object[] {this, args}); *************** *** 849,853 **** } ! internal void OnJoinChannel(JoinChannelMessageEventArgs args) { if(IsMe(args.Message.From)) --- 855,859 ---- } ! internal void OnJoinChannel(JoinMessageEventArgs args) { if(IsMe(args.Message.From)) *************** *** 856,863 **** m_Channels.Add(args.Message.Channel); } - else - { - args.Message.From.Channels.Add(args.Message.Channel); - } if(Join != null) --- 862,865 ---- *************** *** 896,907 **** if(IsMe(args.Message.From)) { ! Log.WriteLine("Irc", "Parted {0}", args.Message.Channel.ToString()); ! m_Channels.Remove(args.Message.Channel.Name); ! } ! else ! { ! args.Message.From.Channels.Remove(args.Message.Channel.Name); ! // TODO: If a user parts all channels remove all records of the user. } --- 898,907 ---- if(IsMe(args.Message.From)) { ! NetworkChannel channel = args.Message.Channel; ! Log.WriteLine("Irc", "Parted {0}", channel); ! ! channel.Users.Clear(); ! m_Channels.Remove(channel); } *************** *** 912,918 **** --- 912,935 ---- internal void OnQuit(QuitMessageEventArgs args) { + if(IsMe(args.Message.From)) + { + foreach(NetworkUser user in m_Users) + user.Channels.Clear(); + foreach(NetworkChannel channel in m_Channels) + channel.Users.Clear(); + + m_Users.Clear(); + m_Channels.Clear(); + } + if(Quit != null) Quit(this, args); } + + internal void OnNameReply(NameReplyEventArgs args) + { + if(NameReply != null) + NameReply(this, args); + } #endregion Index: NetworkUser.cs =================================================================== RCS file: /cvsroot/bobbot/Bob/Core/Irc/NetworkUser.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** NetworkUser.cs 30 Dec 2004 03:33:28 -0000 1.2 --- NetworkUser.cs 16 Jan 2005 03:16:21 -0000 1.3 *************** *** 23,26 **** --- 23,27 ---- using System.Text.RegularExpressions; + using Bot.Core.Irc.Messages; using Bot.Core.Irc.Collections; *************** *** 33,36 **** --- 34,40 ---- { #region Public properties + /// <summary> + /// This user's current nick. + /// </summary> public string Nickname { *************** *** 38,41 **** --- 42,48 ---- } + /// <summary> + /// This user's username (ident). + /// </summary> public string Username { *************** *** 43,46 **** --- 50,56 ---- } + /// <summary> + /// This user's real name string. + /// </summary> public string Realname { *************** *** 48,51 **** --- 58,64 ---- } + /// <summary> + /// This user's current host name. + /// </summary> public string Hostname { *************** *** 53,56 **** --- 66,72 ---- } + /// <summary> + /// Gets the list of all channels this user is currently on. + /// </summary> public ChannelCollection Channels { *************** *** 68,71 **** --- 84,98 ---- #endregion + #region Events + /// <summary>Raised when this user joins a channel.</summary> + public event JoinMessageEventHandler Join; + /// <summary>Raised when this user leaves a channel.</summary> + public event PartMessageEventHandler Part; + /// <summary>Raised when this user quits IRC.</summary> + public event QuitMessageEventHandler Quit; + /// <summary>Raised when this user changes their nick.</summary> + public event NickMessageEventHandler NickChanged; + #endregion + #region Constructor internal NetworkUser(string nick) : this(nick, "unknown", "unknown.com") *************** *** 84,91 **** --- 111,128 ---- m_Channels = new ChannelCollection(); + + Kernel.Instance.Network.Join += new JoinMessageEventHandler(OnJoinChannel); + Kernel.Instance.Network.Part += new PartMessageEventHandler(OnPartChannel); + Kernel.Instance.Network.Quit += new QuitMessageEventHandler(OnQuit); + Kernel.Instance.Network.NickChanged += new NickMessageEventHandler(OnNickChanged); } #endregion #region Public methods + /// <summary> + /// Sends this user a private message. + /// </summary> + /// <param name="format">Message format.</param> + /// <param name="args">Message arguments.</param> public void SendMessage(string format, params object[] args) { *************** *** 93,96 **** --- 130,138 ---- } + /// <summary> + /// Sends this user a notice. + /// </summary> + /// <param name="format">Notice format.</param> + /// <param name="args">Notice args.</param> public void SendNotice(string format, params object[] args) { *************** *** 98,101 **** --- 140,147 ---- } + /// <summary> + /// Overriden to provide the user string as seen in raw IRC. + /// </summary> + /// <returns></returns> public override string ToString() { *************** *** 112,115 **** --- 158,207 ---- } #endregion + + #region Event handlers + private void OnJoinChannel(NetworkConnection sender, JoinMessageEventArgs args) + { + if(args.Message.From.Nickname != this.Nickname) + return; + + m_Channels.Add(args.Message.Channel); + + if(Join != null) + Join(sender, args); + } + + private void OnPartChannel(NetworkConnection sender, PartMessageEventArgs args) + { + if(args.Message.From.Nickname != this.Nickname) + return; + + m_Channels.Remove(args.Message.Channel); + + if(Part != null) + Part(sender, args); + } + + private void OnNickChanged(NetworkConnection sender, NickMessageEventArgs args) + { + if(args.Message.From.Nickname != this.Nickname) + return; + + m_Nickname = args.Message.NewNick; + + if(NickChanged != null) + NickChanged(sender, args); + } + + private void OnQuit(NetworkConnection sender, QuitMessageEventArgs args) + { + if(args.Message.From.Nickname != this.Nickname) + return; + + m_Channels.Clear(); + + if(Quit != null) + Quit(sender, args); + } + #endregion #region Static methods |
From: Iain M. <iai...@us...> - 2005-01-16 03:16:33
|
Update of /cvsroot/bobbot/Bob/Core/Irc/Collections In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv31224/Core/Irc/Collections Modified Files: ChannelCollection.cs UserCollection.cs Log Message: Too many changes to list. The most important change is the new style for defining command handlers. A command handler can now have variable arguments and of variable types, the kernel will automatically convert the text arguments to what you expect. Such an example is: public void MyTestCommand(NetworkChannel chan, NetworkUser user, string userName, bool enableAccount); This would cause the kernel to convert the second argument to a bool. You can also have a catchall argument to catch any extra arguments typed by the user, this is just a string array: public void MyTestCommand(NetworkChannel chan, NetworkUser user, string userName, bool enableAccount, string[] args); --------------------------------------- The NetworkConnection now tracks users across joins, parts, etc. It does not however track mode changes at the moment. NetworkUser and NetworkChannel have events associated with them. --------------------------------------- Check the diffs for full change details. Index: ChannelCollection.cs =================================================================== RCS file: /cvsroot/bobbot/Bob/Core/Irc/Collections/ChannelCollection.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** ChannelCollection.cs 9 Dec 2004 19:43:16 -0000 1.1 --- ChannelCollection.cs 16 Jan 2005 03:16:20 -0000 1.2 *************** *** 58,62 **** #region Public methods ! public void Add(NetworkChannel channel) { if(channel == null) --- 58,62 ---- #region Public methods ! internal void Add(NetworkChannel channel) { if(channel == null) *************** *** 66,70 **** } ! public void AddRange(NetworkChannel[] channels) { if(channels == null) --- 66,70 ---- } ! internal void AddRange(NetworkChannel[] channels) { if(channels == null) *************** *** 77,82 **** } } ! public void Remove(string channel) { m_Table.Remove(channel); --- 77,87 ---- } } + + internal void Remove(NetworkChannel channel) + { + m_Table.Remove(channel.Name); + } ! internal void Remove(string channel) { m_Table.Remove(channel); *************** *** 88,109 **** } ! public void Clear() { m_Table.Clear(); } ! public IDictionaryEnumerator GetEnumerator() { ! return m_Table.GetEnumerator(); } #endregion #region Enumerator ! /*public class Enumerator : IDictionaryEnumerator { #region Public properties ! public object Key { ! get { return m_Enumerator.Key; } } #endregion --- 93,114 ---- } ! internal void Clear() { m_Table.Clear(); } ! public IEnumerator GetEnumerator() { ! return new Enumerator(this); } #endregion #region Enumerator ! public class Enumerator : IEnumerator { #region Public properties ! public object Current { ! get { return m_Enumerator.Value; } } #endregion *************** *** 116,120 **** public Enumerator(ChannelCollection collection) { ! m_Enumerator = collection.GetEnumerator(); } #endregion --- 121,125 ---- public Enumerator(ChannelCollection collection) { ! m_Enumerator = collection.m_Table.GetEnumerator(); } #endregion *************** *** 131,135 **** } #endregion ! }*/ #endregion } --- 136,140 ---- } #endregion ! } #endregion } Index: UserCollection.cs =================================================================== RCS file: /cvsroot/bobbot/Bob/Core/Irc/Collections/UserCollection.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** UserCollection.cs 9 Dec 2004 19:43:16 -0000 1.1 --- UserCollection.cs 16 Jan 2005 03:16:20 -0000 1.2 *************** *** 77,80 **** --- 77,85 ---- } } + + internal void Remove(NetworkUser user) + { + m_Table.Remove(user.Nickname); + } internal void Remove(string user) *************** *** 93,109 **** } ! public IDictionaryEnumerator GetEnumerator() { ! return m_Table.GetEnumerator(); } #endregion #region Enumerator ! /*public class Enumerator : IDictionaryEnumerator { #region Public properties ! public object Key { ! get { return m_Enumerator.Key; } } #endregion --- 98,114 ---- } ! public IEnumerator GetEnumerator() { ! return new Enumerator(this); } #endregion #region Enumerator ! public class Enumerator : IEnumerator { #region Public properties ! public object Current { ! get { return m_Enumerator.Value; } } #endregion *************** *** 114,120 **** #region Constructor ! public Enumerator(ChannelCollection collection) { ! m_Enumerator = collection.GetEnumerator(); } #endregion --- 119,125 ---- #region Constructor ! public Enumerator(UserCollection collection) { ! m_Enumerator = collection.m_Table.GetEnumerator(); } #endregion *************** *** 131,135 **** } #endregion ! }*/ #endregion } --- 136,140 ---- } #endregion ! } #endregion } |
From: Iain M. <iai...@us...> - 2005-01-16 03:16:32
|
Update of /cvsroot/bobbot/Bob/Core/Irc/Messages/Replies In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv31224/Core/Irc/Messages/Replies Added Files: NameReply.cs Log Message: Too many changes to list. The most important change is the new style for defining command handlers. A command handler can now have variable arguments and of variable types, the kernel will automatically convert the text arguments to what you expect. Such an example is: public void MyTestCommand(NetworkChannel chan, NetworkUser user, string userName, bool enableAccount); This would cause the kernel to convert the second argument to a bool. You can also have a catchall argument to catch any extra arguments typed by the user, this is just a string array: public void MyTestCommand(NetworkChannel chan, NetworkUser user, string userName, bool enableAccount, string[] args); --------------------------------------- The NetworkConnection now tracks users across joins, parts, etc. It does not however track mode changes at the moment. NetworkUser and NetworkChannel have events associated with them. --------------------------------------- Check the diffs for full change details. --- NEW FILE: NameReply.cs --- #region LGPL License /* Bastard of a Bot Library Copyright (C) 2004 Bastard of a Bot Team This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion using System; using Bot.Core.Irc; using Bot.Core.Irc.Exceptions; using Bot.Core.Irc.Collections; namespace Bot.Core.Irc.Messages { /// <summary> /// Summary description for NameReply. /// </summary> public class NameReply : BaseMessage { #region Public properties public override int NumericReply { get { return 353; } } public NetworkChannel Channel { get{ return ((NetworkChannel) Parameters[2]); } } public UserCollection Users { get { return m_Users; } } #endregion #region Private members private UserCollection m_Users; #endregion #region Constructor public NameReply() : base() { m_Users = new UserCollection(); } #endregion #region Public methods public override void Notify(NetworkConnection toNotify) { toNotify.OnNameReply(new NameReplyEventArgs(this)); } public override bool Parse(string rawMsg) { if(!base.Parse(rawMsg)) return false; Parameters[2] = Kernel.Instance.Network.GetChannel((string) Parameters[2]); string[] users = ((string) Parameters[3]).Split(' '); foreach(string user in users) { string realUser; if(user.StartsWith("@") || user.StartsWith("+")) realUser = user.Substring(1); else realUser = user; m_Users.Add(Kernel.Instance.Network.GetUser(realUser)); } return true; } #endregion } public delegate void NameReplyEventHandler(NetworkConnection network, NameReplyEventArgs args); public class NameReplyEventArgs : EventArgs { #region Public properties public NameReply Message { get { return m_Message; } } #endregion #region Private members private NameReply m_Message; #endregion #region Constructor public NameReplyEventArgs(NameReply message) { m_Message = message; } #endregion } } |
Update of /cvsroot/bobbot/Bob/Core In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv31224/Core Modified Files: AllowConditionAttribute.cs ChannelCommandAttribute.cs Kernel.cs KernelHelper.cs PrivateCommandAttribute.cs RemoteCommandAttribute.cs Added Files: BaseCommandAttribute.cs Log Message: Too many changes to list. The most important change is the new style for defining command handlers. A command handler can now have variable arguments and of variable types, the kernel will automatically convert the text arguments to what you expect. Such an example is: public void MyTestCommand(NetworkChannel chan, NetworkUser user, string userName, bool enableAccount); This would cause the kernel to convert the second argument to a bool. You can also have a catchall argument to catch any extra arguments typed by the user, this is just a string array: public void MyTestCommand(NetworkChannel chan, NetworkUser user, string userName, bool enableAccount, string[] args); --------------------------------------- The NetworkConnection now tracks users across joins, parts, etc. It does not however track mode changes at the moment. NetworkUser and NetworkChannel have events associated with them. --------------------------------------- Check the diffs for full change details. Index: KernelHelper.cs =================================================================== RCS file: /cvsroot/bobbot/Bob/Core/KernelHelper.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** KernelHelper.cs 10 Jan 2005 01:39:55 -0000 1.4 --- KernelHelper.cs 16 Jan 2005 03:16:19 -0000 1.5 *************** *** 60,66 **** public static bool ImplementsSignature(MethodInfo method, Type[] signature) { ParameterInfo[] args = method.GetParameters(); ! if((args.Length > signature.Length) || (args.Length < signature.Length)) return false; --- 60,71 ---- public static bool ImplementsSignature(MethodInfo method, Type[] signature) { + return ImplementsSignature(method, signature, false); + } + + public static bool ImplementsSignature(MethodInfo method, Type[] signature, bool partial) + { ParameterInfo[] args = method.GetParameters(); ! if(((partial != true) && (args.Length > signature.Length)) || ((partial != true) && (args.Length < signature.Length))) return false; Index: RemoteCommandAttribute.cs =================================================================== RCS file: /cvsroot/bobbot/Bob/Core/RemoteCommandAttribute.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RemoteCommandAttribute.cs 10 Jan 2005 01:39:55 -0000 1.2 --- RemoteCommandAttribute.cs 16 Jan 2005 03:16:19 -0000 1.3 *************** *** 26,38 **** namespace Bot.Core { ! [AttributeUsage(AttributeTargets.Method)] ! public class RemoteCommandAttribute : Attribute { #region Public properties - public string Command - { - get { return m_Command; } - } - public bool CaseInsensitive { --- 26,33 ---- namespace Bot.Core { ! [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] ! public class RemoteCommandAttribute : BaseCommandAttribute { #region Public properties public bool CaseInsensitive { *************** *** 40,63 **** set { m_CaseInsensitive = value; } } - - internal IPlugin Plugin - { - get { return m_Plugin; } - set { m_Plugin = value; } - } - - internal MethodInfo Callback - { - get { return m_Callback; } - set { m_Callback = value; } - } #endregion #region Private members - private string m_Command; private bool m_CaseInsensitive; - - private IPlugin m_Plugin; - private MethodInfo m_Callback; #endregion --- 35,42 ---- Index: AllowConditionAttribute.cs =================================================================== RCS file: /cvsroot/bobbot/Bob/Core/AllowConditionAttribute.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** AllowConditionAttribute.cs 10 Jan 2005 01:39:55 -0000 1.1 --- AllowConditionAttribute.cs 16 Jan 2005 03:16:19 -0000 1.2 *************** *** 26,45 **** namespace Bot.Core { public enum AllowConditionUsage { Equals, NotEqual, HasProperty } public enum AllowConditionTarget { Default, Channel, User } ! [AttributeUsage(AttributeTargets.Method)] ! public class AllowConditionAttribute : Attribute { #region Public properties --- 26,70 ---- namespace Bot.Core { + /// <summary> + /// Determines how the property and value will be compaired. + /// </summary> public enum AllowConditionUsage { + /// <summary>Property value is equal to given value.</summary> Equals, + /// <summary>Property value is not equal to the given value.</summary> NotEqual, + /// <summary>Property value is greater than the given value.</summary> + GreaterThan, + /// <summary>Property value is greater than or equal to the given value.</summary> + GreaterThanOrEqual, + /// <summary>Property value is less than the given value.</summary> + LessThan, + /// <summary>Property value is less than or equal to the given value.</summary> + LessThanOrEqual, + /// <summary>Checks to see if the target has the property.</summary> HasProperty } + /// <summary> + /// Determines what will become the target of the condition. + /// </summary> + /// <remarks> + /// The 'Default' target on a <see cref="Bot.Core.ChannelCommandAttribute"/> is a <see cref="Bot.Core.Channel"/>.<p/> + /// The 'Default' target on a <see cref="Bot.Core.PrivateCommandAttribute"/> is a <see cref="Bot.Core.User"/>.<p/> + /// The 'Default' target on a <see cref="Bot.Core.RemoteCommandAttribute"/> is a <see cref="Bot.Core.User"/>. + /// </remarks> public enum AllowConditionTarget { + /// <summary>Default value, target is determined depending on the usage context.</summary> Default, + /// <summary>Target will be a <see cref="Bot.Core.Channel"/>.</summary> Channel, + /// <summary>Target will be a <see cref="Bot.Core.User"/>.</summary> User } ! [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] ! public class AllowConditionAttribute : BaseCommandAttribute { #region Public properties *************** *** 65,80 **** set { m_Target = value; } } - - internal IPlugin Plugin - { - get { return m_Plugin; } - set { m_Plugin = value; } - } - - internal MethodInfo Callback - { - get { return m_Callback; } - set { m_Callback = value; } - } #endregion --- 90,93 ---- *************** *** 84,90 **** private AllowConditionUsage m_Usage; private AllowConditionTarget m_Target; - - private IPlugin m_Plugin; - private MethodInfo m_Callback; #endregion --- 97,100 ---- Index: PrivateCommandAttribute.cs =================================================================== RCS file: /cvsroot/bobbot/Bob/Core/PrivateCommandAttribute.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** PrivateCommandAttribute.cs 10 Jan 2005 01:39:55 -0000 1.3 --- PrivateCommandAttribute.cs 16 Jan 2005 03:16:19 -0000 1.4 *************** *** 26,38 **** namespace Bot.Core { ! [AttributeUsage(AttributeTargets.Method)] ! public class PrivateCommandAttribute : Attribute { #region Public properties - public string Command - { - get { return m_Command; } - } - public bool CaseInsensitive { --- 26,33 ---- namespace Bot.Core { ! [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] ! public class PrivateCommandAttribute : BaseCommandAttribute { #region Public properties public bool CaseInsensitive { *************** *** 40,63 **** set { m_CaseInsensitive = value; } } - - internal IPlugin Plugin - { - get { return m_Plugin; } - set { m_Plugin = value; } - } - - internal MethodInfo Callback - { - get { return m_Callback; } - set { m_Callback = value; } - } #endregion #region Private members - private string m_Command; private bool m_CaseInsensitive; - - private IPlugin m_Plugin; - private MethodInfo m_Callback; #endregion --- 35,42 ---- Index: Kernel.cs =================================================================== RCS file: /cvsroot/bobbot/Bob/Core/Kernel.cs,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** Kernel.cs 12 Jan 2005 01:47:24 -0000 1.8 --- Kernel.cs 16 Jan 2005 03:16:19 -0000 1.9 *************** *** 224,227 **** --- 224,230 ---- Log.WriteLine("Core", "Kernel shutting down..."); + if(reason == "") + reason = "Shutdown request"; + for(int i = 0; i < m_Plugins.Count; i++) m_Plugins[i].Stop(); *************** *** 357,434 **** { if(attrib is ChannelCommandAttribute) ! { ! if(!KernelHelper.ImplementsSignature(method, new Type[] { typeof(NetworkChannel), typeof(NetworkUser), typeof(string[]) })) ! { ! Log.WriteLine("Core", "'{0}' does not implement correct signature for ChannelCommandAttribute", method.Name); ! continue; ! } ! ! ChannelCommandAttribute comAttrib = (ChannelCommandAttribute) attrib; ! string comStr = comAttrib.Command.ToLower(); ! ! if(method.IsStatic == false) ! comAttrib.Plugin = plugin; ! ! comAttrib.Callback = method; ! ! if(m_ChannelCommandHandlers[comStr] == null) ! m_ChannelCommandHandlers[comStr] = new ArrayList(); ! ! ((ArrayList) m_ChannelCommandHandlers[comStr]).Add(comAttrib); ! } else if(attrib is PrivateCommandAttribute) ! { ! if(!KernelHelper.ImplementsSignature(method, new Type[] { typeof(NetworkUser), typeof(string[]) })) ! { ! Log.WriteLine("Core", "'{0}' does not implement correct signature for PrivateCommandAttribute", method.Name); ! continue; ! } ! ! PrivateCommandAttribute comAttrib = (PrivateCommandAttribute) attrib; ! string comStr = comAttrib.Command.ToLower(); ! ! if(method.IsStatic == false) ! comAttrib.Plugin = plugin; ! ! comAttrib.Callback = method; ! ! if(m_PrivateCommandHandlers[comStr] == null) ! m_PrivateCommandHandlers[comStr] = new ArrayList(); ! ! ((ArrayList) m_PrivateCommandHandlers[comStr]).Add(comAttrib); ! } else if(attrib is RemoteCommandAttribute) ! { ! if(!KernelHelper.ImplementsSignature(method, new Type[] { typeof(RemoteConnection), typeof(string[]) } )) ! { ! Log.WriteLine("Core", "'{0}' does not implement correct signature for RemoteCommandAttribute", method.Name); ! continue; ! } ! ! RemoteCommandAttribute comAttrib = (RemoteCommandAttribute) attrib; ! string comStr = comAttrib.Command.ToLower(); ! ! if(method.IsStatic == false) ! comAttrib.Plugin = plugin; ! ! comAttrib.Callback = method; ! ! if(m_RemoteCommandHandlers[comStr] == null) ! m_RemoteCommandHandlers[comStr] = new ArrayList(); ! ! ((ArrayList) m_RemoteCommandHandlers[comStr]).Add(comAttrib); ! } ! else if(attrib is AllowConditionAttribute) ! { ! AllowConditionAttribute comAttrib = (AllowConditionAttribute) attrib; ! ! if(m_MethodAllowConditions[method.GetHashCode()] == null) ! m_MethodAllowConditions[method.GetHashCode()] = new ArrayList(); ! ! ((ArrayList) m_MethodAllowConditions[method.GetHashCode()]).Add(comAttrib); ! } } } } private bool HandlerConditionMet(AllowConditionAttribute condition, Channel target) --- 360,390 ---- { if(attrib is ChannelCommandAttribute) ! AddCommandHandler((BaseCommandAttribute) attrib, plugin, method, m_ChannelCommandHandlers,new Type[] { typeof(NetworkChannel), typeof(NetworkUser) }); else if(attrib is PrivateCommandAttribute) ! AddCommandHandler((BaseCommandAttribute) attrib, plugin, method, m_PrivateCommandHandlers,new Type[] { typeof(NetworkUser) }); else if(attrib is RemoteCommandAttribute) ! AddCommandHandler((BaseCommandAttribute) attrib, plugin, method, m_RemoteCommandHandlers,new Type[] { typeof(RemoteConnection) }); } } } + private void AddCommandHandler(BaseCommandAttribute attrib, IPlugin plugin, MethodInfo method, Hashtable dest, Type[] signature) + { + if(KernelHelper.ImplementsSignature(method, signature, true) == false) + { + Log.WriteLine("Core", "'{0}' does not implement correct signature for {1}", method.Name, attrib.GetType().Name); + return; + } + + if(method.IsStatic == false) + attrib.Plugin = plugin; + + string comStr = attrib.Command.ToLower(); + attrib.Callback = method; + + if(dest[comStr] == null) + dest[comStr] = new ArrayList(); + + ((ArrayList) dest[comStr]).Add(attrib); + } private bool HandlerConditionMet(AllowConditionAttribute condition, Channel target) *************** *** 446,449 **** --- 402,425 ---- conditionMet = true; break; + case AllowConditionUsage.GreaterThan: + if(Comparer.DefaultInvariant.Compare(target.GetProperty(condition.Property), condition.Value) > 0) + conditionMet = true; + break; + case AllowConditionUsage.GreaterThanOrEqual: + int val = Comparer.DefaultInvariant.Compare(target.GetProperty(condition.Property), condition.Value); + + if((val == 0) || (val > 0)) + conditionMet = true; + break; + case AllowConditionUsage.LessThan: + if(Comparer.DefaultInvariant.Compare(target.GetProperty(condition.Property), condition.Value) < 0) + conditionMet = true; + break; + case AllowConditionUsage.LessThanOrEqual: + int lessVal = Comparer.DefaultInvariant.Compare(target.GetProperty(condition.Property), condition.Value); + + if((lessVal == 0) || (lessVal < 0)) + conditionMet = true; + break; case AllowConditionUsage.HasProperty: if(target.HasProperty(condition.Property) == true) *************** *** 469,472 **** --- 445,468 ---- conditionMet = true; break; + case AllowConditionUsage.GreaterThan: + if(Comparer.DefaultInvariant.Compare(target.GetProperty(condition.Property), condition.Value) > 0) + conditionMet = true; + break; + case AllowConditionUsage.GreaterThanOrEqual: + int val = Comparer.DefaultInvariant.Compare(target.GetProperty(condition.Property), condition.Value); + + if((val == 0) || (val > 0)) + conditionMet = true; + break; + case AllowConditionUsage.LessThan: + if(Comparer.DefaultInvariant.Compare(target.GetProperty(condition.Property), condition.Value) < 0) + conditionMet = true; + break; + case AllowConditionUsage.LessThanOrEqual: + int lessVal = Comparer.DefaultInvariant.Compare(target.GetProperty(condition.Property), condition.Value); + + if((lessVal == 0) || (lessVal < 0)) + conditionMet = true; + break; case AllowConditionUsage.HasProperty: if(target.HasProperty(condition.Property) == true) *************** *** 475,481 **** } - Console.WriteLine("Result: {0}", conditionMet); return conditionMet; } #endregion --- 471,531 ---- } return conditionMet; } + + private object[] TransformText(MethodInfo method, string[] args, int offset) + { + ParameterInfo[] methodArgs = method.GetParameters(); + int argCount = methodArgs.Length - offset; + bool hasCatchall = false; + + if(methodArgs[methodArgs.Length - 1].ParameterType == typeof(string[])) + { + hasCatchall = true; + argCount = methodArgs.Length - 1 - offset; + } + + if(argCount > args.Length) + return null; + + object[] myArgs = new object[argCount]; + + for(int i = 0; i < argCount; i++) + { + if(methodArgs[i + offset].ParameterType.IsArray) + return null; + + try + { + TypeConverter cv = TypeDescriptor.GetConverter(methodArgs[i + offset].ParameterType); + + if((cv == null) || (cv.IsValid(args[i]) == false)) + return null; + + myArgs[i] = cv.ConvertFrom(args[i]); + } + catch(Exception) + { + return null; + } + } + + if(hasCatchall == true) + { + string[] overflow = new string[args.Length - argCount]; + object[] tmpArray = new object[myArgs.Length]; + + Array.Copy(myArgs, 0, tmpArray, 0, tmpArray.Length); + myArgs = new object[tmpArray.Length + 1]; + + Array.Copy(tmpArray, 0, myArgs, 0, tmpArray.Length); + myArgs[myArgs.Length - 1] = overflow; + + for(int i = 0; i < overflow.Length; i++) + overflow[i] = args[argCount + i]; + } + + return myArgs; + } #endregion *************** *** 558,568 **** } } ! ! attrib.Callback.Invoke(attrib.Plugin, new object[] { ! args.Message.Channel, ! args.Message.From, ! argList ! } ! ); } } --- 608,628 ---- } } ! ! object[] newArgs = TransformText(attrib.Callback, argList, 2); ! ! if(newArgs == null) ! continue; ! ! object[] tmpArgs = new object[newArgs.Length]; ! ! Array.Copy(newArgs, 0, tmpArgs, 0, tmpArgs.Length); ! newArgs = new object[tmpArgs.Length + 2]; ! ! Array.Copy(tmpArgs, 0, newArgs, 2, tmpArgs.Length); ! newArgs[0] = args.Message.Channel; ! newArgs[1] = args.Message.From; ! ! ! attrib.Callback.Invoke(attrib.Plugin, newArgs); } } *************** *** 617,625 **** } ! attrib.Callback.Invoke(attrib.Plugin, new object[] { ! args.Message.From, ! argList ! } ! ); } } --- 677,695 ---- } ! object[] newArgs = TransformText(attrib.Callback, argList, 1); ! ! if(newArgs == null) ! continue; ! ! object[] tmpArgs = new object[newArgs.Length]; ! ! Array.Copy(newArgs, 0, tmpArgs, 0, tmpArgs.Length); ! newArgs = new object[tmpArgs.Length + 1]; ! ! Array.Copy(tmpArgs, 0, newArgs, 1, tmpArgs.Length); ! newArgs[0] = args.Message.From; ! ! ! attrib.Callback.Invoke(attrib.Plugin, newArgs); } } *************** *** 675,685 **** } ! Console.WriteLine(args.Message); ! ! attrib.Callback.Invoke(attrib.Plugin, new object[] { ! sender, ! argList ! } ! ); validCommand = true; --- 745,763 ---- } ! object[] newArgs = TransformText(attrib.Callback, argList, 1); ! ! if(newArgs == null) ! continue; ! ! object[] tmpArgs = new object[newArgs.Length]; ! ! Array.Copy(newArgs, 0, tmpArgs, 0, tmpArgs.Length); ! newArgs = new object[tmpArgs.Length + 1]; ! ! Array.Copy(tmpArgs, 0, newArgs, 1, tmpArgs.Length); ! newArgs[0] = sender; ! ! ! attrib.Callback.Invoke(attrib.Plugin, newArgs); validCommand = true; --- NEW FILE: BaseCommandAttribute.cs --- using System; using System.Reflection; namespace Bot.Core { /// <summary> /// Summary description for BaseCommanAttribute. /// </summary> public abstract class BaseCommandAttribute : Attribute { #region Properties public string Command { get { return m_Command; } } internal IPlugin Plugin { get { return m_Plugin; } set { m_Plugin = value; } } internal MethodInfo Callback { get { return m_Callback; } set { m_Callback = value; } } #endregion #region Private properties protected string m_Command; private IPlugin m_Plugin; private MethodInfo m_Callback; #endregion #region Constructor public BaseCommandAttribute() { } #endregion } } Index: ChannelCommandAttribute.cs =================================================================== RCS file: /cvsroot/bobbot/Bob/Core/ChannelCommandAttribute.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** ChannelCommandAttribute.cs 10 Jan 2005 01:39:55 -0000 1.3 --- ChannelCommandAttribute.cs 16 Jan 2005 03:16:19 -0000 1.4 *************** *** 28,40 **** namespace Bot.Core { ! [AttributeUsage(AttributeTargets.Method)] ! public class ChannelCommandAttribute : Attribute { ! #region Public properties ! public string Command ! { ! get { return m_Command; } ! } ! public string[] Channels { --- 28,35 ---- namespace Bot.Core { ! [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] ! public class ChannelCommandAttribute : BaseCommandAttribute { ! #region Public properties public string[] Channels { *************** *** 48,72 **** set { m_CaseInsensitive = value; } } - - internal IPlugin Plugin - { - get { return m_Plugin; } - set { m_Plugin = value; } - } - - internal MethodInfo Callback - { - get { return m_Callback; } - set { m_Callback = value; } - } #endregion #region Private members - private string m_Command; private string[] m_Channels; private bool m_CaseInsensitive; - - private IPlugin m_Plugin; - private MethodInfo m_Callback; #endregion --- 43,51 ---- |
From: Iain M. <iai...@us...> - 2005-01-16 03:16:30
|
Update of /cvsroot/bobbot/Bob/Core/Irc/Messages/Commands In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv31224/Core/Irc/Messages/Commands Added Files: JoinMessage.cs Log Message: Too many changes to list. The most important change is the new style for defining command handlers. A command handler can now have variable arguments and of variable types, the kernel will automatically convert the text arguments to what you expect. Such an example is: public void MyTestCommand(NetworkChannel chan, NetworkUser user, string userName, bool enableAccount); This would cause the kernel to convert the second argument to a bool. You can also have a catchall argument to catch any extra arguments typed by the user, this is just a string array: public void MyTestCommand(NetworkChannel chan, NetworkUser user, string userName, bool enableAccount, string[] args); --------------------------------------- The NetworkConnection now tracks users across joins, parts, etc. It does not however track mode changes at the moment. NetworkUser and NetworkChannel have events associated with them. --------------------------------------- Check the diffs for full change details. --- NEW FILE: JoinMessage.cs --- #region LGPL License /* Bastard of a Bot Library Copyright (C) 2004 Bastard of a Bot Team This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion using System; using Bot.Core; using Bot.Core.Irc; using Bot.Core.Irc.Exceptions; namespace Bot.Core.Irc.Messages { /// <summary> /// Summary description for ChannelMessage. /// </summary> public class JoinMessage : BaseMessage { #region Public properties public override string Command { get { return "JOIN"; } } public NetworkChannel Channel { get { return m_Channel; } set { Parameters[0] = value.Name; m_Channel = value; } } public string Key { get { return ((string) Parameters[1]); } set { Parameters[1] = value; } } #endregion #region Private members private NetworkChannel m_Channel; #endregion #region Constructors public JoinMessage() : base() { } public JoinMessage(string dest) : this(dest, "") { } public JoinMessage(NetworkChannel dest) : this(dest, "") { } public JoinMessage(string dest, string key) : this(Kernel.Instance.Network.GetChannel(dest), key) { } public JoinMessage(NetworkChannel dest, string key) : base() { Parameters.Add(dest.Name); Parameters.Add(key); m_Channel = dest; } #endregion #region Public methods public override void Notify(NetworkConnection toNotify) { toNotify.OnJoinChannel(new JoinMessageEventArgs(this)); } public override bool Parse(string rawMsg) { if(!base.Parse(rawMsg)) return false; m_Channel = Kernel.Instance.Network.GetChannel((string) Parameters[0]); return true; } #endregion } public delegate void JoinMessageEventHandler(NetworkConnection network, JoinMessageEventArgs args); public class JoinMessageEventArgs : EventArgs { #region Public properties public JoinMessage Message { get { return m_Message; } } #endregion #region Channel members private JoinMessage m_Message; #endregion #region Constructor public JoinMessageEventArgs(JoinMessage message) { m_Message = message; } #endregion } } |
From: Iain M. <iai...@us...> - 2005-01-16 01:24:12
|
Update of /cvsroot/bobbot/Plugins/Sphere/Messages In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10360/Sphere/Messages Modified Files: PlayerJailedMessage.cs PlayerReleasedMessage.cs Log Message: CVS client missed updating these files. Index: PlayerReleasedMessage.cs =================================================================== RCS file: /cvsroot/bobbot/Plugins/Sphere/Messages/PlayerReleasedMessage.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** PlayerReleasedMessage.cs 4 Jan 2005 05:21:43 -0000 1.1 --- PlayerReleasedMessage.cs 16 Jan 2005 01:24:00 -0000 1.2 *************** *** 27,30 **** --- 27,33 ---- using Bot.Plugins.Sphere; + using Bot.Other.Sphere; + using Bot.Other.Sphere.Messages; + namespace Bot.Plugins.Sphere.Messages { *************** *** 82,86 **** { if(!CanParse(message)) ! throw new MessageParseException("Cannot parse this message.", message); Match match = m_Regex.Match(message); --- 85,89 ---- { if(!CanParse(message)) ! throw new MessageParserException("Cannot parse this message.", message); Match match = m_Regex.Match(message); *************** *** 97,101 **** public override void Notify(SphereConnection server) { ! server.OnPlayerReleased(new PlayerReleasedEventArgs(this)); } } --- 100,104 ---- public override void Notify(SphereConnection server) { ! server.OnCustomEvent(new PlayerReleasedEventArgs(this)); } } Index: PlayerJailedMessage.cs =================================================================== RCS file: /cvsroot/bobbot/Plugins/Sphere/Messages/PlayerJailedMessage.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** PlayerJailedMessage.cs 4 Jan 2005 05:21:43 -0000 1.1 --- PlayerJailedMessage.cs 16 Jan 2005 01:24:00 -0000 1.2 *************** *** 27,30 **** --- 27,33 ---- using Bot.Plugins.Sphere; + using Bot.Other.Sphere; + using Bot.Other.Sphere.Messages; + namespace Bot.Plugins.Sphere.Messages { *************** *** 94,98 **** { if(!CanParse(message)) ! throw new MessageParseException("Cannot parse this message.", message); Match match = m_Regex.Match(message); --- 97,101 ---- { if(!CanParse(message)) ! throw new MessageParserException("Cannot parse this message.", message); Match match = m_Regex.Match(message); *************** *** 111,115 **** public override void Notify(SphereConnection server) { ! server.OnPlayerJailed(new PlayerJailedEventArgs(this)); } } --- 114,118 ---- public override void Notify(SphereConnection server) { ! server.OnCustomEvent(new PlayerJailedEventArgs(this)); } } |
From: Iain M. <iai...@us...> - 2005-01-12 01:49:08
|
Update of /cvsroot/bobbot/Bob/Storage/Xml In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv28991/Storage/Xml Modified Files: StorageEngine.cs Log Message: The XML Storage Engine now implements the IStore.Shutdown method. Index: StorageEngine.cs =================================================================== RCS file: /cvsroot/bobbot/Bob/Storage/Xml/StorageEngine.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** StorageEngine.cs 3 Jan 2005 05:38:50 -0000 1.4 --- StorageEngine.cs 12 Jan 2005 01:48:57 -0000 1.5 *************** *** 275,280 **** return userCollection; } - #endregion #region Private methods private void SaveUsers() --- 275,286 ---- return userCollection; } + public void Shutdown() + { + Log.WriteLine("Xml", "XML Storage Engine shutting down..."); + Flush(); + } + #endregion + #region Private methods private void SaveUsers() |
From: Iain M. <iai...@us...> - 2005-01-12 01:47:37
|
Update of /cvsroot/bobbot/Bob/Core/RemoteAdmin In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv28743/Core/RemoteAdmin Modified Files: RemoteConnection.cs RemoteService.cs Log Message: Mainly cleanups. The bot will now cleanly shut itself down now, including disconnecting all connection admin, and sending a quit message to IRC. RemoteConnection has been updated to use the Kernel's SyncRoot for synchronizing events. Also, NetworkConnection now resolves hostnames specified for servers and also implements the quit message. New events have also been added to the Kernel and NetworkConnectionl: - Kernel.ShutdownRequest - Raised when a plugin requests the kernel to shutdown, can be cancelled using ShutdownEventArgs.Cancel - Kernel.ShutdownComplete - Raised when the kernel has completed the shutdown phase. - NetworkConnection.Quit - Raised when a user quits IRC. New methods added: - IStore.Shutdown - Shuts the datastore down, what that entails is up to the implementor. - RemoteService.Shutdown - Terminates the remote admin service. - NetworkPump.Flush - Flushes the message queue regardless of penalty implications. - Log.Close - Closes the log file. - Kernel.Shutdown - Shuts the kernel down and all related processes. I think I've covered it all. Index: RemoteService.cs =================================================================== RCS file: /cvsroot/bobbot/Bob/Core/RemoteAdmin/RemoteService.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** RemoteService.cs 10 Jan 2005 01:39:56 -0000 1.3 --- RemoteService.cs 12 Jan 2005 01:47:25 -0000 1.4 *************** *** 96,101 **** conn.MessageReceived += new MessageReceivedEventHandler(OnMessageReceived); ! conn.StartPump(); ! conn.InitiateAuthentication(); m_Listener.BeginAccept(new AsyncCallback(OnAccept), null); --- 96,100 ---- conn.MessageReceived += new MessageReceivedEventHandler(OnMessageReceived); ! conn.Start(); m_Listener.BeginAccept(new AsyncCallback(OnAccept), null); *************** *** 112,115 **** --- 111,122 ---- } } + + public void Shutdown() + { + Log.WriteLine("Admin", "RemoteAdmin shutting down..."); + + for(int i = 0; i < m_Users.Count; i++) + ((RemoteConnection) m_Users[i]).Close(); + } #endregion Index: RemoteConnection.cs =================================================================== RCS file: /cvsroot/bobbot/Bob/Core/RemoteAdmin/RemoteConnection.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RemoteConnection.cs 30 Dec 2004 03:33:28 -0000 1.2 --- RemoteConnection.cs 12 Jan 2005 01:47:25 -0000 1.3 *************** *** 25,28 **** --- 25,29 ---- using System.Threading; using System.Net.Sockets; + using System.ComponentModel; using Bot.Core; *************** *** 37,40 **** --- 38,44 ---- { #region Public properties + /// <summary> + /// Endpoint of the remote connection. + /// </summary> public EndPoint RemoteEndPoint { *************** *** 42,45 **** --- 46,52 ---- } + /// <summary> + /// Status of the connection. + /// </summary> public RemoteConnectionStatus Status { *************** *** 47,50 **** --- 54,63 ---- } + /// <summary> + /// Is this connection accepting messages from the client? + /// </summary> + /// <remarks> + /// Set this to false if you wish to ignore messages sent by the remote client. + /// </remarks> public bool AcceptingMessage { *************** *** 53,60 **** --- 66,84 ---- } + /// <summary> + /// Gets the users <see cref="Bot.Core.User"/> record. + /// </summary> public User Data { get { return m_UserRecord; } } + + /// <summary> + /// Gets the synchronization object for this connection. + /// </summary> + public ISynchronizeInvoke SyncRoot + { + get { return m_SyncRoot; } + } #endregion *************** *** 62,104 **** private Socket m_Socket; private Thread m_Thread; private string m_TempUser; private User m_UserRecord; private bool m_AcceptingMessages; private RemoteConnectionStatus m_Status; #endregion #region Events public event MessageReceivedEventHandler MessageReceived; public event DisconnectedEventHandler Disconnected; public event DisconnectedEventHandler Dropped; public event RemoteConnectionAuthenticatedEventHandler Authenticated; #endregion #region Constructor ! public RemoteConnection(Socket socket) { m_Socket = socket; m_AcceptingMessages = false; m_Status = RemoteConnectionStatus.Authenticating; } #endregion #region Public methods ! public void StartPump() { ! m_Thread = new Thread(new ThreadStart(DataPump)); ! m_Thread.IsBackground = true; ! m_Thread.Start(); ! } ! public void StopPump() ! { ! if(m_Thread != null) ! { ! m_Thread.Abort(); ! m_Thread = null; ! } } ! public void Send(string format, params object[] args) { --- 86,157 ---- private Socket m_Socket; private Thread m_Thread; + private bool m_Connected; private string m_TempUser; private User m_UserRecord; private bool m_AcceptingMessages; + private ISynchronizeInvoke m_SyncRoot; private RemoteConnectionStatus m_Status; + + private bool m_Initialized; + + private MessageReceivedEventHandler m_OnMessageReceived; + private DisconnectedEventHandler m_OnConnectionDropped; + private DisconnectedEventHandler m_OnDisconnected; #endregion #region Events + /// <summary>Raised when a message is received.</summary> public event MessageReceivedEventHandler MessageReceived; + /// <summary>Raised when the client disconnects cleanly.</summary> public event DisconnectedEventHandler Disconnected; + /// <summary>Raised when a client drops unexpectedly.</summary> public event DisconnectedEventHandler Dropped; + /// <summary>Raised once the client has successfully authenticated.</summary> public event RemoteConnectionAuthenticatedEventHandler Authenticated; #endregion #region Constructor ! /// <summary> ! /// Constructor. ! /// </summary> ! /// <param name="socket">Socket to use for communications.</param> ! public RemoteConnection(Socket socket) { + m_SyncRoot = Kernel.Instance.SyncRoot; + m_Socket = socket; + m_Connected = true; m_AcceptingMessages = false; m_Status = RemoteConnectionStatus.Authenticating; + + m_OnConnectionDropped = new DisconnectedEventHandler(OnConnectionDropped); + m_OnMessageReceived = new MessageReceivedEventHandler(OnMessageReceived); + m_OnDisconnected = new DisconnectedEventHandler(OnDisconnected); } #endregion #region Public methods ! /// <summary> ! /// Starts the internal processes. ! /// </summary> ! /// <remarks> ! /// Can only be invoked once. Further calls do nothing. ! /// </remarks> ! public void Start() { ! if(m_Initialized == true) ! return; ! m_Initialized = true; ! ! StartPump(); ! InitiateAuthentication(); } ! ! /// <summary> ! /// Sends the specified message to the remote client. ! /// </summary> ! /// <param name="format">Format string.</param> ! /// <param name="args">Arguments.</param> public void Send(string format, params object[] args) { *************** *** 110,198 **** m_Socket.BeginSend(toSend, 0, toSend.Length, SocketFlags.None, null, null); } ! ! public void InitiateAuthentication() ! { ! m_AcceptingMessages = true; ! ! Send("Please enter a username:"); ! } ! public void Close() ! { if(m_Socket != null) { ! if(Disconnected != null) ! Disconnected(this, new DisconnectedEventArgs("Connection terminated")); m_Socket.Shutdown(SocketShutdown.Both); m_Socket.Close(); m_Socket = null; } - - StopPump(); } #endregion #region Private methods private void DataPump() { string msgBuffer = ""; ! while(Thread.CurrentThread.IsAlive == true) { ! byte[] buffer = new byte[1]; ! ! try { ! int numBytes = m_Socket.Receive(buffer, 0, buffer.Length, SocketFlags.None); ! if(numBytes != 0) { ! if(buffer[0] == '\n') { ! if((msgBuffer == "") || (m_AcceptingMessages == false)) ! continue; ! ! if(Status != RemoteConnectionStatus.Authenticating) { - if(MessageReceived != null) - MessageReceived(this, new MessageReceivedEventArgs((string) msgBuffer.Clone())); } else { ! HandleMessageInternally((string) msgBuffer.Clone()); } - - msgBuffer = ""; - } - else if(buffer[0] == '\r') - { } else { ! msgBuffer += (char) buffer[0]; } ! } ! else ! { ! if(Dropped != null) ! Dropped(this, new DisconnectedEventArgs("Connection lost")); ! ! break; ! } ! } ! catch(SocketException ex) ! { ! if(ex.NativeErrorCode == 10054) { ! if(Dropped != null) ! Dropped(this, new DisconnectedEventArgs("Connection lost")); ! break; } } } } private void HandleMessageInternally(string message) { --- 163,324 ---- m_Socket.BeginSend(toSend, 0, toSend.Length, SocketFlags.None, null, null); } ! ! /// <summary> ! /// Terminates the connection to the remote client. ! /// </summary> public void Close() ! { if(m_Socket != null) { ! OnDisconnectedSync(this, new DisconnectedEventArgs("Connection terminated")); m_Socket.Shutdown(SocketShutdown.Both); m_Socket.Close(); + m_Connected = false; + + StopPump(); + m_Socket = null; } } #endregion #region Private methods + private void StartPump() + { + if(m_Thread != null) + return; + + m_Thread = new Thread(new ThreadStart(DataPump)); + m_Thread.IsBackground = true; + m_Thread.Start(); + } + + private void StopPump() + { + if(m_Thread != null) + { + m_Thread.Abort(); + m_Thread.Join(); + m_Thread = null; + } + } + + private void InitiateAuthentication() + { + m_AcceptingMessages = true; + + Send("Please enter a username:"); + } + private void DataPump() { string msgBuffer = ""; ! try { ! while(Thread.CurrentThread.IsAlive == true) { ! byte[] buffer = new byte[1]; ! try { ! int numBytes = m_Socket.Receive(buffer, 0, buffer.Length, SocketFlags.None); ! ! if(numBytes != 0) { ! if(buffer[0] == '\n') ! { ! if((msgBuffer == "") || (m_AcceptingMessages == false)) ! continue; ! ! OnMessageReceivedSync(this, new MessageReceivedEventArgs((string) msgBuffer.Clone())); ! msgBuffer = ""; ! } ! else if(buffer[0] == '\r') { } else { ! msgBuffer += (char) buffer[0]; } } else { ! OnConnectionDroppedSync(this, new DisconnectedEventArgs("Connection lost")); ! break; } ! } ! catch(SocketException ex) { ! if(ex.NativeErrorCode == 10054) ! { ! OnConnectionDroppedSync(this, new DisconnectedEventArgs("Connection lost")); ! break; ! } } } } + catch(ThreadAbortException) + { + Thread.ResetAbort(); + } } + + private void OnMessageReceivedSync(object sender, MessageReceivedEventArgs args) + { + if((m_SyncRoot != null) && (m_SyncRoot.InvokeRequired)) + m_SyncRoot.BeginInvoke(m_OnMessageReceived, new object[] { this, args }); + else + OnMessageReceived(this, args); + } + + private void OnConnectionDroppedSync(object sender, DisconnectedEventArgs args) + { + if((m_SyncRoot != null) && (m_SyncRoot.InvokeRequired)) + m_SyncRoot.BeginInvoke(m_OnConnectionDropped, new object[] { this, args }); + else + OnConnectionDropped(this, args); + } + + private void OnDisconnectedSync(object sender, DisconnectedEventArgs args) + { + if((m_SyncRoot != null) && (m_SyncRoot.InvokeRequired)) + m_SyncRoot.BeginInvoke(m_OnDisconnected, new object[] { this, args }); + else + OnDisconnected(this, args); + } + + private void OnMessageReceived(object sender, MessageReceivedEventArgs args) + { + if(Status != RemoteConnectionStatus.Authenticating) + { + if(MessageReceived != null) + MessageReceived(this, args); + } + else + { + HandleMessageInternally(args.Message); + } + + } + + private void OnConnectionDropped(object sender, DisconnectedEventArgs args) + { + if(m_Connected == false) + return; + + if(Dropped != null) + Dropped(this, args); + } + + private void OnDisconnected(object sender, DisconnectedEventArgs args) + { + if(Disconnected != null) + Disconnected(this, args); + } + private void HandleMessageInternally(string message) { |
From: Iain M. <iai...@us...> - 2005-01-12 01:47:36
|
Update of /cvsroot/bobbot/Bob/Core In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv28743/Core Modified Files: Channel.cs IStore.cs Kernel.cs Log.cs Log Message: Mainly cleanups. The bot will now cleanly shut itself down now, including disconnecting all connection admin, and sending a quit message to IRC. RemoteConnection has been updated to use the Kernel's SyncRoot for synchronizing events. Also, NetworkConnection now resolves hostnames specified for servers and also implements the quit message. New events have also been added to the Kernel and NetworkConnectionl: - Kernel.ShutdownRequest - Raised when a plugin requests the kernel to shutdown, can be cancelled using ShutdownEventArgs.Cancel - Kernel.ShutdownComplete - Raised when the kernel has completed the shutdown phase. - NetworkConnection.Quit - Raised when a user quits IRC. New methods added: - IStore.Shutdown - Shuts the datastore down, what that entails is up to the implementor. - RemoteService.Shutdown - Terminates the remote admin service. - NetworkPump.Flush - Flushes the message queue regardless of penalty implications. - Log.Close - Closes the log file. - Kernel.Shutdown - Shuts the kernel down and all related processes. I think I've covered it all. Index: Log.cs =================================================================== RCS file: /cvsroot/bobbot/Bob/Core/Log.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** Log.cs 23 Dec 2004 22:56:11 -0000 1.3 --- Log.cs 12 Jan 2005 01:47:24 -0000 1.4 *************** *** 37,40 **** --- 37,43 ---- public static void Init() { + if(m_Stream != null) + return; + m_Stream = new StreamWriter("Bot.log"); m_Stream.AutoFlush = true; *************** *** 43,46 **** --- 46,58 ---- } + public static void Close() + { + if(m_Stream == null) + return; + + m_Stream.Close(); + m_Stream = null; + } + public static void Write(string log) { *************** *** 53,59 **** string logLine = String.Format("[{0}] {1}", DateTime.Now.ToLongTimeString(), log); - m_Stream.Write(logLine); Console.Write(logLine); Kernel.Instance.RemoteAdmin.Broadcast(log); } --- 65,73 ---- string logLine = String.Format("[{0}] {1}", DateTime.Now.ToLongTimeString(), log); Console.Write(logLine); Kernel.Instance.RemoteAdmin.Broadcast(log); + + if(m_Stream != null) + m_Stream.Write(logLine); } *************** *** 64,69 **** Console.WriteLine(logLine); - m_Stream.WriteLine(logLine); Kernel.Instance.RemoteAdmin.Broadcast(log); } #endregion --- 78,85 ---- Console.WriteLine(logLine); Kernel.Instance.RemoteAdmin.Broadcast(log); + + if(m_Stream != null) + m_Stream.WriteLine(logLine); } #endregion Index: Kernel.cs =================================================================== RCS file: /cvsroot/bobbot/Bob/Core/Kernel.cs,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** Kernel.cs 10 Jan 2005 01:39:55 -0000 1.7 --- Kernel.cs 12 Jan 2005 01:47:24 -0000 1.8 *************** *** 45,48 **** --- 45,51 ---- private static Kernel m_Instance; + /// <summary> + /// Gets the main instance of the Kernel. + /// </summary> public static Kernel Instance { *************** *** 50,53 **** --- 53,59 ---- } + /// <summary> + /// Constructor. + /// </summary> static Kernel() { *************** *** 57,60 **** --- 63,69 ---- #region Public properties + /// <summary> + /// Gets the kernel's synchronization object. + /// </summary> public ISynchronizeInvoke SyncRoot { *************** *** 62,65 **** --- 71,77 ---- } + /// <summary> + /// Gets a list of all currently loaded plugins. + /// </summary> public PluginCollection Plugins { *************** *** 67,70 **** --- 79,85 ---- } + /// <summary> + /// Gets the <see cref="Bot.Core.IStore"/> for this instance. + /// </summary> public IStore DataStore { *************** *** 72,75 **** --- 87,93 ---- } + /// <summary> + /// Gets the kernel's configuration object. + /// </summary> public CoreConfig Config { *************** *** 77,80 **** --- 95,101 ---- } + /// <summary> + /// Gets the <see cref="Bot.Core.Irc.NetworkConnection"/> for this instance. + /// </summary> public NetworkConnection Network { *************** *** 82,85 **** --- 103,109 ---- } + /// <summary> + /// Gets the <see cref="Bot.Core.RemoteAdmin.RemoteAdminService"/> for this instance. + /// </summary> public RemoteAdminService RemoteAdmin { *************** *** 105,114 **** --- 129,148 ---- #region Events + /// <summary>Raised when a kernel shutdown is requested.</summary> + public event ShutdownEventHandler ShutdownRequest; + /// <summary>Raised when the kernel has completely shutdown.</summary> + public event ShutdownEventHandler ShutdownComplete; + /// <summary>Raised when a plugin is loaded.</summary> public event PluginLoadedEventHandler PluginLoaded; + /// <summary>Raised when a plugin is unloaded.</summary> public event PluginUnloadedEventHandler PluginUnloaded; + /// <summary>Raised when all plugins have been loaded.</summary> public event PluginLoadingCompleteEventHandler PluginLoadingComplete; #endregion #region Constructor + /// <summary> + /// Constructor. + /// </summary> public Kernel() { *************** *** 117,120 **** --- 151,162 ---- #region Public methods + /// <summary> + /// Initializes the kernel. + /// </summary> + /// <remarks> + /// This MUST be called prior to accessing any of the object's property or calling <see cref="Bot.Core.Kernel.Run"/>. + /// It initializes the IRC connection, remote admin and other such components. + /// </remarks> + /// <returns>True on successfully initialization.</returns> public bool Init() { *************** *** 156,159 **** --- 198,204 ---- } + /// <summary> + /// Tells the kernel to start all major services. + /// </summary> public void Run() { *************** *** 161,167 **** m_RemoteAdmin.Begin(m_Config.AdminPort); } #endregion ! #region Private methods private void LoadStorageSolution() { --- 206,252 ---- m_RemoteAdmin.Begin(m_Config.AdminPort); } + + public void Shutdown() + { + Shutdown("Shutdown Request"); + + } + public void Shutdown(string reason) + { + ShutdownEventArgs args = new ShutdownEventArgs(reason); + + if(ShutdownRequest != null) + ShutdownRequest(this, args); + + if(args.Cancel == true) + return; + + Log.WriteLine("Core", "Kernel shutting down..."); + + for(int i = 0; i < m_Plugins.Count; i++) + m_Plugins[i].Stop(); + + m_ChannelCommandHandlers.Clear(); + m_PrivateCommandHandlers.Clear(); + m_RemoteCommandHandlers.Clear(); + + if(m_Network != null) m_Network.Disconnect(reason); + if(m_RemoteAdmin != null) m_RemoteAdmin.Shutdown(); + if(m_DataStore != null) m_DataStore.Shutdown(); + + m_Network = null; + m_DataStore = null; + m_Disposed = true; + + m_Plugins.Clear(); + + Log.Close(); + + if(ShutdownComplete != null) + ShutdownComplete(this, new ShutdownEventArgs("Shutdown Complete")); + } #endregion ! #region Private methods private void LoadStorageSolution() { *************** *** 374,379 **** bool conditionMet = false; - Console.WriteLine("C: {0} V: {1} T: {2}", condition.Property, condition.Value, target.Name); - switch(condition.Usage) { --- 459,462 ---- *************** *** 591,595 **** } } ! attrib.Callback.Invoke(attrib.Plugin, new object[] { --- 674,679 ---- } } ! ! Console.WriteLine(args.Message); attrib.Callback.Invoke(attrib.Plugin, new object[] { *************** *** 629,646 **** if(disposing) ! { ! if(m_Network != null) ! m_Network.Dispose(); ! ! /*if(m_DataStore != null) ! m_DataStore.Dispose();*/ ! ! foreach(IPlugin plugin in m_Plugins) ! plugin.Stop(); ! ! m_Network = null; ! m_DataStore = null; ! m_Disposed = true; ! } } #endregion --- 713,719 ---- if(disposing) ! Shutdown(); ! ! m_Disposed = true; } #endregion *************** *** 651,654 **** --- 724,728 ---- public delegate void PluginUnloadedEventHandler(object sender, PluginUnloadedEventArgs args); public delegate void PluginLoadingCompleteEventHandler(object sender, EventArgs args); + public delegate void ShutdownEventHandler(object sender, ShutdownEventArgs args); public class PluginLoadedEventArgs : System.EventArgs *************** *** 693,696 **** --- 767,802 ---- #endregion } + + public class ShutdownEventArgs : System.EventArgs + { + #region Public properties + public string Reason + { + get { return m_Reason; } + } + + public bool Cancel + { + get { return m_Cancel; } + set { m_Cancel = value; } + } + #endregion + + #region Private members + private string m_Reason; + private bool m_Cancel; + #endregion + + #region Constructor + public ShutdownEventArgs() : this("Shutdown Request") + { + } + + public ShutdownEventArgs(string reason) + { + m_Reason = reason; + } + #endregion + } #endregion } Index: IStore.cs =================================================================== RCS file: /cvsroot/bobbot/Bob/Core/IStore.cs,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** IStore.cs 3 Jan 2005 06:25:24 -0000 1.6 --- IStore.cs 12 Jan 2005 01:47:24 -0000 1.7 *************** *** 35,38 **** --- 35,39 ---- bool Initialize(); + void Shutdown(); void Flush(); Index: Channel.cs =================================================================== RCS file: /cvsroot/bobbot/Bob/Core/Channel.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** Channel.cs 10 Jan 2005 01:39:55 -0000 1.3 --- Channel.cs 12 Jan 2005 01:47:24 -0000 1.4 *************** *** 21,24 **** --- 21,25 ---- using System; + using System.Collections; using Bot.Core.Collections; |
From: Iain M. <iai...@us...> - 2005-01-12 01:47:36
|
Update of /cvsroot/bobbot/Bob/Core/Irc In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv28743/Core/Irc Modified Files: NetworkConnection.cs NetworkPump.cs Log Message: Mainly cleanups. The bot will now cleanly shut itself down now, including disconnecting all connection admin, and sending a quit message to IRC. RemoteConnection has been updated to use the Kernel's SyncRoot for synchronizing events. Also, NetworkConnection now resolves hostnames specified for servers and also implements the quit message. New events have also been added to the Kernel and NetworkConnectionl: - Kernel.ShutdownRequest - Raised when a plugin requests the kernel to shutdown, can be cancelled using ShutdownEventArgs.Cancel - Kernel.ShutdownComplete - Raised when the kernel has completed the shutdown phase. - NetworkConnection.Quit - Raised when a user quits IRC. New methods added: - IStore.Shutdown - Shuts the datastore down, what that entails is up to the implementor. - RemoteService.Shutdown - Terminates the remote admin service. - NetworkPump.Flush - Flushes the message queue regardless of penalty implications. - Log.Close - Closes the log file. - Kernel.Shutdown - Shuts the kernel down and all related processes. I think I've covered it all. Index: NetworkConnection.cs =================================================================== RCS file: /cvsroot/bobbot/Bob/Core/Irc/NetworkConnection.cs,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** NetworkConnection.cs 10 Jan 2005 01:39:55 -0000 1.7 --- NetworkConnection.cs 12 Jan 2005 01:47:24 -0000 1.8 *************** *** 26,29 **** --- 26,30 ---- using System.Configuration; using System.ComponentModel; + using System.Collections.Specialized; using Bot.Core.Events; *************** *** 148,151 **** --- 149,155 ---- } + /// <summary> + /// Synchronization object this connection uses. + /// </summary> public ISynchronizeInvoke SyncRoot { *************** *** 222,245 **** #region Events public event ConnectingEventHandler Connecting; public event ConnectedEventHandler Connected; public event DisconnectedEventHandler Disconnected; public event WelcomeReplyEventHandler Welcome; public event NickInUseReplyEventHandler NickInUse; public event PartMessageEventHandler Part; ! public event PingMessageEventHandler Ping; public event NoticeMessageEventHandler Notice; public event NickMessageEventHandler NickChanged; public event ModeMessageEventHandler ModeChanged; public event JoinChannelMessageEventHandler Join; public event ChannelMessageEventHandler ChannelMessage; public event PrivateMessageEventHandler PrivateMessage; public event MessageReceivedEventHandler MessageReceived; #endregion #region Constructors static NetworkConnection() { --- 226,271 ---- #region Events + /// <summary>Raised when connecting.</summary> public event ConnectingEventHandler Connecting; + /// <summary>Raised when we have connected to the remote host.</summary> public event ConnectedEventHandler Connected; + /// <summary>Raised when we disconnect from the remote host.</summary> public event DisconnectedEventHandler Disconnected; + /// <summary>Raised when we are welcomed onto the server.</summary> public event WelcomeReplyEventHandler Welcome; + /// <summary>Raised when a requested nickname is in use.</summary> public event NickInUseReplyEventHandler NickInUse; + /// <summary>Raised when a channel part occurs.</summary> public event PartMessageEventHandler Part; ! /// <summary>Raised when we receive a ping.</summary> ! public event PingMessageEventHandler Ping; ! /// <summary>Raised when a user quits IRC.</summary> ! public event QuitMessageEventHandler Quit; ! /// <summary>Raised when we receive a notice.</summary> public event NoticeMessageEventHandler Notice; + /// <summary>Raised when a user changes their nickname.</summary> public event NickMessageEventHandler NickChanged; + /// <summary>Raised when a mode change occurs.</summary> public event ModeMessageEventHandler ModeChanged; + /// <summary>Raised when a user joins a channel.</summary> public event JoinChannelMessageEventHandler Join; + /// <summary>Raised when we receive a channel message.</summary> public event ChannelMessageEventHandler ChannelMessage; + /// <summary>Raised when we receive a private message.</summary> public event PrivateMessageEventHandler PrivateMessage; + /// <summary>Raised when we receive a raw message.</summary> public event MessageReceivedEventHandler MessageReceived; #endregion #region Constructors + /// <summary> + /// Constructor. + /// </summary> + /// <remarks> + /// Registers known messages with the <see cref="Bot.Core.Irc.MessageFactory"/>. + /// </remarks> static NetworkConnection() { *************** *** 255,258 **** --- 281,287 ---- } + /// <summary> + /// Constructor. + /// </summary> public NetworkConnection() { *************** *** 265,274 **** m_OnDisconnected = new DisconnectedEventHandler(OnDisconnected); m_OnMessageReceived = new MessageReceivedEventHandler(OnMessageReceived); - - ResolveNetworkNames(); } #endregion #region Public methods public void Connect() { --- 294,304 ---- m_OnDisconnected = new DisconnectedEventHandler(OnDisconnected); m_OnMessageReceived = new MessageReceivedEventHandler(OnMessageReceived); } #endregion #region Public methods + /// <summary> + /// Initiates a connection with a server. + /// </summary> public void Connect() { *************** *** 279,282 **** --- 309,314 ---- return; + ResolveNetworkNames(); + NetworkRegistration reg = new NetworkRegistration(); reg.NetworkAddress = new IPEndPoint(IPAddress.Parse(m_Config.Servers[0].Address), m_Config.Servers[0].Port); *************** *** 296,299 **** --- 328,334 ---- } + /// <summary> + /// Terminates the connection to the server. + /// </summary> public void Disconnect() { *************** *** 301,307 **** throw new ObjectDisposedException("NetworkConnection"); ! Disconnect(""); } public void Disconnect(string reason) { --- 336,346 ---- throw new ObjectDisposedException("NetworkConnection"); ! Disconnect("Bye"); } + /// <summary> + /// Terminates the connection to the server. + /// </summary> + /// <param name="reason">Reason for quiting.</param> public void Disconnect(string reason) { *************** *** 312,318 **** --- 351,365 ---- return; + m_NetworkPump.ClearQueue(); + m_NetworkPump.Enqueue(new QuitMessage(reason)); + m_NetworkPump.Flush(); + OnDisconnectedSync(this, new DisconnectedEventArgs(reason)); } + /// <summary> + /// Sends the given text to the server. + /// </summary> + /// <param name="rawMessage"></param> public void Send(string rawMessage) { *************** *** 323,326 **** --- 370,377 ---- } + /// <summary> + /// Sends the given <see cref="Bot.Core.Irc.Messages.BaseMessage"/> to the server. + /// </summary> + /// <param name="msg"></param> public void Send(BaseMessage msg) { *************** *** 336,339 **** --- 387,395 ---- } + /// <summary> + /// Given a nickname, will return true if it is the bot. + /// </summary> + /// <param name="nick">Nick to check.</param> + /// <returns>True if it is us.</returns> public bool IsMe(string nick) { *************** *** 347,350 **** --- 403,411 ---- } + /// <summary> + /// Given a <see cref="Bot.Core.Irc.NetworkUser"/>, will return true if it is the bot. + /// </summary> + /// <param name="user">User to check.</param> + /// <returns>True if it is us.</returns> public bool IsMe(NetworkUser user) { *************** *** 355,358 **** --- 416,425 ---- } + /// <summary> + /// Sends a message to the given channel. + /// </summary> + /// <param name="dest">Destination channel.</param> + /// <param name="message">Message to send.</param> + /// <param name="args">Message arguments.</param> public void SendChannelMessage(string dest, string message, params object[] args) { *************** *** 365,368 **** --- 432,441 ---- } + /// <summary> + /// Sends a message to the given channel. + /// </summary> + /// <param name="dest">Destination channel.</param> + /// <param name="message">Message to send.</param> + /// <param name="args">Message arguments.</param> public void SendChannelMessage(NetworkChannel dest, string message, params object[] args) { *************** *** 375,378 **** --- 448,457 ---- } + /// <summary> + /// Sends a message to the given user. + /// </summary> + /// <param name="dest">Destination user.</param> + /// <param name="message">Message to send.</param> + /// <param name="args">Message arguments.</param> public void SendPrivateMessage(string dest, string message, params object[] args) { *************** *** 385,388 **** --- 464,473 ---- } + /// <summary> + /// Sends a message to the given user. + /// </summary> + /// <param name="dest">Destination user.</param> + /// <param name="message">Message to send.</param> + /// <param name="args">Message arguments.</param> public void SendPrivateMessage(NetworkUser dest, string message, params object[] args) { *************** *** 395,398 **** --- 480,489 ---- } + /// <summary> + /// Sends a notice to the given user. + /// </summary> + /// <param name="dest">Destination user.</param> + /// <param name="message">Message to send.</param> + /// <param name="args">Message arguments.</param> public void SendNotice(string dest, string message, params object[] args) { *************** *** 405,408 **** --- 496,505 ---- } + /// <summary> + /// Sends a notice to the given user. + /// </summary> + /// <param name="dest">Destination user.</param> + /// <param name="message">Message to send.</param> + /// <param name="args">Message arguments.</param> public void SendNotice(NetworkUser dest, string message, params object[] args) { *************** *** 415,423 **** } public void SendPart(string dest) { SendPart(dest, ""); } ! public void SendPart(NetworkChannel dest) { --- 512,528 ---- } + /// <summary> + /// Sends a part to the given channel. + /// </summary> + /// <param name="dest">Destination channel.</param> public void SendPart(string dest) { SendPart(dest, ""); } ! ! /// <summary> ! /// Sends a part to the given channel. ! /// </summary> ! /// <param name="dest">Destination channel.</param> public void SendPart(NetworkChannel dest) { *************** *** 425,428 **** --- 530,539 ---- } + /// <summary> + /// Sends a part to the given channel. + /// </summary> + /// <param name="dest">Destination channel.</param> + /// <param name="reason">Reason for parting.</param> + /// <param name="args">Reason arguments.</param> public void SendPart(string dest, string reason, params object[] args) { *************** *** 434,438 **** Send(new PartMessage(dest, String.Format(reason, args))); } ! public void SendPart(NetworkChannel dest, string reason, params object[] args) { --- 545,555 ---- Send(new PartMessage(dest, String.Format(reason, args))); } ! ! /// <summary> ! /// Sends a part to the given channel. ! /// </summary> ! /// <param name="dest">Destination channel.</param> ! /// <param name="reason">Reason for parting.</param> ! /// <param name="args">Reason arguments.</param> public void SendPart(NetworkChannel dest, string reason, params object[] args) { *************** *** 445,453 **** } public void SendJoin(string dest) { SendJoin(dest, ""); } ! public void SendJoin(string dest, string key) { --- 562,579 ---- } + /// <summary> + /// Joins the given channel. + /// </summary> + /// <param name="dest">Destination channel.</param> public void SendJoin(string dest) { SendJoin(dest, ""); } ! ! /// <summary> ! /// Joins the given channel. ! /// </summary> ! /// <param name="dest">Destination channel.</param> ! /// <param name="key">Channel key.</param> public void SendJoin(string dest, string key) { *************** *** 460,463 **** --- 586,593 ---- } + /// <summary> + /// Joins the given channel. + /// </summary> + /// <param name="dest">Destination channel.</param> public void SendJoin(NetworkChannel dest) { *************** *** 465,468 **** --- 595,603 ---- } + /// <summary> + /// Joins the given channel. + /// </summary> + /// <param name="dest">Destination channel.</param> + /// <param name="key">Channel key.</param> public void SendJoin(NetworkChannel dest, string key) { *************** *** 479,482 **** --- 614,657 ---- private void ResolveNetworkNames() { + Log.WriteLine("Irc", "Resolving network names..."); + + ArrayList ipAddresses = new ArrayList(); + + for(int i = 0; i < m_Config.Servers.Length; i++) + { + try + { + IPAddress.Parse(m_Config.Servers[i].Address); + ipAddresses.Add(m_Config.Servers[i]); + } + catch(FormatException) + { + try + { + IPHostEntry dnsEntry = Dns.GetHostByName(m_Config.Servers[i].Address); + + if(dnsEntry.AddressList.Length > 1) + { + Log.WriteLine("Irc", "\t{0} -> {1}", + m_Config.Servers[i].Address, dnsEntry.AddressList[0].ToString()); + + m_Config.Servers[i].Address = dnsEntry.AddressList[0].ToString(); + ipAddresses.Add(m_Config.Servers[i]); + } + else + { + Log.WriteLine("Irc", "\t{0} -> {1}", + m_Config.Servers[i].Address, dnsEntry.AddressList[0].ToString()); + + m_Config.Servers[i].Address = dnsEntry.AddressList[0].ToString(); + ipAddresses.Add(m_Config.Servers[i]); + } + } + catch(SocketException) + { + Log.WriteLine("Irc", "\tCould not resolve '{0}'", m_Config.Servers[i].Address); + } + } + } } *************** *** 513,517 **** { if((m_SyncRoot != null) && (m_SyncRoot.InvokeRequired)) ! m_SyncRoot.Invoke(m_OnConnected, new object[] { this, new ConnectedEventArgs() }); else OnConnected(this, new ConnectedEventArgs()); --- 688,692 ---- { if((m_SyncRoot != null) && (m_SyncRoot.InvokeRequired)) ! m_SyncRoot.BeginInvoke(m_OnConnected, new object[] { this, new ConnectedEventArgs() }); else OnConnected(this, new ConnectedEventArgs()); *************** *** 521,525 **** { if((m_SyncRoot != null) && (m_SyncRoot.InvokeRequired)) ! m_SyncRoot.Invoke(m_OnDisconnected, new object[] { this, args }); else OnDisconnected(this, args ); --- 696,700 ---- { if((m_SyncRoot != null) && (m_SyncRoot.InvokeRequired)) ! m_SyncRoot.BeginInvoke(m_OnDisconnected, new object[] { this, args }); else OnDisconnected(this, args ); *************** *** 529,533 **** { if((m_SyncRoot != null) && (m_SyncRoot.InvokeRequired)) ! m_SyncRoot.Invoke(m_OnMessageReceived, new object[] {this, args}); else OnMessageReceived(this, args); --- 704,708 ---- { if((m_SyncRoot != null) && (m_SyncRoot.InvokeRequired)) ! m_SyncRoot.BeginInvoke(m_OnMessageReceived, new object[] {this, args}); else OnMessageReceived(this, args); *************** *** 734,737 **** --- 909,918 ---- Part(this, args); } + + internal void OnQuit(QuitMessageEventArgs args) + { + if(Quit != null) + Quit(this, args); + } #endregion *************** *** 772,775 **** --- 953,959 ---- } + /// <summary> + /// Disposes of critical resources. + /// </summary> public void Dispose() { Index: NetworkPump.cs =================================================================== RCS file: /cvsroot/bobbot/Bob/Core/Irc/NetworkPump.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** NetworkPump.cs 10 Jan 2005 01:39:56 -0000 1.4 --- NetworkPump.cs 12 Jan 2005 01:47:24 -0000 1.5 *************** *** 38,44 **** /// Summary description for NetworkPump. /// </summary> ! internal class NetworkPump : IDisposable { #region Public properties public int MaxPenalty { --- 38,47 ---- /// Summary description for NetworkPump. /// </summary> ! internal class NetworkPump { #region Public properties + /// <summary> + /// Maximum penalty we can occur before buffering occurs. + /// </summary> public int MaxPenalty { *************** *** 46,49 **** --- 49,55 ---- } + /// <summary> + /// Current penalty acrewed. + /// </summary> public int CurrentPenalty { *************** *** 51,54 **** --- 57,63 ---- } + /// <summary> + /// Number of messages still in the queue. + /// </summary> public int MessageCount { *************** *** 70,78 **** --- 79,95 ---- #region Events + /// <summary>Raised when a message is received.</summary> public event MessageReceivedEventHandler MessageReceived; + /// <summary>Raised when we get disconnected.</summary> public event DisconnectedEventHandler Disconnected; #endregion #region Constructor + /// <summary> + /// Constructor. + /// </summary> + /// <param name="network">Parent network connection.</param> + /// <param name="socket">Socket to use for communications.</param> + /// <param name="maxPenalty">Maximum penalty to allow.</param> public NetworkPump(NetworkConnection network, Socket socket, int maxPenalty) : base() { *************** *** 93,96 **** --- 110,116 ---- #region Public methods + /// <summary> + /// Starts the pump. + /// </summary> public void StartPump() { *************** *** 100,109 **** --- 120,136 ---- } + /// <summary> + /// Stops the pump. + /// </summary> public void StopPump() { m_Thread.Abort(); + m_Thread.Join(); m_Thread = null; } + /// <summary> + /// Clears the message queue. + /// </summary> public void ClearQueue() { *************** *** 111,114 **** --- 138,145 ---- } + /// <summary> + /// Adds a new <see cref="Bot.Core.Irc.Messages.BaseMessage"/> to the message queue. + /// </summary> + /// <param name="msg"></param> public void Enqueue(BaseMessage msg) { *************** *** 116,119 **** --- 147,154 ---- } + /// <summary> + /// Removes the first <see cref="Bot.Core.Irc.Messages.BaseMessage"/> from the queue and returns it. + /// </summary> + /// <returns></returns> public BaseMessage Dequeue() { *************** *** 121,124 **** --- 156,163 ---- } + /// <summary> + /// Returns the first <see cref="Bot.Core.Irc.Messages.BaseMessage"/> on the queue but does not remove it. + /// </summary> + /// <returns></returns> public BaseMessage Peek() { *************** *** 126,155 **** } ! private void OnPenaltyTimer(object sender, ElapsedEventArgs args) ! { ! BaseMessage ircMsg; ! m_CurrentPenalty++; ! ! if(m_CurrentPenalty > m_MaxPenalty) ! m_CurrentPenalty = m_MaxPenalty; ! ! if((!m_Network.IsConnected) || (m_CurrentPenalty <= 0) || (MessageCount == 0)) ! return; ! if((ircMsg = ((BaseMessage) m_Queue.Peek())) == null) ! return; ! ! int penalty = GetPenalty(ircMsg); ! ! if((m_CurrentPenalty - penalty) >= -3) ! { ! byte[] toSend = Encoding.ASCII.GetBytes(ircMsg.ToString() + "\r\n"); ! ! m_Queue.Dequeue(); ! m_CurrentPenalty -= penalty; ! ! m_Socket.BeginSend(toSend, 0, toSend.Length, SocketFlags.None, null, null); ! } ! } ! public int GetPenalty(BaseMessage msg) { --- 165,173 ---- } ! /// <summary> ! /// Gets the estimated penalty for the given <see cref="Bot.Core.Irc.Messages.BaseMessage"/>. ! /// </summary> ! /// <param name="msg">Message to calculate penalty for.</param> ! /// <returns>Number of estimated points.</returns> public int GetPenalty(BaseMessage msg) { *************** *** 183,248 **** } ! public void Dispose() { ! if(m_PenaltyTimer != null) { ! m_PenaltyTimer.Stop(); ! m_PenaltyTimer.Dispose(); ! m_PenaltyTimer = null; } } #endregion #region Private methods private void DataPump() { string msgBuffer = ""; ! while(Thread.CurrentThread.IsAlive == true) { ! byte[] buffer = new byte[1024]; ! ! try { ! int numBytes = m_Socket.Receive(buffer, 0, buffer.Length, SocketFlags.None); ! if(numBytes != 0) { ! string message = String.Format("{0}{1}", msgBuffer, Encoding.ASCII.GetString(buffer)); ! string[] subMessages = message.Split('\n'); ! for(int i = 0; i < subMessages.Length; i++) { ! if(subMessages[i].EndsWith("\r")) ! { ! //Console.WriteLine(subMessages[i]); ! if(MessageReceived != null) ! MessageReceived(m_Network, new MessageReceivedEventArgs(subMessages[i].Trim('\r', '\n', ' '))); ! } ! else { ! message += subMessages[i]; } } ! } ! else ! { ! if(Disconnected != null) ! Disconnected(m_Network, new DisconnectedEventArgs("Connection lost")); ! break; ! } ! } ! catch(SocketException ex) ! { ! if(ex.NativeErrorCode == 10054) { ! if(Disconnected != null) ! Disconnected(m_Network, new DisconnectedEventArgs("Connection lost")); ! break; } } } } #endregion --- 201,309 ---- } ! public void Flush() { ! for(int i = 0; i < m_Queue.Count; i++) { ! BaseMessage msg = (BaseMessage) m_Queue.Peek(); ! byte[] toSend = Encoding.ASCII.GetBytes(msg.ToString() + "\r\n"); ! ! m_Socket.BeginSend(toSend, 0, toSend.Length, SocketFlags.None, null, null); } + + Reset(); } #endregion #region Private methods + private void Reset() + { + m_Queue.Clear(); + m_CurrentPenalty = 0; + m_LastIteration = DateTime.Now; + } + + private void OnPenaltyTimer(object sender, ElapsedEventArgs args) + { + BaseMessage ircMsg; + m_CurrentPenalty++; + + if(m_CurrentPenalty > m_MaxPenalty) + m_CurrentPenalty = m_MaxPenalty; + + if((!m_Network.IsConnected) || (m_CurrentPenalty <= 0) || (MessageCount == 0)) + return; + if((ircMsg = ((BaseMessage) m_Queue.Peek())) == null) + return; + + int penalty = GetPenalty(ircMsg); + + if((m_CurrentPenalty - penalty) >= -3) + { + byte[] toSend = Encoding.ASCII.GetBytes(ircMsg.ToString() + "\r\n"); + + m_Queue.Dequeue(); + m_CurrentPenalty -= penalty; + + m_Socket.BeginSend(toSend, 0, toSend.Length, SocketFlags.None, null, null); + } + } + private void DataPump() { string msgBuffer = ""; ! try { ! while(Thread.CurrentThread.IsAlive == true) { ! byte[] buffer = new byte[1024]; ! try { ! int numBytes = m_Socket.Receive(buffer, 0, buffer.Length, SocketFlags.None); ! if(numBytes != 0) { ! string message = String.Format("{0}{1}", msgBuffer, Encoding.ASCII.GetString(buffer)); ! string[] subMessages = message.Split('\n'); ! ! for(int i = 0; i < subMessages.Length; i++) { ! if(subMessages[i].EndsWith("\r")) ! { ! //Console.WriteLine(subMessages[i]); ! if(MessageReceived != null) ! MessageReceived(m_Network, new MessageReceivedEventArgs(subMessages[i].Trim('\r', '\n', ' '))); ! } ! else ! { ! message += subMessages[i]; ! } } } ! else ! { ! if(Disconnected != null) ! Disconnected(m_Network, new DisconnectedEventArgs("Connection lost")); ! break; ! } ! } ! catch(SocketException ex) { ! if(ex.NativeErrorCode == 10054) ! { ! if(Disconnected != null) ! Disconnected(m_Network, new DisconnectedEventArgs("Connection lost")); ! break; ! } } } } + catch(ThreadAbortException) + { + Thread.ResetAbort(); + } } #endregion |
From: Iain M. <iai...@us...> - 2005-01-12 01:47:36
|
Update of /cvsroot/bobbot/Bob/Core/Collections In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv28743/Core/Collections Modified Files: PluginCollection.cs Log Message: Mainly cleanups. The bot will now cleanly shut itself down now, including disconnecting all connection admin, and sending a quit message to IRC. RemoteConnection has been updated to use the Kernel's SyncRoot for synchronizing events. Also, NetworkConnection now resolves hostnames specified for servers and also implements the quit message. New events have also been added to the Kernel and NetworkConnectionl: - Kernel.ShutdownRequest - Raised when a plugin requests the kernel to shutdown, can be cancelled using ShutdownEventArgs.Cancel - Kernel.ShutdownComplete - Raised when the kernel has completed the shutdown phase. - NetworkConnection.Quit - Raised when a user quits IRC. New methods added: - IStore.Shutdown - Shuts the datastore down, what that entails is up to the implementor. - RemoteService.Shutdown - Terminates the remote admin service. - NetworkPump.Flush - Flushes the message queue regardless of penalty implications. - Log.Close - Closes the log file. - Kernel.Shutdown - Shuts the kernel down and all related processes. I think I've covered it all. Index: PluginCollection.cs =================================================================== RCS file: /cvsroot/bobbot/Bob/Core/Collections/PluginCollection.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** PluginCollection.cs 9 Dec 2004 19:43:16 -0000 1.1 --- PluginCollection.cs 12 Jan 2005 01:47:24 -0000 1.2 *************** *** 107,142 **** #endregion ! #region Enumerator ! public class Enumerator : IEnumerator ! { ! #region Private members ! IEnumerator m_PluginEnumerator; ! #endregion ! ! #region Constructor ! public Enumerator(PluginCollection plugins) ! { m_PluginEnumerator = plugins.GetEnumerator(); ! } ! #endregion ! ! #region IEnumerator implementation ! public Object Current ! { get { return m_PluginEnumerator.Current; } ! } ! ! public bool MoveNext() ! { return m_PluginEnumerator.MoveNext(); ! } ! ! public void Reset() ! { m_PluginEnumerator.Reset(); ! } ! #endregion ! } ! #endregion } } --- 107,142 ---- #endregion ! #region Enumerator ! public class Enumerator : IEnumerator ! { ! #region Private members ! IEnumerator m_PluginEnumerator; ! #endregion ! ! #region Constructor ! public Enumerator(PluginCollection plugins) ! { m_PluginEnumerator = plugins.GetEnumerator(); ! } ! #endregion ! ! #region IEnumerator implementation ! public Object Current ! { get { return m_PluginEnumerator.Current; } ! } ! ! public bool MoveNext() ! { return m_PluginEnumerator.MoveNext(); ! } ! ! public void Reset() ! { m_PluginEnumerator.Reset(); ! } ! #endregion ! } ! #endregion } } |
From: Iain M. <iai...@us...> - 2005-01-12 01:47:36
|
Update of /cvsroot/bobbot/Bob/Core/Irc/Messages/Commands In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv28743/Core/Irc/Messages/Commands Added Files: QuitMessage.cs Log Message: Mainly cleanups. The bot will now cleanly shut itself down now, including disconnecting all connection admin, and sending a quit message to IRC. RemoteConnection has been updated to use the Kernel's SyncRoot for synchronizing events. Also, NetworkConnection now resolves hostnames specified for servers and also implements the quit message. New events have also been added to the Kernel and NetworkConnectionl: - Kernel.ShutdownRequest - Raised when a plugin requests the kernel to shutdown, can be cancelled using ShutdownEventArgs.Cancel - Kernel.ShutdownComplete - Raised when the kernel has completed the shutdown phase. - NetworkConnection.Quit - Raised when a user quits IRC. New methods added: - IStore.Shutdown - Shuts the datastore down, what that entails is up to the implementor. - RemoteService.Shutdown - Terminates the remote admin service. - NetworkPump.Flush - Flushes the message queue regardless of penalty implications. - Log.Close - Closes the log file. - Kernel.Shutdown - Shuts the kernel down and all related processes. I think I've covered it all. --- NEW FILE: QuitMessage.cs --- #region LGPL License /* Bastard of a Bot Library Copyright (C) 2004 Bastard of a Bot Team This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion using System; using Bot.Core.Irc; namespace Bot.Core.Irc.Messages { /// <summary> /// Summary description for QuitMessage. /// </summary> public class QuitMessage : BaseMessage { #region Public properties public override string Command { get { return "QUIT"; } } public string Reason { get { return ((string) Parameters[0]); } } #endregion #region Constructors public QuitMessage() : base() { Parameters.Add(""); } public QuitMessage(string reason) : base() { Parameters.Add(reason); } #endregion #region Public methods public override void Notify(NetworkConnection network) { network.OnQuit(new QuitMessageEventArgs(this)); } #endregion } public delegate void QuitMessageEventHandler(NetworkConnection network, QuitMessageEventArgs args); public class QuitMessageEventArgs : EventArgs { #region Public properties public QuitMessage Message { get { return m_Message; } } #endregion #region Private members private QuitMessage m_Message; #endregion #region Constructor public QuitMessageEventArgs(QuitMessage message) { m_Message = message; } #endregion } } |