bobbot-cvs Mailing List for BoB
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-10-18 20:51:28
|
Update of /cvsroot/bobbot/Other/UltimaOnline.Sphere.Connection/Messages In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv27479/UltimaOnline.Sphere.Connection/Messages Modified Files: RideLostMessage.cs Log Message: -Fixed Regex match string Index: RideLostMessage.cs =================================================================== RCS file: /cvsroot/bobbot/Other/UltimaOnline.Sphere.Connection/Messages/RideLostMessage.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RideLostMessage.cs 17 Jul 2005 21:56:38 -0000 1.1 --- RideLostMessage.cs 18 Oct 2005 20:51:20 -0000 1.2 *************** *** 35,39 **** #region Members protected Regex m_Regex = new Regex( ! @"^([0-9]{2}:[0-9]{2}):ERROR:RIDDEN NPC NOT ACTING AS SUCH: UID=(.+), id=(.+) '(.+)', Invalid code=(.+)", RegexOptions.Compiled ); --- 35,39 ---- #region Members protected Regex m_Regex = new Regex( ! @"([0-9]{2}:[0-9]{2}):ERROR:RIDDEN NPC NOT ACTING AS SUCH: UID=(.+), id=(.+) '(.+)', Invalid code=(.+)", RegexOptions.Compiled ); |
From: Mr S. C. <mrs...@us...> - 2005-10-18 20:26:17
|
Update of /cvsroot/bobbot/Plugins/Sphere/Messages In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21047/Sphere/Messages Added Files: JSInformationRequestMessage.cs Log Message: -Added this! --- NEW FILE: JSInformationRequestMessage.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.Net; using System.Globalization; using System.Text.RegularExpressions; using Bot.Plugins.Sphere; using UltimaOnline.Sphere.Connection; using UltimaOnline.Sphere.Connection.Messages; namespace Bot.Plugins.Sphere.Messages { public delegate void JSInformationRequestEventHandler(object sender, JSInformationRequestEventArgs args); /// <summary> /// Summary description for JSInformationRequestMessage. /// </summary> public class JSInformationRequestMessage : BaseMessage { #region Members protected Regex m_Regex = new Regex( @"^([0-9]{2}:[0-9]{2}):\(.+\)JS:Information Request::Account:(.+)::RequestBy:(.+)", RegexOptions.Compiled ); protected DateTime m_Time; protected string m_Account; protected string m_RequestBy; #endregion #region Public properties /// <summary> /// The time this message was sent. /// </summary> public DateTime Time { get { return m_Time; } } public string Account { get { return m_Account; } } public string RequestBy { get { return m_RequestBy; } } #endregion public JSInformationRequestMessage() { } public override bool CanParse(string message) { if(m_Regex.IsMatch(message)) return true; return false; } public override void Parse(string message) { if(!CanParse(message)) throw new MessageParserException("Cannot parse this message.", message); Match match = m_Regex.Match(message); if(!match.Success) return; m_Time = DateTime.Parse(match.Groups[1].Value); m_Account = match.Groups[2].Value; m_RequestBy = match.Groups[3].Value; } public override void Notify(SphereConnection server) { server.OnCustomEvent(new JSInformationRequestEventArgs(this)); } } public class JSInformationRequestEventArgs : System.EventArgs { protected JSInformationRequestMessage m_Message; /// <summary> /// Gets the <see cref="Plugin.Messages.JSInformationRequestMessage"/> object of this event. /// </summary> public JSInformationRequestMessage Message { get { return m_Message; } } /// <summary> /// Instanciates the <see cref="JSInformationRequestEventArgs"/> class with a <see cref="JSInformationRequestMessage"/> object. /// </summary> /// <param name="msg"></param> public JSInformationRequestEventArgs(JSInformationRequestMessage msg) { m_Message = msg; } } } |
From: Mr S. C. <mrs...@us...> - 2005-10-18 20:24:45
|
Update of /cvsroot/bobbot/Plugins/Sphere/PunishSystem In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv20607/Sphere/PunishSystem Modified Files: JailEntry.cs JailSystem.cs Log Message: -I changed stuff apparently :D Index: JailEntry.cs =================================================================== RCS file: /cvsroot/bobbot/Plugins/Sphere/PunishSystem/JailEntry.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** JailEntry.cs 21 Jan 2005 03:29:53 -0000 1.1 --- JailEntry.cs 18 Oct 2005 20:24:33 -0000 1.2 *************** *** 25,32 **** using System.Timers; ! namespace Bot.Plugins.Sphere.PunishSystem ! { ! public class JailEntry ! { #region Private members --- 25,30 ---- using System.Timers; ! namespace Bot.Plugins.Sphere.PunishSystem { ! public class JailEntry { #region Private members *************** *** 45,88 **** #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"; --- 43,78 ---- #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"; *************** *** 98,105 **** #region Public methods ! public void StartSentence() ! { ! if (m_JailTimer != null) ! { m_JailTimer.Stop(); m_JailTimer.Dispose(); --- 88,93 ---- #region Public methods ! public void StartSentence() { ! if (m_JailTimer != null) { m_JailTimer.Stop(); m_JailTimer.Dispose(); *************** *** 118,123 **** } ! public bool Load(XmlElement xmlElement) ! { string account = xmlElement.GetAttribute("account"); string jailedon = xmlElement.GetAttribute("jailedon"); --- 106,110 ---- } ! public bool Load(XmlElement xmlElement) { string account = xmlElement.GetAttribute("account"); string jailedon = xmlElement.GetAttribute("jailedon"); *************** *** 139,144 **** } ! public bool Save(XmlElement xmlElement) ! { xmlElement.SetAttribute("account", m_Account); xmlElement.SetAttribute("jailedon", m_JailStart.ToFileTime().ToString()); --- 126,130 ---- } ! public bool Save(XmlElement xmlElement) { xmlElement.SetAttribute("account", m_Account); xmlElement.SetAttribute("jailedon", m_JailStart.ToFileTime().ToString()); *************** *** 177,186 **** #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; --- 163,169 ---- #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; *************** *** 189,198 **** 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; --- 172,182 ---- return; } + else + this.m_JailSystem.RemoveEntry( this ); 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; *************** *** 207,212 **** #region Constructor ! public JailEntry(JailSystem system) ! { m_JailSystem = system; } --- 191,195 ---- #region Constructor ! public JailEntry(JailSystem system) { m_JailSystem = system; } Index: JailSystem.cs =================================================================== RCS file: /cvsroot/bobbot/Plugins/Sphere/PunishSystem/JailSystem.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** JailSystem.cs 17 Jul 2005 21:46:28 -0000 1.4 --- JailSystem.cs 18 Oct 2005 20:24:33 -0000 1.5 *************** *** 37,61 **** using UltimaOnline.Sphere.Connection.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; } } --- 37,61 ---- using UltimaOnline.Sphere.Connection.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; } } *************** *** 64,69 **** #region Constructor ! public JailSystem(SpherePlugin parent) ! { m_Parent = parent; m_Server = m_Parent.InnerConnection; --- 64,69 ---- #region Constructor ! ! public JailSystem(SpherePlugin parent) { m_Parent = parent; m_Server = m_Parent.InnerConnection; *************** *** 71,76 **** } ! public JailSystem(SpherePlugin parent, string database) ! { m_Parent = parent; m_Server = m_Parent.InnerConnection; --- 71,75 ---- } ! public JailSystem(SpherePlugin parent, string database) { m_Parent = parent; m_Server = m_Parent.InnerConnection; *************** *** 79,88 **** } ! 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); --- 78,85 ---- } ! 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); *************** *** 93,100 **** } ! 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(); --- 90,98 ---- } ! if (!LoadDatabase()) { ! Log.WriteLine("Sphere (JailSystem)", "Error occured whilst loading the Jail Database."); ! } ! Log.WriteLine("Sphere (JailSystem)", "{0} Jail Entries Loaded", this.m_JailEntries.Length); SaveDatabase(); *************** *** 102,112 **** 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); --- 100,110 ---- 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); *************** *** 120,125 **** return true; ! foreach(XmlElement xmlElement in xmlList) ! { JailEntry entry = new JailEntry( this ); --- 118,122 ---- return true; ! foreach(XmlElement xmlElement in xmlList) { JailEntry entry = new JailEntry( this ); *************** *** 131,136 **** } ! catch(Exception ex) ! { Log.WriteLine("Sphere (JailDB)", "Failed to load Jail Database file, reason: {0}", ex.ToString()); return false; --- 128,132 ---- } ! catch(Exception ex) { Log.WriteLine("Sphere (JailDB)", "Failed to load Jail Database file, reason: {0}", ex.ToString()); return false; *************** *** 138,145 **** } ! public bool SaveDatabase() ! { ! try ! { Log.WriteLine("Sphere (JailDB)", "Writing database to '{0}'...", this.JailDatabase); --- 134,139 ---- } ! public bool SaveDatabase() { ! try { Log.WriteLine("Sphere (JailDB)", "Writing database to '{0}'...", this.JailDatabase); *************** *** 154,159 **** ! foreach(JailEntry entry in m_JailEntries) ! { XmlElement xmlElement = xmlDoc.CreateElement("JailEntry"); xmlRoot.AppendChild(xmlElement); --- 148,152 ---- ! foreach(JailEntry entry in m_JailEntries) { XmlElement xmlElement = xmlDoc.CreateElement("JailEntry"); xmlRoot.AppendChild(xmlElement); *************** *** 169,397 **** } ! 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); ! if (jailed == null) ! { ! Log.WriteLine("Sphere (JailDB)", "Account '{0}' doesn't exist and cannot be jailed!", account); ! return false; ! } ! 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 (Exception e) ! { ! Console.WriteLine(e.ToString()); ! 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; } --- 162,328 ---- } ! catch(Exception ex) { Log.WriteLine("Sphere (JailDB)", "Failed to write Jail Database file, reason: {0}", ex.Message); return false; } } + #endregion #region Public Methods ! #region Jail Method ! 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; } ! if (IsJailed( account )) { ! return EditJail( account , gm , length , reason ); ! } ! if (reason == null || reason == "") { ! reason = "None Set"; ! } ! if (character == null || character == "") { ! character = "All"; ! } ! Account jailed = new Account( account ); ! /*Account jailed = AccountRegistration.Instance.GetAccount( account ); ! if (jailed == null) { ! Log.WriteLine("Sphere (JailSystem)", "Account '{0}' doesn't exist and cannot be jailed!", account); ! return false; ! }*/ ! m_Server.WriteLine("account {0} jail 1", jailed.Name); ! //for (int i = 0; i < jailed.Chars; i++) { ! for (int i = 0; i < 5; i++) { ! m_Server.WriteLine("account {0} char.{1}.send_to_jail={2}", jailed.Name, i, length); } ! JailEntry entry = new JailEntry( this ); ! entry.Account = account; ! entry.Character = character; ! entry.JailedBy = gm; ! entry.JailedOn = DateTime.Now; ! entry.JailedUntil = DateTime.Now.Add(TimeSpan.FromHours(double.Parse(length))); ! entry.Reason = reason; ! entry.StartSentence(); ! AddEntry( entry ); ! Log.WriteLine("Sphere (JailSystem)", "Account '{0}' is jailed by {1}! ({2} hours) (Reason: {3})", account, gm, length, reason); ! return true; } ! #endregion ! #region EditJail Method ! public bool EditJail(string[] args) { ! if (args.Length != 4) { 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; } ! JailEntry jailed = GetJailEntry( account ); ! RemoveEntry( jailed ); ! if (reason == null || reason == "") { ! reason = null; ! } ! if (jailed.JailedBy.IndexOf(" (Amended by ") > -1) { ! jailed.JailedBy = jailed.JailedBy.Substring( 0 , jailed.JailedBy.IndexOf( " (Amended by " ) ); ! } ! if (gm.ToLower() != jailed.JailedBy.ToLower()) { ! jailed.JailedBy += " (Amended by " + gm + ")"; ! } ! if (TimeSpan.FromHours(double.Parse(length)).TotalMilliseconds > DateTime.Now.Subtract(jailed.JailedUntil).TotalMilliseconds) { ! jailed.JailedUntil = jailed.JailedUntil.Add( TimeSpan.FromHours(double.Parse(length)) ); } ! if (reason != null) { ! jailed.Reason = reason; } ! jailed.StartSentence(); ! AddEntry( jailed ); ! Log.WriteLine("Sphere (JailSystem)", "Account Entry '{0}' is edited by {1}! ({2} hours) (Reason: {3})", jailed.Account, gm, (double.Parse(length) != 0? length : "Unedited"), (reason == null || reason == ""? "Unedited" : reason )); ! return true; } ! #endregion ! #region Release Method ! 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; } ! //Account jailed = AccountRegistration.Instance.GetAccount( account ); ! Account jailed = new Account( account ); ! m_Server.WriteLine("account {0} jail 0", jailed.Name); ! //for (int i = 0; i < jailed.Chars; i++) { ! for (int i = 0; i < 5; i++) { ! m_Server.WriteLine("account {0} char.{1}.release_from_jail", jailed.Name, i); ! } ! RemoveEntry( GetJailEntry( jailed.Name ) ); ! Log.WriteLine("Sphere (JailSystem)", "Account '{0}' is released from jail!", jailed.Name); ! return true; ! } ! ! #endregion ! ! #region JailEntry Handling ! ! public void AddEntry(JailEntry entry) { ! if (!m_JailEntryList.Contains( entry )) { ! m_JailEntryList.Add( entry ); } + return; + } ! public void RemoveEntry(JailEntry entry) { ! if (m_JailEntryList.Contains( entry )) { ! this.m_JailEntryList.Remove( entry ); ! } ! return; } ! public bool IsJailed(string account) { ! account = account.ToLower(); + foreach (JailEntry entry in m_JailEntryList) { + if (entry.Account.ToLower() == account) { + return true; + } } *************** *** 399,434 **** } #endregion #region Event handlers ! 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, 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); } #endregion } } --- 330,399 ---- } + public JailEntry[] GetJailEntryList() { + return m_JailEntries; + } + + public JailEntry GetJailEntry(string account) { + account = account.ToLower(); + + foreach (JailEntry entry in m_JailEntries) { + if (entry.Account.ToLower() == account) { + return entry; + } + } + + return null; + } + + #endregion + #endregion #region Event handlers ! private void OnCustomEvent(object sender, EventArgs args) { ! if(args is PlayerJailedEventArgs) { OnPlayerJailed(sender, (PlayerJailedEventArgs) args); ! } else if(args is PlayerReleasedEventArgs) { OnPlayerReleased(sender, (PlayerReleasedEventArgs) args); + } else if(args is JSInformationRequestEventArgs) { + OnJSInformationRequest(sender, (JSInformationRequestEventArgs) args); + } } ! private void OnPlayerJailed(object sender, PlayerJailedEventArgs args) { ! if (IsJailed( args.Message.PlayerAccount )) { ! RemoveEntry( GetJailEntry( args.Message.PlayerAccount ) ); ! } ! if (!Jail( args.Message.PlayerAccount, args.Message.PlayerName, args.Message.GM, args.Message.Length, args.Message.Reason)) { ! Kernel.Instance.Network.SendChannelMessage(m_Parent.InnerConfig.OutputChannel, "Unable to Jail Account '{0}'.", args.Message.PlayerAccount); ! } ! } ! private void OnPlayerReleased(object sender, PlayerReleasedEventArgs args) { ! if (!Release( args.Message.Player, args.Message.GM )) { ! Kernel.Instance.Network.SendChannelMessage(m_Parent.InnerConfig.OutputChannel, "Unable to Release Account '{0}'.", args.Message.Player); ! } } ! private void OnJSInformationRequest(object snder, JSInformationRequestEventArgs args) { ! JailEntry entry = GetJailEntry( args.Message.Account ); if (entry != null) { SendMessage( args.Message.RequestBy, string.Format( "Jailed By: {0}", entry.JailedBy)); SendMessage( args.Message.RequestBy, string.Format( "Jail Date: {0}", entry.JailedOn)); SendMessage( args.Message.RequestBy, string.Format( "Release Date: {0} ({1})", entry.JailedUntil, entry.TimeLeft)); SendMessage( args.Message.RequestBy, string.Format( "Reason: {0}", entry.Reason)); } else { ! SendMessage( args.Message.RequestBy, "There is no stored record of this jailing. It may have been delayed, lost in error, or this account may not be jailed."); } ! return; } #endregion + + public void SendMessage(string uid, string message) { + while (message.Length >= 50) { + SphereConnection.Instance.WriteLine("uid.{0}.f_jail_msg \"{1}\"", uid, message.Substring(0, 50)); + message = message.Remove(0, 50); + } + if (message.Length > 0) { + SphereConnection.Instance.WriteLine("uid.{0}.f_jail_msg {1}", uid, message); + } + SphereConnection.Instance.WriteLine("uid.{0}.f_jail_write", uid); + } } } |
From: Mr S. C. <mrs...@us...> - 2005-10-18 20:24:42
|
Update of /cvsroot/bobbot/Plugins/Sphere In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv20607/Sphere Modified Files: SpherePlugin.cs Log Message: -I changed stuff apparently :D Index: SpherePlugin.cs =================================================================== RCS file: /cvsroot/bobbot/Plugins/Sphere/SpherePlugin.cs,v retrieving revision 1.24 retrieving revision 1.25 diff -C2 -d -r1.24 -r1.25 *** SpherePlugin.cs 17 Jul 2005 21:46:29 -0000 1.24 --- SpherePlugin.cs 18 Oct 2005 20:24:33 -0000 1.25 *************** *** 1,6 **** ! #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.Collections.Specialized; using System.Configuration; using System.Text.RegularExpressions; 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.PunishSystem; using Bot.Plugins.Sphere.Accounting; using Bot.Plugins.Sphere.LogManagement; using UltimaOnline.Sphere.Connection; using UltimaOnline.Sphere.Connection.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 m_JailSystem; private BanSystem m_BanSystem; private LogManager m_LogManager; private MultiAccountSearch m_MultiAccountSearch; private AccountsReader m_AccountsReader; 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_LastKillTimer; private StringCollection m_AccountWatch = new StringCollection(); private StringCollection m_IPWatch = new StringCollection(); private Regex m_IPRegex = new Regex( @"^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$", RegexOptions.Compiled); private StringCollection m_IgnoreList = new StringCollection(); private Timer m_WatchTimer = new Timer(100); private int m_WatchTime = 10000; private Timer m_Timer; private DateTime m_LogNextOpen; 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 = ""; StreamReader peakRead; if (File.Exists("peak.txt")) { 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(); } if (File.Exists("accountwatch.txt")) { m_AccountWatch = new StringCollection(); peakRead = File.OpenText("accountwatch.txt"); string line = peakRead.ReadLine(); while (line != null) { if (line.StartsWith("ACCT")) { m_AccountWatch.Add( line.Remove(0, 5) ); } line = peakRead.ReadLine(); } peakRead.Close(); } if (File.Exists("ipwatch.txt")) { m_IPWatch = new StringCollection(); peakRead = File.OpenText("ipwatch.txt"); string line = peakRead.ReadLine(); while (line != null) { if (line.StartsWith("IP")) { m_IPWatch.Add( line.Remove(0, 3) ); } 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_WatchTimer.AutoReset = false; m_WatchTimer.Interval = m_WatchTime; m_WatchTimer.Elapsed += new ElapsedEventHandler(OnWatchTimerElapsed); m_LastKillTimer = new Timer(); m_LastKillTimer.Interval = 300000; m_LastKillTimer.AutoReset = false; m_LastKillTimer.Elapsed += new ElapsedEventHandler(OnLastKillTimerElapsed); 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_Server.ClientConnected += new ClientConnectedEventHandler(OnClientConnected); m_Server.ClientLogin += new ClientLoginEventHandler(OnClientLogin); m_Server.RegisterHandler(typeof(HouseKillingMessage)); m_Server.RegisterHandler(typeof(PlayerJailedMessage)); m_Server.RegisterHandler(typeof(PlayerReleasedMessage)); m_Server.RegisterHandler(typeof(SkillNukeMessage)); m_Server.RegisterHandler(typeof(PlayerPunishedMessage)); m_Server.RegisterHandler(typeof(ResKillingMessage)); 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); if (this.m_Config.JailDatabase != "-1") m_JailSystem = new JailSystem(this, m_Config.JailDatabase); if (this.m_Config.BanDatabase != "-1") m_BanSystem = new BanSystem(this, m_Config.BanDatabase); m_Accounting = new AccountRegistration(m_Server, m_Config.AccountDatabase); m_SphereAuth = new SphereAuth(this); m_LogManager = new LogManager(m_Server, m_Config.LogDatabase); } 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) { m_PageCount++; 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); } 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); m_JailSystem.SaveDatabase(); m_BanSystem.SaveDatabase(); m_LogManager.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_AccountWatch != null) { if (File.Exists("accountwatch.txt")) File.Delete("accountwatch.txt"); peakWrite = File.CreateText("accountwatch.txt"); foreach (string account in m_AccountWatch) peakWrite.WriteLine( "ACCT={0}", account ); peakWrite.Close(); Log.WriteLine("Sphere", "Written Account List ({0} Accounts)", m_AccountWatch.Count); } if (m_IPWatch != null) { if (File.Exists("ipwatch.txt")) File.Delete("ipwatch.txt"); peakWrite = File.CreateText("ipwatch.txt"); foreach (string ip in m_IPWatch) peakWrite.WriteLine( "IP={0}", ip ); peakWrite.Close(); Log.WriteLine("Sphere", "Written IP List ({0} IPs)", m_IPWatch.Count); } if (m_Timer.Interval == 1) { m_Timer.Stop(); m_Timer.Interval = m_Config.ResyncPeriod; m_Timer.Start(); } MultiAccountSearch.WriteAuthorisedMultis( m_Config.MultiFile ); } ! private void OnClientConnected(object sender, ClientConnectedEventArgs args) ! { m_ConnectCount++; --- 1,5 ---- ! #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.Collections.Specialized; using System.Configuration; using System.Text.RegularExpressions; 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.PunishSystem; using Bot.Plugins.Sphere.Accounting; using Bot.Plugins.Sphere.LogManagement; using UltimaOnline.Sphere.Connection; using UltimaOnline.Sphere.Connection.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 m_JailSystem; private BanSystem m_BanSystem; private LogManager m_LogManager; private MultiAccountSearch m_MultiAccountSearch; private AccountsReader m_AccountsReader; 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 bool m_RetryConnect = true; private Mobile m_LastVictim; private Mobile[] m_LastKillers; private Timer m_LastKillTimer; private StringCollection m_AccountWatch = new StringCollection(); private StringCollection m_IPWatch = new StringCollection(); private Regex m_IPRegex = new Regex( @"^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$", RegexOptions.Compiled); private StringCollection m_IgnoreList = new StringCollection(); private Timer m_WatchTimer = new Timer(100); private int m_WatchTime = 10000; private Timer m_Timer; private DateTime m_LogNextOpen; 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 = ""; StreamReader peakRead; if (File.Exists("peak.txt")) { 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(); } if (File.Exists("accountwatch.txt")) { m_AccountWatch = new StringCollection(); peakRead = File.OpenText("accountwatch.txt"); string line = peakRead.ReadLine(); while (line != null) { if (line.StartsWith("ACCT")) { m_AccountWatch.Add( line.Remove(0, 5) ); } line = peakRead.ReadLine(); } peakRead.Close(); } if (File.Exists("ipwatch.txt")) { m_IPWatch = new StringCollection(); peakRead = File.OpenText("ipwatch.txt"); string line = peakRead.ReadLine(); while (line != null) { if (line.StartsWith("IP")) { m_IPWatch.Add( line.Remove(0, 3) ); } 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_WatchTimer.AutoReset = false; m_WatchTimer.Interval = m_WatchTime; m_WatchTimer.Elapsed += new ElapsedEventHandler(OnWatchTimerElapsed); m_LastKillTimer = new Timer(); m_LastKillTimer.Interval = 300000; m_LastKillTimer.AutoReset = false; m_LastKillTimer.Elapsed += new ElapsedEventHandler(OnLastKillTimerElapsed); 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_Server.ClientConnected += new ClientConnectedEventHandler(OnClientConnected); m_Server.ClientLogin += new ClientLoginEventHandler(OnClientLogin); m_Server.RegisterHandler(typeof(HouseKillingMessage)); m_Server.RegisterHandler(typeof(PlayerJailedMessage)); m_Server.RegisterHandler(typeof(PlayerReleasedMessage)); m_Server.RegisterHandler(typeof(SkillNukeMessage)); m_Server.RegisterHandler(typeof(PlayerPunishedMessage)); m_Server.RegisterHandler(typeof(ResKillingMessage)); m_Server.RegisterHandler(typeof(JSInformationRequestMessage)); 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); if (this.m_Config.JailDatabase != "-1") m_JailSystem = new JailSystem(this, m_Config.JailDatabase); if (this.m_Config.BanDatabase != "-1") m_BanSystem = new BanSystem(this, m_Config.BanDatabase); m_Accounting = new AccountRegistration(m_Server, m_Config.AccountDatabase); m_SphereAuth = new SphereAuth(this); m_LogManager = new LogManager(m_Server, m_Config.LogDatabase); } public void Stop() { if(m_Server != null) { m_Server.Disconnect(); m_Server = null; } } #endregion #region Event handlers private void OnConnected(object sender, ConnectedEventArgs args) { m_RetryConnect = true; 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) { if (m_RetryConnect) { m_RetryConnect = false; Log.WriteLine("Sphere", "Connection lost to '{0}', attempting to reconnect...", args.EndPoint.ToString()); Kernel.Instance.Network.SendChannelMessage(m_Config.OutputChannel, String.Format("Connection lost to '{0}', attempting to reconnect...", args.EndPoint.ToString())); m_Server.Connect(IPAddress.Parse(m_Config.Address), m_Config.Port); return; } 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) { m_PageCount++; 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); } 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_JailSystem != null) { m_JailSystem.SaveDatabase(); } if (m_BanSystem != null) { m_BanSystem.SaveDatabase(); } if (m_LogManager != null) { m_LogManager.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_AccountWatch != null) { if (File.Exists("accountwatch.txt")) File.Delete("accountwatch.txt"); peakWrite = File.CreateText("accountwatch.txt"); foreach (string account in m_AccountWatch) peakWrite.WriteLine( "ACCT={0}", account ); peakWrite.Close(); Log.WriteLine("Sphere", "Written Account List ({0} Accounts)", m_AccountWatch.Count); } if (m_IPWatch != null) { if (File.Exists("ipwatch.txt")) File.Delete("ipwatch.txt"); peakWrite = File.CreateText("ipwatch.txt"); foreach (string ip in m_IPWatch) peakWrite.WriteLine( "IP={0}", ip ); peakWrite.Close(); Log.WriteLine("Sphere", "Written IP List ({0} IPs)", m_IPWatch.Count); } if (m_Timer.Interval == 1) { m_Timer.Stop(); m_Timer.Interval = m_Config.ResyncPeriod; m_Timer.Start(); } MultiAccountSearch.WriteAuthorisedMultis( m_Config.MultiFile ); } ! private void OnClientConnected(object sender, ClientConnectedEventArgs args) { m_ConnectCount++; *************** *** 11,15 **** return; ! if (m_IPWatch.Contains( args.Message.Address.ToString() ) && !m_IgnoreList.Contains( args.Message.Address.ToString() )) { Kernel.Instance.Network.SendChannelMessage(m_Config.OutputChannel, String.Format("IP '{0}' is attempting to connect.", args.Message.Address.ToString())); m_IgnoreList.Add( args.Message.Address.ToString() ); if (!m_WatchTimer.Enabled) --- 10,14 ---- return; ! if (m_IPWatch.Contains( args.Message.Address.ToString() ) && !m_IgnoreList.Contains( args.Message.Address.ToString() )) { Kernel.Instance.Network.SendChannelMessage(m_Config.OutputChannel, String.Format("IP '{0}' is attempting to connect.", args.Message.Address.ToString())); m_IgnoreList.Add( args.Message.Address.ToString() ); if (!m_WatchTimer.Enabled) *************** *** 19,28 **** } ! private void OnClientLogin(object sender, ClientLoginEventArgs args) ! { if (m_AccountWatch == null) return; ! if (m_AccountWatch.Contains( args.Message.Account.ToLower() ) && !m_IgnoreList.Contains( args.Message.Account.ToLower() )) { Kernel.Instance.Network.SendChannelMessage(m_Config.OutputChannel, String.Format("Account '{0}' has connected.", args.Message.Account)); m_IgnoreList.Add( args.Message.Account.ToLower() ); if (!m_WatchTimer.Enabled) --- 18,26 ---- } ! private void OnClientLogin(object sender, ClientLoginEventArgs args) { if (m_AccountWatch == null) return; ! if (m_AccountWatch.Contains( args.Message.Account.ToLower() ) && !m_IgnoreList.Contains( args.Message.Account.ToLower() )) { Kernel.Instance.Network.SendChannelMessage(m_Config.OutputChannel, String.Format("Account '{0}' has connected.", args.Message.Account)); m_IgnoreList.Add( args.Message.Account.ToLower() ); if (!m_WatchTimer.Enabled) *************** *** 32,59 **** } ! private void OnWatchTimerElapsed(object sender, ElapsedEventArgs e) ! { m_IgnoreList.Clear(); m_WatchTimer.Stop(); } ! private void OnLastKillTimerElapsed(object sender, ElapsedEventArgs e) ! { m_LastKillTimer.Enabled = false; m_LastKillTimer.Stop(); ! } #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 #region Connection Commands [AllowCondition("LothStaff", AccountPriv.GM, AllowConditionUsage.GreaterThanOrEqual, AllowConditionTarget.User)] [AllowCondition("StaffChannel", true, AllowConditionUsage.Equals, AllowConditionTarget.Channel)] [ChannelCommand("!recon")] private void ReconCommand(NetworkChannel chan, NetworkUser user, string[] args) { 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)] [AllowCondition("StaffChannel", true, AllowConditionUsage.Equals, AllowConditionTarget.Channel)] [ChannelCommand("!discon")] private void DisconCommand(NetworkChannel chan, NetworkUser user, string[] args) { if (m_Server.IsConnected) m_Server.Disconnect(); else chan.SendMessage("Not Connected To Server."); } #endregion #region Misc Commands [AllowCondition("LothStaff", AccountPriv.Admin, AllowConditionUsage.GreaterThanOrEqual, AllowConditionTarget.User)] [AllowCondition("StaffChannel", true, AllowConditionUsage.Equals, AllowConditionTarget.Channel)] [ChannelCommand("!watchip")] private void WatchIPCommand(NetworkChannel chan, NetworkUser user, string[] args) { if (args.Length < 1) { chan.SendMessage("You didn't specify an IP to watch."); return; } chan.SendMessage( WatchIP(args[0]), args[0] ); } [AllowCondition("LothStaff", AccountPriv.Admin, AllowConditionUsage.GreaterThanOrEqual, AllowConditionTarget.User)] [PrivateCommand("watchip")] private void WatchIPCommand(NetworkUser user, string[] args) { if (args.Length < 1) { user.SendMessage("You didn't specify an IP to watch."); return; } user.SendMessage( WatchIP(args[0]), args[0] ); } [AllowCondition("LothStaff", AccountPriv.Admin, AllowConditionUsage.GreaterThanOrEqual, AllowConditionTarget.User)] [AllowCondition("StaffChannel", true, AllowConditionUsage.Equals, AllowConditionTarget.Channel)] [ChannelCommand("!watchaccount")] private void WatchAccountCommand(NetworkChannel chan, NetworkUser user, string[] args) { if (args.Length < 1) { chan.SendMessage("You didn't specify an account to watch."); return; } chan.SendMessage(WatchAccount(args[0]), args[0]); } [AllowCondition("LothStaff", AccountPriv.Admin, AllowConditionUsage.GreaterThanOrEqual, AllowConditionTarget.User)] [PrivateCommand("watchaccount")] private void WatchAccountCommand(NetworkUser user, string[] args) { if (args.Length < 1) { user.SendMessage("You didn't specify an account to watch."); return; } user.SendMessage(WatchAccount(args[0]), args[0]); } private string WatchAccount( string account ) { account = account.ToLower(); if (m_AccountWatch == null) m_AccountWatch = new StringCollection(); if (m_WatchTimer == null) m_WatchTimer = new Timer( 100 ); if (m_AccountWatch.Contains(account)) { m_AccountWatch.Remove( account ); return "This account is no longer being watched."; } m_AccountWatch.Add( account ); return "Account '{0}' is now being watched."; } private string WatchIP( string ip ) { if (!m_IPRegex.IsMatch( ip )) { return "That isn't a valid IP."; } if (m_IPWatch == null) m_IPWatch = new StringCollection(); if (m_WatchTimer == null) m_WatchTimer = new Timer( 100 ); if (m_IPWatch.Contains(ip)) { m_IPWatch.Remove( ip ); return "This IP is no longer being watched."; } m_IPWatch.Add( ip ); return "IP '{0}' is now being watched."; } [AllowCondition("LothStaff", AccountPriv.Admin, AllowConditionUsage.GreaterThanOrEqual, AllowConditionTarget.User)] [AllowCondition("StaffChannel", true, AllowConditionUsage.Equals, AllowConditionTarget.Channel)] [ChannelCommand("!resync")] private void ResyncCommand(NetworkChannel chan, NetworkUser user, string[] args) { if (!m_Server.IsConnected) { chan.SendMessage("Not Connected To Server"); return; } m_Server.WriteLine("r"); m_Server.WriteLine("r"); chan.SendMessage("Done."); } [AllowCondition("LothStaff", AccountPriv.GM, AllowConditionUsage.GreaterThanOrEqual, AllowConditionTarget.User)] [AllowCondition("StaffChannel", true, AllowConditionUsage.Equals, AllowConditionTarget.Channel)] [ChannelCommand("!broadcast")] private void BroadcastCommand(NetworkChannel chan, NetworkUser user, string[] args) { if (args.Length < 1) { chan.SendMessage("You didn't specify a message to send."); return; } if (!m_Server.IsConnected) { chan.SendMessage("Not Connected To Server"); return; } string message = ""; foreach (string i in args) message += " " + i; Kernel.Instance.Network.SendChannelMessage(m_Config.PublicChannel, "Broadcast: {0}", message); Log.WriteLine("Sphere", "Broadcast:{0}", message); if (message.Length < 70) { m_Server.WriteLine("b" + message); } else { message = message.Trim(); while (message.Length > 70) { m_Server.WriteLine("b " + message.Substring(0, 70)); message = message.Remove(0, 70); } m_Server.WriteLine("b " + message); } } [AllowCondition("LothStaff", AccountPriv.GM, AllowConditionUsage.GreaterThanOrEqual, AllowConditionTarget.User)] [AllowCondition("StaffChannel", true, AllowConditionUsage.Equals, AllowConditionTarget.Channel)] [ChannelCommand("!broadcastirc")] private void BroadcastIrcCommand(NetworkChannel chan, NetworkUser user, string[] args) { if (args.Length < 1) { Kernel.Instance.Network.SendChannelMessage(chan, "You didn't specify a message to send."); return; } if (!m_Server.IsConnected) { chan.SendMessage("Not Connected To Server"); 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)] [AllowCondition("StaffChannel", true, AllowConditionUsage.Equals, AllowConditionTarget.Channel)] [ChannelCommand("!go")] private void GoCommand(NetworkChannel chan, NetworkUser user, string[] args) { if (args.Length < 2) { chan.SendMessage("Usage: !Go <uid> <message>"); return; } if (!m_Server.IsConnected) { chan.SendMessage("Not Connected To Server"); return; } string message = ""; foreach (string i in args) { if (i != args[0]) message += " " + i; } if (message.Length > 250) { chan.SendMessage("The specified message is too long. You cannot use more than 250 characters."); return; } m_Server.WriteLine("var.lothbot_target={0}", args[0]); message = message.Trim(); m_Server.WriteLine("var.lothbot_msg"); while (message.Length > 50) { m_Server.WriteLine("uid.{0}.f_lothbot_msg \"{1}\"", m_LothBotUid, message.Substring(0, 50)); message = message.Remove(0, 50); } m_Server.WriteLine("uid.{0}.f_lothbot_msg \"{1}\"", m_LothBotUid, message); m_Server.WriteLine("uid.{0}.respondtoplayer", m_LothBotUid); } [AllowCondition("LothStaff", AccountPriv.GM, AllowConditionUsage.GreaterThanOrEqual)] [PrivateCommand("admin listlog")] private void AdminListLogCommand(NetworkUser user, string[] args) { 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 (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; } } } #endregion #region Jail Commands [PrivateCommand("jail")] private void JailCommand(NetworkUser user, string[] args) { if (m_JailSystem == null) { user.SendMessage("The Jail System is disabled and your command cannot be processed."); return; } 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 #region Ban Commands [PrivateCommand("ban")] private void BanCommand(NetworkUser user, string[] args) { if (this.m_BanSystem == null) { user.SendMessage("The Ban System is disabled and your command cannot be processed."); return; } if (args.Length <= 0) { user.SendNotice("Incorrect Usage. (Ban <command> [<arguments>])"); user.SendNotice("Following commands are available to you"); user.SendNotice("Use 'Ban Help <command>' for more information"); user.SendNotice("------------------------------------------------"); user.SendNotice("Ban Info Displays ban entry information"); user.SendNotice("Ban List Displays full list of banned accounts."); if (m_SphereAuth.IsStaff(user)) { user.SendNotice("Ban Add Bans an account."); if (m_SphereAuth.GetStaffPriv(user) < AccountPriv.GM) return; user.SendNotice("Ban Edit Edits a ban entry."); if (m_SphereAuth.GetStaffPriv(user) < AccountPriv.Admin) return; user.SendNotice("Ban Del Unbans an account."); user.SendNotice("Ban Save Forces the Ban 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 < 2) { user.SendNotice("Incorrect Arguments: 'Ban Add <Account> [<Reason>]'"); return; } if (m_BanSystem.IsBanned(args[1])) { user.SendNotice("Account '{0}' is already banned!", args[1]); return; } string banargs = ""; for (int i = 2; i < args.Length; i++) banargs += " " + args[i]; if (m_BanSystem.Ban(args[1], null, user.Nickname, banargs.Trim())) user.SendNotice("'{0}' banned!", args[1]); else user.SendNotice("Unable to ban '{0}'", args[1]); return; } case "del": { if (!m_SphereAuth.IsStaff(user) || (m_SphereAuth.GetStaffPriv(user) < AccountPriv.Admin)) { user.SendNotice("You cannot use this command."); return; } if (args.Length < 2) { user.SendNotice("Incorrect Arguments: 'Ban Del <Account>'"); return; } if (!m_BanSystem.IsBanned(args[1])) { user.SendNotice("Account '{0}' wasn't banned!", args[1]); return; } if (m_BanSystem.UnBan(args[1], user.Nickname)) user.SendNotice("'{0}' unbanned!", args[1]); else user.SendNotice("Unable to unban '{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: 'Ban Edit <Account> <Reason>'"); return; } if (!m_BanSystem.IsBanned(args[1])) { user.SendNotice("Account '{0}' wasn't banned!", args[1]);... [truncated message content] |
From: Mr S. C. <mrs...@us...> - 2005-10-18 20:24:42
|
Update of /cvsroot/bobbot/Plugins/Sphere/Accounting In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv20607/Sphere/Accounting Modified Files: Account.cs MultiAccountSearch.cs Log Message: -I changed stuff apparently :D Index: Account.cs =================================================================== RCS file: /cvsroot/bobbot/Plugins/Sphere/Accounting/Account.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** Account.cs 17 Jul 2005 21:08:54 -0000 1.3 --- Account.cs 18 Oct 2005 20:24:33 -0000 1.4 *************** *** 284,287 **** --- 284,289 ---- case "3": return AccountPriv.Seer; + case "counsel": + return AccountPriv.Counselor; case "counselor": return AccountPriv.Counselor; *************** *** 290,294 **** case "player": return AccountPriv.Player; ! case "1r": return AccountPriv.Player; default: --- 292,296 ---- case "player": return AccountPriv.Player; ! case "1": return AccountPriv.Player; default: Index: MultiAccountSearch.cs =================================================================== RCS file: /cvsroot/bobbot/Plugins/Sphere/Accounting/MultiAccountSearch.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** MultiAccountSearch.cs 17 Jul 2005 21:08:54 -0000 1.1 --- MultiAccountSearch.cs 18 Oct 2005 20:24:33 -0000 1.2 *************** *** 11,14 **** --- 11,21 ---- private Account[] m_Accounts; private static AuthorisedMulti[] AuthorisedMultis; + private bool _wasIP; + + #endregion + + #region Public properties + + public bool ScanWasIP { get { return _wasIP; } } #endregion *************** *** 134,137 **** --- 141,145 ---- public Account[] ScanPassword(string account) { + _wasIP = false; account = account.ToLower(); foreach (Account acct in m_Accounts) *************** *** 163,173 **** #region IP Scan ! public Account[] ScanMultiIP(string account) { ! account = account.ToLower(); ! foreach (Account acct in m_Accounts) ! { ! if (acct.Name.ToLower() == account) ! return ScanMultiIP(acct); } return null; --- 171,189 ---- #region IP Scan ! public Account[] ScanMultiIP(string search) { ! if (search.Split('.').Length != 4) { ! _wasIP = false; ! search = search.ToLower(); ! foreach (Account acct in m_Accounts) { ! if (acct.Name.ToLower() == search) ! return ScanMultiIP(acct); ! } ! } else { ! _wasIP = true; ! foreach (Account acct in m_Accounts) { ! if (acct.FirstIP == search || acct.LastIP == search) ! return ScanMultiIP(acct); ! } } return null; |
From: Mr S. C. <mrs...@us...> - 2005-10-18 20:24:42
|
Update of /cvsroot/bobbot/Plugins/Sphere/Messages In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv20607/Sphere/Messages Modified Files: PlayerJailedMessage.cs PlayerReleasedMessage.cs Log Message: -I changed stuff apparently :D Index: PlayerReleasedMessage.cs =================================================================== RCS file: /cvsroot/bobbot/Plugins/Sphere/Messages/PlayerReleasedMessage.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** PlayerReleasedMessage.cs 17 Jul 2005 21:46:27 -0000 1.3 --- PlayerReleasedMessage.cs 18 Oct 2005 20:24:33 -0000 1.4 *************** *** 30,35 **** using UltimaOnline.Sphere.Connection.Messages; ! namespace Bot.Plugins.Sphere.Messages ! { public delegate void PlayerReleasedEventHandler(object sender, PlayerReleasedEventArgs args); --- 30,34 ---- using UltimaOnline.Sphere.Connection.Messages; ! namespace Bot.Plugins.Sphere.Messages { public delegate void PlayerReleasedEventHandler(object sender, PlayerReleasedEventArgs args); *************** *** 37,44 **** /// Summary description for PlayerReleasedMessage. /// </summary> ! public class PlayerReleasedMessage : BaseMessage ! { #region Members protected Regex m_Regex = new Regex( @"^([0-9]{2}:[0-9]{2}):\(.+\)JS::Player Released::GM:(.+)::Player:(.+)", RegexOptions.Compiled --- 36,44 ---- /// Summary description for PlayerReleasedMessage. /// </summary> ! public class PlayerReleasedMessage : BaseMessage { #region Members + protected Regex m_Regex = new Regex( + // @"^([0-9]{2}:[0-9]{2}):\(.+\)JS::Player Released::GM:(.+)::Player:(.+)", @"^([0-9]{2}:[0-9]{2}):\(.+\)JS::Player Released::GM:(.+)::Player:(.+)", RegexOptions.Compiled *************** *** 46,51 **** protected DateTime m_Time; ! protected int m_GM; ! protected int m_Player; #endregion --- 46,54 ---- protected DateTime m_Time; ! //protected int m_GM; ! //protected int m_Player; ! protected string m_GM; ! protected string m_Player; ! #endregion *************** *** 54,79 **** /// The time this message was sent. /// </summary> ! public DateTime Time ! { get { return m_Time; } } ! public int GM ! { get { return m_GM; } } ! public int Player ! { get { return m_Player; } } #endregion ! public PlayerReleasedMessage() ! { } ! public override bool CanParse(string message) ! { if(m_Regex.IsMatch(message)) return true; --- 57,77 ---- /// The time this message was sent. /// </summary> ! public DateTime Time { get { return m_Time; } } ! public string GM { get { return m_GM; } } ! public string Player { get { return m_Player; } } #endregion ! public PlayerReleasedMessage() { } ! public override bool CanParse(string message) { if(m_Regex.IsMatch(message)) return true; *************** *** 82,87 **** } ! public override void Parse(string message) ! { if(!CanParse(message)) throw new MessageParserException("Cannot parse this message.", message); --- 80,84 ---- } ! public override void Parse(string message) { if(!CanParse(message)) throw new MessageParserException("Cannot parse this message.", message); *************** *** 94,109 **** m_Time = DateTime.Parse(match.Groups[1].Value); ! m_GM = Int32.Parse(match.Groups[2].Value, NumberStyles.AllowHexSpecifier); ! m_Player = Int32.Parse(match.Groups[3].Value, NumberStyles.AllowHexSpecifier); } ! public override void Notify(SphereConnection server) ! { server.OnCustomEvent(new PlayerReleasedEventArgs(this)); } } ! public class PlayerReleasedEventArgs : System.EventArgs ! { protected PlayerReleasedMessage m_Message; --- 91,106 ---- m_Time = DateTime.Parse(match.Groups[1].Value); ! //m_GM = Int32.Parse(match.Groups[2].Value, NumberStyles.AllowHexSpecifier); ! //m_Player = Int32.Parse(match.Groups[3].Value, NumberStyles.AllowHexSpecifier); ! m_GM = match.Groups[2].Value; ! m_Player = match.Groups[3].Value; } ! public override void Notify(SphereConnection server) { server.OnCustomEvent(new PlayerReleasedEventArgs(this)); } } ! public class PlayerReleasedEventArgs : System.EventArgs { protected PlayerReleasedMessage m_Message; *************** *** 111,116 **** /// Gets the <see cref="Plugin.Messages.PlayerReleasedMessage"/> object of this event. /// </summary> ! public PlayerReleasedMessage Message ! { get { return m_Message; } } --- 108,112 ---- /// Gets the <see cref="Plugin.Messages.PlayerReleasedMessage"/> object of this event. /// </summary> ! public PlayerReleasedMessage Message { get { return m_Message; } } *************** *** 120,125 **** /// </summary> /// <param name="msg"></param> ! public PlayerReleasedEventArgs(PlayerReleasedMessage msg) ! { m_Message = msg; } --- 116,120 ---- /// </summary> /// <param name="msg"></param> ! public PlayerReleasedEventArgs(PlayerReleasedMessage msg) { m_Message = msg; } Index: PlayerJailedMessage.cs =================================================================== RCS file: /cvsroot/bobbot/Plugins/Sphere/Messages/PlayerJailedMessage.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** PlayerJailedMessage.cs 17 Jul 2005 21:46:27 -0000 1.4 --- PlayerJailedMessage.cs 18 Oct 2005 20:24:33 -0000 1.5 *************** *** 41,51 **** #region Members protected Regex m_Regex = new Regex( ! @"^([0-9]{2}:[0-9]{2}):\(.+\)JS::Player Jailed::GM:(.+)::Player:(.+)::Length:(.+)::Reason:(.+)", RegexOptions.Compiled ); protected DateTime m_Time; ! protected int m_GM; ! protected int m_Player; protected string m_Length; protected string m_Reason; --- 41,56 ---- #region Members protected Regex m_Regex = new Regex( ! //@"^([0-9]{2}:[0-9]{2}):\(.+\)JS::Player Jailed::GM:(.+)::Player:(.+)::Length:(.+)::Reason:(.+)", ! @"^([0-9]{2}:[0-9]{2}):\(.+\)JS::Player Jailed::GM:(.+)::PlayerAccount:(.+)::PlayerName:(.+)::PlayerChars:(.+)::Length:(.+)::Reason:(.+)", RegexOptions.Compiled ); protected DateTime m_Time; ! //protected int m_GM; ! //protected int m_Player; ! protected string m_GM; ! protected string m_PlayerAccount; ! protected string m_PlayerName; ! protected int m_PlayerChars; protected string m_Length; protected string m_Reason; *************** *** 61,72 **** } ! public int GM { get { return m_GM; } } ! public int Player { ! get { return m_Player; } } --- 66,85 ---- } ! public string GM { get { return m_GM; } } ! public string PlayerAccount { ! get { return m_PlayerAccount; } ! } ! ! public string PlayerName { ! get { return m_PlayerName; } ! } ! ! public int PlayerChars { ! get { return m_PlayerChars; } } *************** *** 106,113 **** m_Time = DateTime.Parse(match.Groups[1].Value); ! m_GM = Int32.Parse(match.Groups[2].Value, NumberStyles.AllowHexSpecifier); ! m_Player = Int32.Parse(match.Groups[3].Value, NumberStyles.AllowHexSpecifier); ! m_Length = match.Groups[4].Value; ! m_Reason = match.Groups[5].Value; } --- 119,134 ---- m_Time = DateTime.Parse(match.Groups[1].Value); ! //m_GM = Int32.Parse(match.Groups[2].Value, NumberStyles.AllowHexSpecifier); ! //m_Player = Int32.Parse(match.Groups[3].Value, NumberStyles.AllowHexSpecifier); ! m_GM = match.Groups[2].Value; ! m_PlayerAccount = match.Groups[3].Value; ! m_PlayerName = match.Groups[4].Value; ! try { ! m_PlayerChars = Int32.Parse( match.Groups[5].Value ); ! } catch { ! m_PlayerChars = 5; ! } ! m_Length = match.Groups[6].Value; ! m_Reason = match.Groups[7].Value; } |
From: Iain M. <iai...@us...> - 2005-07-17 22:26:54
|
Update of /cvsroot/bobbot/Other/UltimaOnline.Sphere.Connection In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv6937/UltimaOnline.Sphere.Connection Added Files: UltimaOnline.Sphere.Connection.csproj Log Message: Added project file --- NEW FILE: UltimaOnline.Sphere.Connection.csproj --- <VisualStudioProject> <CSHARP ProjectType = "Local" ProductVersion = "7.10.3077" SchemaVersion = "2.0" ProjectGuid = "{B68E9851-48E0-4807-BBB5-D46CD384D83B}" > <Build> <Settings ApplicationIcon = "" AssemblyKeyContainerName = "" AssemblyName = "UltimaOnline.Sphere.Connection" AssemblyOriginatorKeyFile = "" DefaultClientScript = "JScript" DefaultHTMLPageLayout = "Grid" DefaultTargetSchema = "IE50" DelaySign = "false" OutputType = "Library" PreBuildEvent = "" PostBuildEvent = "" RootNamespace = "UltimaOnline.Sphere.Connection" RunPostBuildEvent = "OnBuildSuccess" StartupObject = "" > <Config Name = "Debug" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "DEBUG;TRACE" DocumentationFile = "" DebugSymbols = "true" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "false" OutputPath = "bin\Debug\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> <Config Name = "Release" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "TRACE" DocumentationFile = "" DebugSymbols = "false" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "true" OutputPath = "bin\Release\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> </Settings> <References> <Reference Name = "System" AssemblyName = "System" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.dll" /> <Reference Name = "System.Data" AssemblyName = "System.Data" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Data.dll" /> <Reference Name = "System.XML" AssemblyName = "System.XML" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.XML.dll" /> </References> </Build> <Files> <Include> <File RelPath = "AssemblyInfo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "MessageParserException.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "SphereConnection.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Types.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Messages\AccountDoesNotExistMessage.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Messages\AdminAccountInUseMessage.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Messages\AdminBadPasswordMessage.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Messages\AdminWelcomeMessage.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Messages\BaseMessage.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Messages\ClientBadPasswordMessage.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Messages\ClientCharacterSelectedMessage.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Messages\ClientCommandMessage.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Messages\ClientConnectedMessage.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Messages\ClientDisconnectedMessage.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Messages\ClientKickedMessage.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Messages\ClientKilledMessage.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Messages\ClientLoginMessage.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Messages\ClientPageMessage.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Messages\CustomLogMessage.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Messages\HttpRequestMessage.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Messages\ResyncCompleteMessage.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Messages\ResyncPauseMessage.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Messages\ResyncRestartMessage.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Messages\RideLostMessage.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Messages\ScriptErrorMessage.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Messages\SecureModeDisabledMessage.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Messages\SecureModeEnabledMessage.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Messages\ServerInfoMessage.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Messages\ShowValueMessage.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Messages\UnknownCommandMessage.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Messages\VerboseModeDisabledMessage.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Messages\VerboseModeEnabledMessage.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Messages\WorldSaveMessage.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Messages\CVS\Entries" BuildAction = "None" /> <File RelPath = "Messages\CVS\Entries.Extra" BuildAction = "None" /> <File RelPath = "Messages\CVS\Entries.Extra.Old" BuildAction = "None" /> <File RelPath = "Messages\CVS\Entries.Old" BuildAction = "None" /> <File RelPath = "Messages\CVS\Repository" BuildAction = "None" /> <File RelPath = "Messages\CVS\Root" BuildAction = "None" /> </Include> </Files> </CSHARP> </VisualStudioProject> |
From: Iain M. <iai...@us...> - 2005-07-17 21:56:47
|
Update of /cvsroot/bobbot/Other/UltimaOnline.Sphere.WorldParser In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv1283/UltimaOnline.Sphere.WorldParser Added Files: AssemblyInfo.cs SphereAccount.cs SphereAccountCollection.cs SphereCharacter.cs SphereCharacterCollection.cs SphereContainer.cs SphereHelper.cs SphereItem.cs SphereItemCollection.cs Types.cs UltimaOnline.Sphere.WorldParser.sln WorldParser.cs Log Message: Changes: - Renamed Bot.Other.SphereConnection to UltimaOnline.Sphere.Connection for use in other projects Added: - New WIP assembly UltimaOnline.Sphere.WorldParser which is to be used in an upcoming plugin and client-side application --- NEW FILE: WorldParser.cs --- using System; using System.IO; using System.Collections; using System.Globalization; using Ultima; namespace UltimaOnline.Sphere.WorldParser { public class WorldParser { #region Public properties public SphereItemCollection Items { get { return _items; } } public SphereAccountCollection Accounts { get { return _accounts; } } public SphereCharacterCollection Characters { get { return _characters; } } #endregion #region Events /*public event WorldLoadingEventHandler Loading; public event WorldLoadingAccountsEventHandler LoadingAccounts; public event WorldLoadingCharactersEventHandler LoadingCharacters; public event WorldLoadingWorldEventHandler LoadingWorld; public event WorldLoadedEventHandler Loaded;*/ #endregion #region Protected members protected string _worldFile; protected string _spherePath; protected string _accountFile; protected string _characterFile; protected SphereItemCollection _items; protected SphereAccountCollection _accounts; protected SphereCharacterCollection _characters; protected Hashtable _typeTable; protected string[] _ignoreTypeList; protected ArrayList _loadedScripts; #endregion #region Constructor public WorldParser(string spherePath, string accountFile, string characterFile, string worldFile) { _worldFile = worldFile; _spherePath = spherePath; _accountFile = accountFile; _characterFile = characterFile; _items = new SphereItemCollection(); _accounts = new SphereAccountCollection(); _characters = new SphereCharacterCollection(); _typeTable = new Hashtable(CaseInsensitiveHashCodeProvider.Default, CaseInsensitiveComparer.Default); _loadedScripts = new ArrayList(); // don't want any of this shite. _ignoreTypeList = new string[] { "i_memory", "i_stat_locker_mem" }; } #endregion #region Public methods public void Load() { LoadTypeTable(_spherePath); ParseAccounts(_accountFile); ParseCharacters(_characterFile); ParseWorld(_characterFile, _worldFile); } #endregion #region Protected methods protected void LoadTypeTable(string path) { LoadTileData(path); LoadScripts(path); } protected void LoadTileData(string path) { // load defaults from tiledata for(int i = 0; i < TileData.ItemTable.Length; i++) { ItemData itemData = TileData.ItemTable[i]; SphereItem item; Hashtable block = new Hashtable(CaseInsensitiveHashCodeProvider.Default, CaseInsensitiveComparer.Default); block["serial"] = String.Format("{0:X}", i); block["name"] = itemData.Name; block["quality"] = itemData.Quality.ToString(); block["amount"] = itemData.Quantity.ToString(); block["price"] = itemData.Value.ToString(); block["weight"] = itemData.Weight.ToString(); if((itemData.Flags & TileFlag.Wearable) == TileFlag.Wearable) { block["layer"] = itemData.Quality.ToString(); } if((itemData.Flags & TileFlag.Container) == TileFlag.Container) { item = new SphereContainer(this, block); } else { item = new SphereItem(this, block); } _typeTable.Add("0" + block["serial"], item); } } protected void LoadScripts(string path) { // now load in the scripts string line; bool inResources = false; StreamReader reader = new StreamReader(Path.Combine(path, Path.Combine("scripts", "spheretables.scp"))); while((line = reader.ReadLine()) != null) { line = line.Trim(); if(line == String.Empty) { continue; } else if((line.StartsWith("//") == true) || (line.StartsWith("\\\\") == true) || (line.StartsWith("#") == true)) { continue; } if(line.ToUpper() == "[RESOURCES]") { inResources = true; } else if((line.StartsWith("[") == true) && (line.EndsWith("]"))) { inResources = false; } else if(inResources == true) { if(line.ToLower().StartsWith("scripts") != true) { line = Path.Combine("scripts", line); } string scriptPath = Path.Combine(path, line); if(Directory.Exists(scriptPath) == true) { LoadScriptDirectory(scriptPath); } else if(File.Exists(scriptPath) == true) { LoadScriptFile(scriptPath); } } } reader.Close(); } protected void LoadScriptDirectory(string path) { string[] files = Directory.GetFiles(path, "*.scp"); foreach(string file in files) { LoadScriptFile(file); } } protected void LoadScriptFile(string path) { if(_loadedScripts.Contains(path) == true) { return; } StreamReader reader = new StreamReader(path); Hashtable block; while((block = ReadNextBlock(reader)) != null) { if((string) block["section"] != "ITEMDEF") { continue; } SphereItem newItem = null; if(block["id"] != null) { if(_typeTable[(string) block["id"]] != null) { newItem = (SphereItem) _typeTable[(string) block["id"]]; newItem = (SphereItem) newItem.Clone(); } } else { if(_typeTable[(string) block["itemCode"]] != null) { newItem = (SphereItem) _typeTable[(string) block["itemCode"]]; newItem = (SphereItem) newItem.Clone(); } } if(newItem == null) { newItem = new SphereItem(this, block); } else { newItem.Update(this, block); } if(block["id"] != null) { _typeTable.Add((string) block["itemCode"], newItem); } if(block["defName"] != null) { _typeTable.Add((string) block["defName"], newItem); } } reader.Close(); _loadedScripts.Add(path); } protected void ParseAccounts(string file) { StreamReader reader = new StreamReader(file); Hashtable block; while((block = ReadNextBlock(reader)) != null) { _accounts.Add(new SphereAccount(block)); } reader.Close(); } protected void ParseCharacters(string file) { StreamReader reader = new StreamReader(file); Hashtable block; while((block = ReadNextBlock(reader)) != null) { if((block["name"] != null) && (((string) block["section"] == "WORLDCHAR") || ((string) block["section"] == "WC"))) { SphereCharacter newChar = new SphereCharacter(this, block); _characters.Add(newChar); _items.Add(newChar.TopLevelContainer); } } reader.Close(); } protected void ParseWorld(string charFile, string worldFile) { StreamReader reader = new StreamReader(charFile); Hashtable block; while((block = ReadNextBlock(reader)) != null) { if(IsIgnoredType((string) block["itemCode"]) == true) { continue; } if(((string) block["section"] == "WORLDITEM") || ((string) block["section"] == "WI")) { SphereItem item; if(_typeTable[(string) block["itemCode"]] != null) { item = (SphereItem) _typeTable[(string) block["itemCode"]]; item = (SphereItem) item.Clone(); item.Update(this, block); } else { item = new SphereItem(this, block); } _items.Add(item); } } reader.Close(); } protected Hashtable ReadNextBlock(StreamReader reader) { int peekChar; char nextChar; bool inValidBlock = false; bool inLine = false; string entry = String.Empty; Hashtable block = new Hashtable(CaseInsensitiveHashCodeProvider.Default, CaseInsensitiveComparer.Default); while((peekChar = reader.Peek()) != -1) { nextChar = (char) peekChar; // If we encounter an opening bracket and are already in // a valid block then we must have reached the end. if((nextChar == '[') && (inValidBlock == true) && (inLine != true)) { return block; } nextChar = (char) reader.Read(); // Skip characters we don't want. if(nextChar == '\r') { continue; } if(nextChar == '\n') { entry = ParseLine(entry.Trim()); if(entry.ToUpper() == "[EOF]") { // cow go moo } else if(entry.StartsWith("//") == true) { // duck go quack } else if(entry.StartsWith("\\\\") == true) { // dog go meow } else if(entry.StartsWith("#") == true) { // cat go woof } else { if((entry.StartsWith("[") == true) && (entry.EndsWith("]") == true)) { string[] parts = entry.Split(new char[] {' '}, 2); if(parts.Length != 2) { block["section"] = entry.Substring(1, entry.Length - 2); } else { block["section"] = parts[0].Substring(1); block["itemCode"] = parts[1].Substring(0, parts[1].Length - 1); } inValidBlock = true; } else if(inValidBlock == true) { string[] parts = entry.Split(new char[] {'='}, 2); if(parts.Length == 2) { string key = parts[0]; // exit if we enter an event if(key.ToLower() == "on") { return block; /*} else if(block.ContainsKey(key) == true) { if(block[key] is ArrayList) { ((ArrayList) block[key]).Add(parts[1]); } else { ArrayList subTable = new ArrayList(); subTable.Add(block[key]); subTable.Add(parts[1]); block[key] = subTable; }*/ } else { block[key] = parts[1]; } } } } inLine = false; entry = String.Empty; } else { inLine = true; entry += nextChar; } } if(inValidBlock) { return block; } else { return null; } } protected string ParseLine(string line) { bool inQuotes = false; string newLine = String.Empty; for(int i = 0; i < line.Length; i++) { char chr = line[i]; string chrPlusOne = line[i] + ((line.Length > (i + 1)) ? line[i + 1].ToString() : ""); if(chr == '"') { inQuotes = !inQuotes; } if((inQuotes == false) && ((chrPlusOne == "//") || (chrPlusOne == "\\\\") || (chr == '#'))) { return newLine; } newLine += chr; } return newLine; } protected bool IsIgnoredType(string type) { foreach(string itemType in _ignoreTypeList) { if(itemType.ToLower() == type.ToLower()) { return true; } } return false; } #endregion } } --- NEW FILE: SphereAccountCollection.cs --- using System; using System.Collections; namespace UltimaOnline.Sphere.WorldParser { public class SphereAccountCollection : CollectionBase { #region Protected members protected Hashtable _indexByName; #endregion #region Public properties public SphereAccount this[string name] { get { return (_indexByName[name] as SphereAccount); } } #endregion #region Constructor public SphereAccountCollection() : base() { _indexByName = new Hashtable(CaseInsensitiveHashCodeProvider.Default, CaseInsensitiveComparer.Default); } #endregion #region Public methods public void Add(SphereAccount account) { if(account == null) { throw new ArgumentNullException("account", "Cannot be null"); } this.InnerList.Add(account); this._indexByName[account.Name] = account; } public void AddRange(SphereAccount[] accounts) { if(accounts == null) { throw new ArgumentNullException("accounts", "Cannot be null"); } foreach(SphereAccount account in accounts) { if(account == null) { continue; } this.InnerList.Add(account); this._indexByName[account.Name] = account; } } #endregion } } --- NEW FILE: Types.cs --- using System; namespace UltimaOnline.Sphere.WorldParser { public enum Skills { Alchemy, Anatomy, ItemId, ArmsLore, Parrying, Begging, Blacksmithing, Bowcraft, Peacemaking, Camping, Carpentry, Cartography, Cooking, DetectingHidden, Enticement, EvaluatingIntel, Healing, Fishing, Forensics, Herding, Hiding, Provocation, Inscription, LockPicking, Magery, MagicResistance, Tactics, Snooping, Musicianship, Poisoning, Archery, SpiritSpeak, Stealing, Tailoring, Taming, TasteId, Tinkering, Tracking, Veterinary, Swordsmanship, Macefighting, Fencing, Wrestling, Lumberjacking, Mining, Meditation, Stealth, RemoveTrap, Necromancy } public enum ItemLayer { None = 0, LeftHand, RightHand, Shoes, Pants, Shirt, Helm, Gloves, Ring, Light, Collar, Hair, HalfApron, Chest, Wrist, Hidden, Beard, Tunic, Ears, Arms, Cape, BackPack, Robe, Skirt, Legs, Horse, VendorStock, VendorExtra, VendorBuys, BankBox, Special, Dragging, SpellStats, SpellReactive, SpellNightSight, SpellProtection, SpellIncognito, SpellMagicReflect, SpellParalyze, SpellInvisible, SpellPolymorph, SpellSummon, // why are these layers? FlagPoison, FlagCriminal, FlagPotion, FlagSpiritSpeak, FlagWool, FlagDrunk, FlagClientLinger, FlagHallucination, FlagPotionUsed, FlagStuck, FlagMurders, FlagBandage } /// <summary> /// Represents a position in the game world. /// </summary> public struct Position { public static readonly Position Default = new Position(0, 0, 0, 0); /// <summary> /// Location on the x-axis. /// </summary> public int X; /// <summary> /// Location on the y-axis. /// </summary> public int Y; /// <summary> /// Location on the z-axis. /// </summary> public int Z; /// <summary> /// Plane they are on. /// </summary> public int Plane; public Position(int x, int y, int z, int plane) { X = x; Y = y; Z = z; Plane = plane; } /// <summary> /// Parses the given position string. /// </summary> /// <param name="position">Position to parse.</param> /// <returns> /// A new <see cref="Position"/> structure representing the position. /// </returns> public Position Parse(string position) { string[] parts = position.Split(','); Position pos = new Position(); if (parts.Length == 4) { try { pos.X = Int32.Parse(parts[0]); pos.Y = Int32.Parse(parts[1]); pos.Z = Int32.Parse(parts[2]); pos.Plane = Int32.Parse(parts[3]); } catch { } } else if (parts.Length == 3) { try { pos.X = Int32.Parse(parts[0]); pos.Y = Int32.Parse(parts[1]); pos.Z = Int32.Parse(parts[2]); } catch { } } else if (parts.Length == 2) { try { pos.X = Int32.Parse(parts[0]); pos.Y = Int32.Parse(parts[1]); } catch { } } return pos; } /// <summary> /// Overriden to return the position as it would be seen in-game. /// </summary> /// <returns>Position as it would be in-game.</returns> public override string ToString() { if (Plane != 0) return String.Format("{0},{1},{2},{3}", X, Y, Z, Plane); else if (Z != 0) return String.Format("{0},{1},{2}", X, Y, Z); else return String.Format("{0},{1}", X, Y); //return String.Format("{0},{1},{2},{3}", X, Y, Z, Plane); } } } --- NEW FILE: SphereCharacter.cs --- using System; using System.Collections; using System.Globalization; namespace UltimaOnline.Sphere.WorldParser { public class SphereCharacter { #region Public properties public int Serial { get { return _serial; } } public int Mana { get { return _mana; } } public int Food { get { return _food; } } public int Karma { get { return _karma; } } public int Stamina { get { return _stamina; } } public int Dexterity { get { return _dexterity; } } public int[] Skills { get { return _skills; } } public string Name { get { return _name; } } public SphereAccount Account { get { return _account; } } public Position Position { get { return _position; } } public int Intelligence { get { return _int; } } public int Strength { get { return _strength; } } public int Hits { get { return _hits; } } public SphereContainer TopLevelContainer { get { return _topLevelContainer; } } #endregion #region Protected members protected int _serial; protected int _int; protected int _hits; protected int _mana; protected int _food; protected int _karma; protected int _stamina; protected int _strength; protected int _dexterity; protected int[] _skills; protected string _name; protected SphereAccount _account; protected Position _position; protected SphereContainer _topLevelContainer; #endregion #region Constructor public SphereCharacter(WorldParser parser, Hashtable block) { // Give our top level the same id as ourselves _topLevelContainer = new SphereContainer(parser, block); _serial = (block["serial"] != null) ? Int32.Parse((string) block["serial"], NumberStyles.HexNumber) : 0; _name = (block["name"] != null) ? (string) block["name"] : "unknown"; _int = (block["int"] != null) ? Int32.Parse((string) block["int"]) : 0; _hits = (block["hits"] != null) ? Int32.Parse((string) block["hits"]) : 0; _mana = (block["mana"] != null) ? Int32.Parse((string) block["mana"]) : 0; _food = (block["food"] != null) ? Int32.Parse((string) block["food"]) : 0; _strength = (block["str"] != null) ? Int32.Parse((string) block["str"]) : 0; _hits = (block["karma"] != null) ? Int32.Parse((string) block["karma"]) : 0; _dexterity = (block["dex"] != null) ? Int32.Parse((string) block["dex"]) : 0; _position = (block["p"] != null) ? Position.Parse((string) block["p"]) : Position.Default; int[] skills = (int[]) Enum.GetValues(typeof(UltimaOnline.Sphere.WorldParser.Skills)); string[] skillNames = (string[]) Enum.GetNames(typeof(UltimaOnline.Sphere.WorldParser.Skills)); _skills = new int[skills.Length]; foreach(int skillIndex in skills) { if(block[skillNames[skillIndex]] != null) { _skills[skillIndex] = Int32.Parse((string) block[skillNames[skillIndex]]); } } if(parser.Accounts[(string) block["account"]] != null) { _account = parser.Accounts[(string) block["account"]]; _account.Characters.Add(this); } } #endregion } } --- NEW FILE: SphereContainer.cs --- using System; using System.Collections; namespace UltimaOnline.Sphere.WorldParser { /// <summary> /// Summary description for Container. /// </summary> public class SphereContainer : SphereItem { #region Public properties public SphereItemCollection Items { get { return _items; } } #endregion #region Private members private SphereItemCollection _items; #endregion #region Constructor public SphereContainer() : base() { _items = new SphereItemCollection(); } public SphereContainer(WorldParser parser, Hashtable block) : base(parser, block) { _items = new SphereItemCollection(); } #endregion } } --- NEW FILE: AssemblyInfo.cs --- using System.Reflection; using System.Runtime.CompilerServices; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("UltimaOnline.Sphere.WorldParser")] [assembly: AssemblyDescription("Provides a parser for a sphere world.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("UltimaOnline.Sphere")] [assembly: AssemblyCopyright("Iain Mckay")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] --- NEW FILE: SphereCharacterCollection.cs --- using System; using System.Collections; namespace UltimaOnline.Sphere.WorldParser { public class SphereCharacterCollection { #region Public properties public SphereCharacter this[int serial] { get { return (_indexBySerial[serial] as SphereCharacter); } } public int Count { get { return _indexBySerial.Count; } } #endregion #region Private members private Hashtable _indexBySerial; #endregion #region Constructor public SphereCharacterCollection() : base() { _indexBySerial = new Hashtable(); } #endregion #region Public methods public void Add(SphereCharacter character) { if(character == null) { throw new ArgumentNullException("character", "Cannot be null"); } _indexBySerial[character.Serial] = character; } public void AddRange(SphereCharacter[] characters) { if(characters == null) { throw new ArgumentNullException("characters", "Cannot be null"); } foreach(SphereCharacter character in characters) { if(character == null) { continue; } _indexBySerial[character.Serial] = character; } } public IEnumerator GetEnumerator() { return new Enumerator(this); } #endregion #region Enumerator public class Enumerator : IEnumerator { #region Private members private IDictionaryEnumerator _enum; #endregion #region Constructor public Enumerator(SphereCharacterCollection parent) { _enum = parent._indexBySerial.GetEnumerator(); } #endregion #region IEnumerator implementation public object Current { get { return _enum.Value; } } public void Reset() { _enum.Reset(); } public bool MoveNext() { return _enum.MoveNext(); } #endregion } #endregion } } --- NEW FILE: SphereHelper.cs --- using System; using System.Text; using System.Security; using System.Security.Cryptography; namespace UltimaOnline.Sphere.WorldParser { public class SphereHelper { public static string EncryptString(string toEncrypt) { MD5 crypto = new MD5CryptoServiceProvider(); byte[] result = crypto.ComputeHash(Encoding.ASCII.GetBytes(toEncrypt)); string hashedString = ""; foreach(byte b in result) { hashedString += String.Format("{0:x2}", b); } return hashedString; } public static ItemLayer ConvertSphereLayer(string layer) { // What do we have? int or string layer? try { Int32.Parse(layer); // can just convert straight into ItemLayer return (ItemLayer) Enum.Parse(typeof(ItemLayer), layer); } catch(FormatException) { // eek, we have to compare against all textual layer identifiers switch(layer) { case "layer_hand1": return ItemLayer.LeftHand; case "layer_hand2": return ItemLayer.RightHand; case "layer_shoes": return ItemLayer.Shoes; case "layer_pants": return ItemLayer.Pants; case "layer_shirt": return ItemLayer.Shirt; case "layer_helm": return ItemLayer.Helm; case "layer_gloves": return ItemLayer.Gloves; case "layer_ring": return ItemLayer.Ring; case "layer_light": return ItemLayer.Light; case "layer_collar": return ItemLayer.Collar; case "layer_hair": return ItemLayer.Hair; case "layer_half_apron": return ItemLayer.HalfApron; case "layer_chest": return ItemLayer.Chest; case "layer_wrist": return ItemLayer.Wrist; case "layer_hidden": return ItemLayer.Hidden; case "layer_beard": return ItemLayer.Beard; case "layer_tunic": return ItemLayer.Tunic; case "layer_ears": return ItemLayer.Ears; case "layer_arms": return ItemLayer.Arms; case "layer_cape": return ItemLayer.Cape; case "layer_pack": return ItemLayer.BackPack; case "layer_robe": return ItemLayer.Robe; case "layer_skirt": return ItemLayer.Skirt; case "layer_legs": return ItemLayer.Legs; case "layer_horse": return ItemLayer.Horse; case "layer_vendor_stock": return ItemLayer.VendorStock; case "layer_vendor_extra": return ItemLayer.VendorExtra; case "layer_vendor_buys": return ItemLayer.VendorBuys; case "layer_bankbox": return ItemLayer.BankBox; case "layer_special": return ItemLayer.Special; case "layer_dragging": return ItemLayer.Dragging; case "layer_spell_stats": return ItemLayer.SpellStats; case "layer_spell_reactive": return ItemLayer.SpellReactive; case "layer_spell_night_sight": return ItemLayer.SpellNightSight; case "layer_spell_protection": return ItemLayer.SpellProtection; case "layer_spell_incognito": return ItemLayer.SpellIncognito; case "layer_spell_magic_reflect": return ItemLayer.SpellMagicReflect; case "layer_spell_paralyze": return ItemLayer.SpellParalyze; case "layer_spell_invis": return ItemLayer.SpellInvisible; case "layer_spell_polymorph": return ItemLayer.SpellPolymorph; case "layer_spell_summon": return ItemLayer.SpellSummon; case "layer_flag_poison": return ItemLayer.FlagPoison; case "layer_flag_criminal": return ItemLayer.FlagCriminal; case "layer_flag_potion": return ItemLayer.FlagPotion; case "layer_flag_spiritspeak": return ItemLayer.FlagSpiritSpeak; case "layer_flag_wool": return ItemLayer.FlagWool; case "layer_flag_drunk": return ItemLayer.FlagDrunk; case "layer_flag_clientlinger": return ItemLayer.FlagClientLinger; case "layer_flag_hallucination": return ItemLayer.FlagHallucination; case "layer_flag_potionused": return ItemLayer.FlagPotionUsed; case "layer_flag_stuck": return ItemLayer.FlagStuck; case "layer_flag_murders": return ItemLayer.FlagMurders; case "layer_flag_bandage": return ItemLayer.FlagBandage; } } return ItemLayer.None; } } } --- NEW FILE: UltimaOnline.Sphere.WorldParser.sln --- Microsoft Visual Studio Solution File, Format Version 8.00 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UltimaOnline.Sphere.WorldParser", "UltimaOnline.Sphere.WorldParser.csproj", "{C7E24816-DA93-4937-A1E1-917DF751394C}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Global GlobalSection(SolutionConfiguration) = preSolution Debug = Debug Release = Release EndGlobalSection GlobalSection(ProjectConfiguration) = postSolution {C7E24816-DA93-4937-A1E1-917DF751394C}.Debug.ActiveCfg = Debug|.NET {C7E24816-DA93-4937-A1E1-917DF751394C}.Debug.Build.0 = Debug|.NET {C7E24816-DA93-4937-A1E1-917DF751394C}.Release.ActiveCfg = Release|.NET {C7E24816-DA93-4937-A1E1-917DF751394C}.Release.Build.0 = Release|.NET EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution EndGlobalSection GlobalSection(ExtensibilityAddIns) = postSolution EndGlobalSection EndGlobal --- NEW FILE: SphereAccount.cs --- using System; using System.Net; using System.Collections; using System.Globalization; namespace UltimaOnline.Sphere.WorldParser { public class SphereAccount { #region Protected members protected string _name; protected string _password; protected string _language; protected int _priviledges; protected TimeSpan _totalConnectTime; protected DateTime _firstConnectDate; protected DateTime _lastConnectDate; protected IPAddress _firstAddress; protected IPAddress _lastAddress; protected Hashtable _details; protected SphereCharacterCollection _characters; #endregion #region Public properties public string Name { get { return _name; } } public string Password { get { return _password; } } public string Language { get { return _language; } } public int Priviledges { get { return _priviledges; } } public TimeSpan TotalConnectTime { get { return _totalConnectTime; } } public DateTime FirstConnectDate { get { return _firstConnectDate; } } public DateTime LastConnectDate { get { return _lastConnectDate; } } public IPAddress FirstAddress { get { return _firstAddress; } } public IPAddress LastAddress { get { return _lastAddress; } } public SphereCharacterCollection Characters { get { return _characters; } } #endregion #region Constructor public SphereAccount(Hashtable details) { if(details == null) { throw new ArgumentNullException("details", "Cannot be null"); } _details = details; _name = ReadAccountName(); _password = ReadPassword(); _language = ReadLanguage(); _priviledges = ReadPriviledges(); _totalConnectTime = ReadTotalConnectTime(); _firstConnectDate = ReadFirstConnectDate(); _lastConnectDate = ReadLastConnectDate(); _firstAddress = ReadFirstAddress(); _lastAddress = ReadLastAddress(); _characters = new SphereCharacterCollection(); } #endregion #region Protected methods protected string ReadAccountName() { if(_details.ContainsKey("Section")) { return ReadString(_details["Section"]); } else { return String.Empty; } } protected string ReadPassword() { if(_details.ContainsKey("password")) { return SphereHelper.EncryptString(ReadString(_details["password"])); } else { return String.Empty; } } protected int ReadPriviledges() { if(_details.ContainsKey("priv")) { return ReadHex(_details["priv"]); } else { return 0; } } protected TimeSpan ReadTotalConnectTime() { if(_details.ContainsKey("totalconnecttime")) { return TimeSpan.FromMinutes(ReadInt32(_details["totalconnecttime"])); } else { return TimeSpan.FromSeconds(0); } } protected DateTime ReadFirstConnectDate() { if(_details.ContainsKey("firstconnectdate")) { return DateTime.Parse(ReadString(_details["firstconnectdate"])); } else { return DateTime.MinValue; } } protected DateTime ReadLastConnectDate() { if(_details.ContainsKey("lastconnectdate")) { return DateTime.Parse(ReadString(_details["lastconnectdate"])); } else { return DateTime.MinValue; } } protected IPAddress ReadFirstAddress() { if(_details.ContainsKey("firstip")) { return IPAddress.Parse(ReadString(_details["firstip"])); } else { return IPAddress.Parse("0.0.0.0"); } } protected IPAddress ReadLastAddress() { if(_details.ContainsKey("lastip")) { return IPAddress.Parse(ReadString(_details["lastip"])); } else { return IPAddress.Parse("0.0.0.0"); } } protected string ReadLanguage() { if(_details.ContainsKey("lang")) { return ReadString(_details["lang"]); } else { return "ENG"; } } protected int ReadInt32(object item) { return Int32.Parse(ReadString(item)); } protected int ReadHex(object item) { return Int32.Parse(ReadString(item), NumberStyles.HexNumber); } protected string ReadString(object item) { return (item as String); } #endregion } } --- NEW FILE: SphereItemCollection.cs --- using System; using System.Collections; namespace UltimaOnline.Sphere.WorldParser { public class SphereItemCollection { #region Public properties public SphereItem this[int serial] { get { return (_indexBySerial[serial] as SphereItem); } } #endregion #region Private members private Hashtable _indexBySerial; #endregion #region Constructor public SphereItemCollection() : base() { _indexBySerial = new Hashtable(); } #endregion #region Public methods public void Add(SphereItem item) { if(item == null) { throw new ArgumentNullException("item", "Cannot be null"); } _indexBySerial[item.Serial] = item; } public void AddRange(SphereItem[] items) { if(items == null) { throw new ArgumentNullException("items", "Cannot be null"); } foreach(SphereItem item in items) { if(item == null) { continue; } _indexBySerial[item.Serial] = item; } } public IEnumerator GetEnumerator() { return new Enumerator(this); } #endregion #region Enumerator public class Enumerator : IEnumerator { #region Private members private IDictionaryEnumerator _enum; #endregion #region Constructor public Enumerator(SphereItemCollection parent) { _enum = parent._indexBySerial.GetEnumerator(); } #endregion #region IEnumerator implementation public object Current { get { return _enum.Value; } } public void Reset() { _enum.Reset(); } public bool MoveNext() { return _enum.MoveNext(); } #endregion } #endregion } } --- NEW FILE: SphereItem.cs --- using System; using System.Collections; using System.Globalization; namespace UltimaOnline.Sphere.WorldParser { public class SphereItem : ICloneable { #region Public properties public int Serial { get { return _serial; } set { _serial = value; } } public string Name { get { return _name; } set { _name = value; } } public int Hue { get { return _hue; } set { _hue = value; } } public int Amount { get { return _amount; } set { _amount = value; } } public int Quality { get { return _quality; } set { _quality = value; } } public int Price { get { return _price; } set { _price = value; } } public Position Position { get { return _position; } set { _position = value; } } public string BaseType { get { return _baseType; } set { _baseType = value; } } public string DefName { get { return _defName; } set { _defName = value; } } public float Weight { get { return _weight; } set { _weight = value; } } public SphereContainer Container { get { return _container; } set { _container = value; } } public ItemLayer Layer { get { return _layer; } set { _layer = value; } } #endregion #region Protected members protected int _serial; protected int _hue; protected int _amount; protected int _quality; protected int _price; protected float _weight; protected string _name; protected string _defName; protected string _baseType; protected Position _position; protected SphereContainer _container; protected ItemLayer _layer; #endregion #region Constructor public SphereItem(WorldParser parser, Hashtable block) { _serial = (block["serial"] != null) ? Int32.Parse((string) block["serial"], NumberStyles.HexNumber) : 0; _hue = (block["color"] != null) ? Int32.Parse((string) block["color"], NumberStyles.HexNumber) : 0; _amount = (block["amount"] != null) ? Int32.Parse((string) block["amount"]) : 0; _quality = (block["quality"] != null) ? Int32.Parse((string) block["quality"]) : 0; _price = (block["price"] != null) ? Int32.Parse((string) block["price"]) : 0; _weight = (block["weight"] != null) ? float.Parse((string) block["weight"]) : 0; _name = (block["name"] != null) ? (string) block["name"] : "unknown"; _defName = (block["defName"] != null) ? (string) block["defName"] : "unknown"; _baseType = (block["type"] != null) ? (string) block["type"] : "unknown"; _position = (block["p"] != null) ? Position.Parse((string) block["p"]) : Position.Default; _layer = (block["layer"] != null) ? SphereHelper.ConvertSphereLayer((string) block["layer"]) : ItemLayer.None; if(block["cont"] != null) { int parentSerial = Int32.Parse((string) block["cont"], NumberStyles.HexNumber); SphereContainer parent = parser.Items[parentSerial] as SphereContainer; if(parent != null) { parent.Items.Add(this); _container = parent; } } } internal SphereItem() { } #endregion #region Internal methods internal void Update(WorldParser parser, Hashtable block) { if(block["serial"] != null) { _serial = Int32.Parse((string) block["serial"], NumberStyles.HexNumber); } if(block["color"] != null) { _hue = Int32.Parse((string) block["color"], NumberStyles.HexNumber); } if(block["amount"] != null) { _amount = Int32.Parse((string) block["amount"]); } if(block["quality"] != null) { _quality = Int32.Parse((string) block["quality"]); } if(block["price"] != null) { _price = Int32.Parse((string) block["price"]); } if(block["weight"] != null) { _weight = float.Parse((string) block["weight"]); } if(block["name"] != null) { _name = (string) block["name"]; } if(block["defName"] != null) { _defName = (string) block["defName"]; } if(block["type"] != null) { _baseType = (string) block["type"]; } if(block["p"] != null) { _position = Position.Parse((string) block["p"]); } if(block["layer"] != null) { _layer = SphereHelper.ConvertSphereLayer((string) block["layer"]); } if(block["cont"] != null) { int parentSerial = Int32.Parse((string) block["cont"], NumberStyles.HexNumber); SphereContainer parent = parser.Items[parentSerial] as SphereContainer; if(parent != null) { parent.Items.Add(this); _container = parent; } } } #endregion #region ICloneable implementation public object Clone() { SphereItem clone; if(this is SphereContainer) { clone = new SphereContainer(); } else { clone = new SphereItem(); } clone._serial = this._serial; clone._hue = this._hue; clone._amount = this._amount; clone._quality = this._quality; clone._price = this._price; clone._weight = this._weight; clone._name = this._name; clone._defName = this._defName; clone._baseType = this._baseType; clone._layer = this._layer; clone._position = this._position; return clone; } #endregion } } |
From: Iain M. <iai...@us...> - 2005-07-17 21:56:47
|
Update of /cvsroot/bobbot/Other/UltimaOnline.Sphere.Connection In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv1283/UltimaOnline.Sphere.Connection Added Files: AssemblyInfo.cs MessageParserException.cs SphereConnection.cs Types.cs UltimaOnline.Sphere.Connection.sln Log Message: Changes: - Renamed Bot.Other.SphereConnection to UltimaOnline.Sphere.Connection for use in other projects Added: - New WIP assembly UltimaOnline.Sphere.WorldParser which is to be used in an upcoming plugin and client-side application --- NEW FILE: MessageParserException.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; namespace UltimaOnline.Sphere.Connection { /// <summary> /// Summary description for MessageParserException. /// </summary> public class MessageParserException : ApplicationException { private string m_Data; /// <summary> /// Message the parser ran into problems with. /// </summary> public string Data { get { return m_Data; } } public MessageParserException(string message, string data) : base(message) { m_Data = data; } } } --- NEW FILE: UltimaOnline.Sphere.Connection.sln --- Microsoft Visual Studio Solution File, Format Version 8.00 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UltimaOnline.Sphere.Connection", "UltimaOnline.Sphere.Connection.csproj", "{603FDB64-0CA4-4B0C-9AD6-7695885B21E6}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Global GlobalSection(SolutionConfiguration) = preSolution Debug = Debug Release = Release EndGlobalSection GlobalSection(ProjectConfiguration) = postSolution {603FDB64-0CA4-4B0C-9AD6-7695885B21E6}.Debug.ActiveCfg = Debug|.NET {603FDB64-0CA4-4B0C-9AD6-7695885B21E6}.Debug.Build.0 = Debug|.NET {603FDB64-0CA4-4B0C-9AD6-7695885B21E6}.Release.ActiveCfg = Release|.NET {603FDB64-0CA4-4B0C-9AD6-7695885B21E6}.Release.Build.0 = Release|.NET EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution EndGlobalSection GlobalSection(ExtensibilityAddIns) = postSolution EndGlobalSection EndGlobal --- NEW FILE: SphereConnection.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.Text; using System.Timers; using System.Threading; using System.Reflection; using System.Collections; using System.ComponentModel; using System.Net; using System.Net.Sockets; using UltimaOnline.Sphere.Connection.Messages; namespace UltimaOnline.Sphere.Connection { public class SphereConnection { #region Singleton implementation private static SphereConnection _instance; public static SphereConnection Instance { get { return _instance; } } static SphereConnection() { _instance = new SphereConnection(); } #endregion #region Public properties public virtual ISynchronizeInvoke SyncRoot { get { return _syncRoot; } set { _syncRoot = value; } } public virtual bool IsConnected { get { return _connected; } } public virtual string Password { get { return _password; } set { _password = value; } } public virtual int ClientCount { get { return _clientCount; } } public virtual ArrayList ValidAccountProperties { get { return _accountProperties; } } #endregion #region Private members protected bool _connected; protected int _clientCount; protected string _password; protected Socket _socket; protected IPEndPoint _endPoint; protected Thread _clientThread; protected ArrayList _accountProperties; protected ArrayList _messageParsers; protected ArrayList _queryBuffer; protected ArrayList _accountQueryBuffer; protected object _queryTempValue; protected object _accountQueryTempValue; protected ISynchronizeInvoke _syncRoot; protected DisconnectedEventHandler _onDisconnected; protected DisconnectedEventHandler _onConnectionLost; protected MessageReceivedEventHandler _onMessageReceived; #endregion #region Events public event ConnectedEventHandler Connected; public event DisconnectedEventHandler Disconnected; public event DisconnectedEventHandler ConnectionLost; public event DisconnectedEventHandler ConnectionFailed; public event MessageReceivedEventHandler MessageReceived; public event AdminWelcomeEventHandler AdminWelcome; public event AdminBadPasswordEventHandler AdminBadPassword; public event AdminAccountInUseEventHandler AdminAccountInUse; public event ClientPageEventHandler ClientPage; public event ClientLoginEventHandler ClientLogin; public event ClientKilledEventHandler ClientKilled; public event ClientCommandEventHandler ClientCommand; public event ClientConnectedEventHandler ClientConnected; public event ClientBadPasswordEventHandler ClientBadPassword; public event ClientDisconnectedEventHandler ClientDisconnected; public event ClientCharacterSelectedEventHandler ClientCharacterSelected; public event WorldSaveEventHandler WorldSave; public event ServerInfoEventHandler ServerInfo; public event HttpRequestEventHandler HttpRequest; public event SecureModeEnabledEventHandler SecureModeEnabled; public event SecureModeDisabledEventHandler SecureModeDisabled; public event VerboseModeEnabledEventHandler VerboseModeEnabled; public event VerboseModeDisabledEventHandler VerboseModeDisabled; public event ResyncPauseEventHandler ResyncPause; public event ResyncRestartEventHandler ResyncRestart; public event ResyncCompleteEventHandler ResyncComplete; public event EventHandler CustomEvent; public event CustomLogEventHandler CustomLog; public event ShowValueEventHandler ShowValue; public event ScriptErrorEventHandler ScriptError; public event UnknownCommandEventHandler UnknownCommand; public event AccountDoesNotExistEventHandler AccountDoesNotExist; public event RideLostEventHandler RideLost; public event ClientKickedEventHandler ClientKicked; #endregion #region Constructor protected SphereConnection() { _onDisconnected = new DisconnectedEventHandler(OnDisconnected); _onConnectionLost = new DisconnectedEventHandler(OnConnectionLost); _onMessageReceived = new MessageReceivedEventHandler(OnMessageReceived); _messageParsers = new ArrayList(); _messageParsers.Add(typeof(WorldSaveMessage)); _messageParsers.Add(typeof(ShowValueMessage)); //m_MessageParsers.Add(typeof(CustomLogMessage)); _messageParsers.Add(typeof(ClientPageMessage)); _messageParsers.Add(typeof(ServerInfoMessage)); //m_MessageParsers.Add(typeof(ScriptErrorMessage)); _messageParsers.Add(typeof(ClientLoginMessage)); _messageParsers.Add(typeof(HttpRequestMessage)); _messageParsers.Add(typeof(ResyncPauseMessage)); _messageParsers.Add(typeof(ClientKilledMessage)); _messageParsers.Add(typeof(AdminWelcomeMessage)); _messageParsers.Add(typeof(ResyncRestartMessage)); _messageParsers.Add(typeof(ClientCommandMessage)); _messageParsers.Add(typeof(UnknownCommandMessage)); _messageParsers.Add(typeof(ResyncCompleteMessage)); _messageParsers.Add(typeof(ClientConnectedMessage)); _messageParsers.Add(typeof(AdminBadPasswordMessage)); _messageParsers.Add(typeof(SecureModeEnabledMessage)); _messageParsers.Add(typeof(ClientBadPasswordMessage)); _messageParsers.Add(typeof(AdminAccountInUseMessage)); _messageParsers.Add(typeof(SecureModeDisabledMessage)); _messageParsers.Add(typeof(VerboseModeEnabledMessage)); _messageParsers.Add(typeof(ClientDisconnectedMessage)); _messageParsers.Add(typeof(VerboseModeDisabledMessage)); _messageParsers.Add(typeof(AccountDoesNotExistMessage)); _messageParsers.Add(typeof(ClientCharacterSelectedMessage)); _messageParsers.Add(typeof(RideLostMessage)); _messageParsers.Add(typeof(ClientKickedMessage)); _queryBuffer = new ArrayList(); _accountQueryBuffer = new ArrayList(); string[] accountProps = new string[] { "NAME", "PLEVEL", "PRIV", "PASSWORD", "TOTALCONNECTTIME", "LASTCONNECTTIME", "LASTCHARUID", "CHARUID", "FIRSTCONNECTDATE", "FIRSTIP", "LASTCONNECTDATE", "LASTIP", "CHATNAME", "LANG", "CHARS", "JAIL", "BLOCK" }; _accountProperties = new ArrayList(); _accountProperties.AddRange(accountProps); } #endregion #region Public methods public void RegisterHandler(Type toRegister) { if(!toRegister.IsSubclassOf(typeof(BaseMessage))) { throw new ArgumentException("type must be a subclass of BaseMessage", "toRegister"); } if(_messageParsers.Contains(toRegister) == false) { _messageParsers.Add(toRegister); } } public void Connect(IPAddress addr, int port) { if(IsConnected) { return; } _endPoint = new IPEndPoint(addr, port); _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _socket.BeginConnect(_endPoint, new AsyncCallback(OnConnected), this); } public void Disconnect() { if(_socket == null) { return; } _clientThread.Abort(); _clientThread = null; _socket.Shutdown(SocketShutdown.Both); _socket.Close(); _socket = null; OnDisconnectedSync(); } public void Write(byte[] bytes) { if(!IsConnected) { return; } _socket.BeginSend(bytes, 0, bytes.Length, SocketFlags.None, null, this); } public void Write(string message) { if(!IsConnected) { return; } Write(message, true); } public void WriteLine(string message, params object[] args) { if (!IsConnected) { return; } Write(String.Format(message, args), true); } public object GetProperty(string property) { return GetProperty(property, typeof(string)); } public object GetProperty(string property, Type type) { int timeout = 0; if(!IsConnected) { return null; } InternalValueMessage queryMsg = new InternalValueMessage(property, type); _queryTempValue = null; WriteLine("show {0}", property); while((IsMessageComplete(queryMsg) == false) && (timeout < 10000)) { Thread.Sleep(50); timeout += 50; } _queryBuffer.Clear(); return _queryTempValue; } public object GetItemProperty(int item, string property, Type type) { return GetProperty(String.Format("uid.0{0:X}.{1}", item, property), type); } public string GetItemProperty(int item, string property) { return (GetItemProperty(item, property, typeof(string)) as String); } public string GetAccountProperty(string account, string property) { return (GetAccountProperty(account, property, typeof(string)) as String); } public object GetAccountProperty(string account, string property, Type type) { if (!IsConnected) { return null; } InternalAccountMessage queryMsg = new InternalAccountMessage(account, property, type); _accountQueryTempValue = null; int timeout = 0; WriteLine("account {0} show {1}", account, property); while((IsAccountMessageComplete(queryMsg) == false) && (timeout < 5000)) { Thread.Sleep( 50 ); timeout += 50; } _accountQueryBuffer.Clear(); return _accountQueryTempValue; } public BaseMessage ParseMessage(string rawMessage) { // Needs rethinking, something more efficient. foreach(Type msgObj in _messageParsers) { BaseMessage msg = (BaseMessage) msgObj.Assembly.CreateInstance(msgObj.FullName); if(msg.CanParse(rawMessage) == false) { continue; } msg.Parse(rawMessage); return msg; } return null; } #endregion #region Private methods private void DataPump() { string msgBuffer = ""; while(Thread.CurrentThread.IsAlive == true) { byte[] buffer = new byte[1024]; try { int numBytes = _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")) { OnMessageReceivedSync(new MessageReceivedEventArgs(subMessages[i].Trim('\r', '\n', ' '))); } else { message += subMessages[i]; } } } else { OnConnectionLostSync(); break; } } catch(SocketException ex) { if(ex.NativeErrorCode == 10054) { OnConnectionLostSync(); break; } } } } private void Write(string message, bool appendNewline) { if(!IsConnected) { return; } if(appendNewline) { message += "\n"; } byte[] buffer = Encoding.ASCII.GetBytes(message); _socket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, null, this); } private bool IsMessageComplete(InternalValueMessage property) { for (int i = 0; i < _queryBuffer.Count; i++) { if (_queryBuffer[i].GetType() != typeof(InternalValueMessage)) { continue; } InternalValueMessage j = (InternalValueMessage) _queryBuffer[i]; if((j.Item != null) && (j.Property.ToLower() == property.Property.ToLower())) { try { _queryTempValue = Convert.ChangeType(j.Value, property.Type); } catch(FormatException) { _queryTempValue = null; } return true; } } return false; } private bool IsAccountMessageComplete(InternalAccountMessage account) { for(int i = 0; i < _accountQueryBuffer.Count; i++) { if (_accountQueryBuffer[i].GetType() != typeof(InternalAccountMessage)) { continue; } InternalAccountMessage j = (InternalAccountMessage) _accountQueryBuffer[i]; if((j.Property == null) || (j.Value == null)) { _accountQueryTempValue = null; return true; } if((j.Account.ToLower() == account.Account.ToLower()) && (j.Property.ToLower() == account.Property.ToLower())) { try { _accountQueryTempValue = Convert.ChangeType(j.Value, account.Type); } catch(FormatException e) { Console.WriteLine(e.ToString()); _accountQueryTempValue = null; } return true; } } return false; } #endregion #region Event handlers internal void OnMessageReceivedSync(MessageReceivedEventArgs args) { // Hack to get properties working ShowValueMessage msg = new ShowValueMessage(); if(msg.CanParse(args.Message)) { msg.Parse(args.Message); if((msg.Value != null) && (msg.Property != null)) { if (msg.Property.ToLower() == "clients") { _clientCount = Int32.Parse(msg.Value); } if(this.ValidAccountProperties.Contains(msg.Property.ToUpper())) { _accountQueryBuffer.Add(new InternalAccountMessage(msg.Object, msg.Property, msg.Value, null)); } else { _queryBuffer.Add(new InternalValueMessage(msg.Property, msg.Object, msg.Value, null)); } } } if((_syncRoot != null) && (_syncRoot.InvokeRequired == true)) { _syncRoot.BeginInvoke(_onMessageReceived, new object[] { this, args }); } else { OnMessageReceived(this, args); } } internal void OnDisconnectedSync() { if((_syncRoot != null) && (_syncRoot.InvokeRequired == true)) { _syncRoot.Invoke(_onDisconnected, new object[] { this, new DisconnectedEventArgs(_endPoint) }); } else { OnDisconnected(this, new DisconnectedEventArgs(_endPoint)); } } internal void OnConnectionLostSync() { if((_syncRoot != null) && (_syncRoot.InvokeRequired == true)) { _syncRoot.Invoke(_onConnectionLost, new object[] { this, new DisconnectedEventArgs(_endPoint) }); } else { OnConnectionLost(this, new DisconnectedEventArgs(_endPoint)); } } internal void OnConnected(IAsyncResult ar) { if(_socket.Connected) { _connected = true; Write(new byte[] {1}); Thread.Sleep( 500 ); // Pause between login code & password to ensure connection success. Write(Password); _clientThread = new Thread(new ThreadStart(DataPump)); _clientThread.IsBackground = true; //_clientThread.Priority = ThreadPriority.Highest; _clientThread.Start(); if(Connected != null) { Connected(this, new ConnectedEventArgs(_endPoint)); } } else { _connected = false; if(ConnectionFailed != null) { ConnectionFailed(this, new DisconnectedEventArgs(_endPoint)); } } } internal void OnConnectionLost(object sender, DisconnectedEventArgs args) { _connected = false; if(ConnectionLost != null) { ConnectionLost(this, new DisconnectedEventArgs(_endPoint)); } } internal void OnDisconnected(object sender, DisconnectedEventArgs args) { _connected = false; if(Disconnected != null) { Disconnected(this, args); } } internal void OnMessageReceived(object sender, MessageReceivedEventArgs args) { BaseMessage msg = ParseMessage(args.Message); if(msg == null) { // Try to see if its a script error message. msg = new ScriptErrorMessage(); if (msg.CanParse(args.Message)) { msg.Parse(args.Message); } else { // Try to see if its a custom log message. msg = new CustomLogMessage(); if(msg.CanParse(args.Message)) { msg.Parse(args.Message); } else { return; } } } msg.Notify(this); if(MessageReceived != null) { MessageReceived(this, args); } } internal void OnClientConnected(ClientConnectedEventArgs args) { _clientCount = args.Message.ClientCount; if(ClientConnected != null) { ClientConnected(this, args); } } internal void OnClientLogin(ClientLoginEventArgs args) { if(ClientLogin != null) { ClientLogin(this, args); } } internal void OnClientCharacterSelected(ClientCharacterSelectedEventArgs args) { if(ClientCharacterSelected != null) { ClientCharacterSelected(this, args); } } internal void OnClientBadPassword(ClientBadPasswordEventArgs args) { if(ClientBadPassword != null) { ClientBadPassword(this, args); } } internal void OnClientKilled(ClientKilledEventArgs args) { if(ClientKilled != null) { ClientKilled(this, args); } } internal void OnClientDisconnected(ClientDisconnectedEventArgs args) { _clientCount = args.Message.ClientCount; if(ClientDisconnected != null) { ClientDisconnected(this, args); } } internal void OnServerInfo(ServerInfoEventArgs args) { if(ServerInfo != null) { ServerInfo(this, args); } } internal void OnHttpRequest(HttpRequestEventArgs args) { if(HttpRequest != null) { HttpRequest(this, args); } } internal void OnWorldSave(WorldSaveEventArgs args) { if(WorldSave != null) { WorldSave(this, args); } } internal void OnAdminWelcome(AdminWelcomeEventArgs args) { if(AdminWelcome != null) { AdminWelcome(this, args); } } internal void OnAdminBadPassword(AdminBadPasswordEventArgs args) { if(AdminBadPassword != null) { AdminBadPassword(this, args); } } internal void OnAdminAccountInUse(AdminAccountInUseEventArgs args) { if(AdminAccountInUse != null) { AdminAccountInUse(this, args); } } internal void OnVerboseModeEnabled(VerboseModeEnabledEventArgs args) { if(VerboseModeEnabled != null) { VerboseModeEnabled(this, args); } } internal void OnVerboseModeDisabled(VerboseModeDisabledEventArgs args) { if(VerboseModeDisabled != null) { VerboseModeDisabled(this, args); } } internal void OnSecureModeEnabled(SecureModeEnabledEventArgs args) { if(SecureModeEnabled != null) { SecureModeEnabled(this, args); } } internal void OnSecureModeDisabled(SecureModeDisabledEventArgs args) { if(SecureModeDisabled != null) { SecureModeDisabled(this, args); } } internal void OnResyncPause(ResyncPauseEventArgs args) { if(ResyncPause != null) { ResyncPause(this, args); } } internal void OnResyncRestart(ResyncRestartEventArgs args) { if(ResyncRestart != null) { ResyncRestart(this, args); } } internal void OnResyncComplete(ResyncCompleteEventArgs args) { if(ResyncComplete != null) { ResyncComplete(this, args); } } internal void OnClientPage(ClientPageEventArgs args) { if(ClientPage != null) { ClientPage(this, args); } } internal void OnClientCommand(ClientCommandEventArgs args) { if(ClientCommand != null) { ClientCommand(this, args); } } internal void OnShowValue(ShowValueEventArgs args) { if (ShowValue != null) { ShowValue(this, args); } } internal void OnScriptError(ScriptErrorEventArgs args) { if (ScriptError != null) { ScriptError(this, args); } } internal void OnCustomLog(CustomLogEventArgs args) { if(CustomLog != null) { CustomLog(this, args); } } internal void OnAccountDoesNotExist(AccountDoesNotExistEventArgs args) { _accountQueryBuffer.Add(new InternalAccountMessage(args.Message.Account, null, null)); if (AccountDoesNotExist != null) { AccountDoesNotExist(this, args); } } internal void OnUnknownCommand(UnknownCommandEventArgs args) { if(args.Message.Command.ToLower().StartsWith("account ")) { string[] command = args.Message.Command.Split(' '); if (command.Length >= 3) { if (command[2].ToLower() == "show") { _accountQueryBuffer.Add(new InternalAccountMessage(command[1], command[3], null)); } } } else if (args.Message.Command.ToLower().StartsWith("show ")) { _queryBuffer.Add(new InternalValueMessage(args.Message.Command.Split(' ')[1], null)); } if (UnknownCommand != null) { UnknownCommand(this, args); } } internal void OnRideLost(RideLostEventArgs args) { if (RideLost != null) { RideLost(this, args); } } internal void OnClientKicked(ClientKickedEventArgs args) { if (ClientKicked != null) { ClientKicked(this, args); } } public void OnCustomEvent(EventArgs args) { if(CustomEvent != null) { CustomEvent(this, args); } } #endregion #region Internal classes private class InternalValueMessage { #region Private members private string _property; private string _item; private object _value; private Type _type; #endregion #region Public properties public string Property { get { return _property; } set { _property = value; } } public string Item { get { return _item; } set { _item = value; } } public object Value { get { return _value; } set { _value = value; } } public Type Type { get { return _type; } set { _type = value; } } #endregion #region Constructor public InternalValueMessage(string property, Type type) : this(property, null, null, type) { } public InternalValueMessage(string property, string item, object value, Type type) { _property = property; _item = item; _value = value; _type = type; } #endregion } private class InternalAccountMessage { #region Private members private string _account; private string _property; private object _value; private Type _type; #endregion #region Public properties public string Account { get { return _account; } set { _account = value; } } public string Property { get { return _property; } set { _property = value; } } public object Value { get { return _value; } set { _value = value; } } public Type Type { get { return _type; } set { _type = value; } } #endregion #region Constructor public InternalAccountMessage(string account, string property, Type type) : this(account, property, null, type) { } public InternalAccountMessage(string account, string property, object value, Type type) { _account = account; _property = property; _value = value; _type = type; } #endregion } #endregion } #region Delegates and event args public delegate void ConnectedEventHandler(object sender, ConnectedEventArgs args); public delegate void ConnectingEventHandler(object sender, ConnectingEventArgs args); public delegate void DisconnectedEventHandler(object sender, DisconnectedEventArgs args); public delegate void MessageReceivedEventHandler(object sender, MessageReceivedEventArgs args); public class ConnectingEventArgs : EventArgs { private IPEndPoint _endPoint; public IPEndPoint EndPoint { get { return _endPoint; } } public ConnectingEventArgs(IPEndPoint endpoint) { _endPoint = endpoint; } } public class ConnectedEventArgs : EventArgs { private IPEndPoint _endPoint; public IPEndPoint EndPoint { get { return _endPoint; } } public ConnectedEventArgs(IPEndPoint endpoint) { _endPoint = endpoint; } } public class DisconnectedEventArgs : EventArgs { private IPEndPoint _endPoint; public IPEndPoint EndPoint { get { return _endPoint; } } public DisconnectedEventArgs(IPEndPoint endpoint) { _endPoint = endpoint; } } public class MessageReceivedEventArgs : EventArgs { private string _message; public string Message { get { return _message; } } public MessageReceivedEventArgs(string message) { _message = message; } } #endregion } --- NEW FILE: AssemblyInfo.cs --- using System.Reflection; using System.Runtime.CompilerServices; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("UltimaOnline.Sphere.Connection")] [assembly: AssemblyDescription("Provides an event-based interface to the remote admin of a sphere server.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("UltimaOnline.Sphere")] [assembly: AssemblyCopyright("Iain Mckay")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] --- NEW FILE: Types.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; namespace UltimaOnline.Sphere.Connection { public enum MobileType { Player, Npc } public struct Mobile { #region Public members public MobileType Type; public string Name; #endregion #region Constructor public Mobile(MobileType type, string name) { Type = type; Name = name; } #endregion } /// <summary> /// Represents a position in the game world. /// </summary> public struct Position { /// <summary> /// Location on the x-axis. /// </summary> public int X; /// <summary> /// Location on the y-axis. /// </summary> public int Y; /// <summary> /// Location on the z-axis. /// </summary> public int Z; /// <summary> /// Plane they are on. /// </summary> public int Plane; /// <summary> /// Parses the given position string. /// </summary> /// <param name="position">Position to parse.</param> /// <returns> /// A new <see cref="Position"/> structure representing the position. /// </returns> public Position Parse(string position) { string[] parts = position.Split(','); Position pos = new Position(); if (parts.Length == 4) { try { pos.X = Int32.Parse(parts[0]); pos.Y = Int32.Parse(parts[1]); pos.Z = Int32.Parse(parts[2]); pos.Plane = Int32.Parse(parts[3]); } catch { } } else if (parts.Length == 3) { try { pos.X = Int32.Parse(parts[0]); pos.Y = Int32.Parse(parts[1]); pos.Z = Int32.Parse(parts[2]); } catch { } } else if (parts.Length == 2) { try { pos.X = Int32.Parse(parts[0]); pos.Y = Int32.Parse(parts[1]); } catch { } } return pos; } /// <summary> /// Overriden to return the position as it would be seen in-game. /// </summary> /// <returns>Position as it would be in-game.</returns> public override string ToString() { if (Plane != 0) return String.Format("{0},{1},{2},{3}", X, Y, Z, Plane); else if (Z != 0) return String.Format("{0},{1},{2}", X, Y, Z); else return String.Format("{0},{1}", X, Y); //return String.Format("{0},{1},{2},{3}", X, Y, Z, Plane); } } } |
Update of /cvsroot/bobbot/Other/UltimaOnline.Sphere.Connection/Messages In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv1283/UltimaOnline.Sphere.Connection/Messages Added Files: AccountDoesNotExistMessage.cs AdminAccountInUseMessage.cs AdminBadPasswordMessage.cs AdminWelcomeMessage.cs BaseMessage.cs ClientBadPasswordMessage.cs ClientCharacterSelectedMessage.cs ClientCommandMessage.cs ClientConnectedMessage.cs ClientDisconnectedMessage.cs ClientKickedMessage.cs ClientKilledMessage.cs ClientLoginMessage.cs ClientPageMessage.cs CustomLogMessage.cs HttpRequestMessage.cs ResyncCompleteMessage.cs ResyncPauseMessage.cs ResyncRestartMessage.cs RideLostMessage.cs ScriptErrorMessage.cs SecureModeDisabledMessage.cs SecureModeEnabledMessage.cs ServerInfoMessage.cs ShowValueMessage.cs UnknownCommandMessage.cs VerboseModeDisabledMessage.cs VerboseModeEnabledMessage.cs WorldSaveMessage.cs Log Message: Changes: - Renamed Bot.Other.SphereConnection to UltimaOnline.Sphere.Connection for use in other projects Added: - New WIP assembly UltimaOnline.Sphere.WorldParser which is to be used in an upcoming plugin and client-side application --- NEW FILE: AccountDoesNotExistMessage.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.Net; using System.Text.RegularExpressions; namespace UltimaOnline.Sphere.Connection.Messages { public delegate void AccountDoesNotExistEventHandler(object sender, AccountDoesNotExistEventArgs args); /// <summary> /// Summary description for AccountDoesNotExistMessage. /// </summary> public class AccountDoesNotExistMessage : BaseMessage { #region Members protected Regex m_Regex = new Regex( @"^Account '(.+)' does not exist", RegexOptions.Compiled ); protected string m_Account; #endregion #region Public properties /// <summary> /// Account which doesn't exist. /// </summary> public string Account { get { return m_Account; } } #endregion public AccountDoesNotExistMessage() { } public override bool CanParse(string message) { if(m_Regex.IsMatch(message)) return true; return false; } public override void Parse(string message) { if(!CanParse(message)) throw new MessageParserException("Cannot parse this message.", message); Match match = m_Regex.Match(message); if(!match.Success) return; m_Account = match.Groups[1].Value; } public override void Notify(SphereConnection server) { server.OnAccountDoesNotExist(new AccountDoesNotExistEventArgs(this)); } } public class AccountDoesNotExistEventArgs : System.EventArgs { protected AccountDoesNotExistMessage m_Message; /// <summary> /// Gets the <see cref="Plugin.Messages.AccountDoesNotExistMessage"/> object of this event. /// </summary> public AccountDoesNotExistMessage Message { get { return m_Message; } } /// <summary> /// Instanciates the <see cref="AccountDoesNotExistEventArgs"/> class with a <see cref="AccountDoesNotExistMessage"/> object. /// </summary> /// <param name="msg"></param> public AccountDoesNotExistEventArgs(AccountDoesNotExistMessage msg) { m_Message = msg; } } } --- NEW FILE: ClientKilledMessage.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.Net; using System.Collections; using System.Text.RegularExpressions; using UltimaOnline.Sphere.Connection; namespace UltimaOnline.Sphere.Connection.Messages { public delegate void ClientKilledEventHandler(object sender, ClientKilledEventArgs args); /// <summary> /// Summary description for ClientKilledMessage. /// </summary> [Serializable] public class ClientKilledMessage : BaseMessage { #region Members protected Regex m_Regex = new Regex( @"^([0-9]{2}:[0-9]{2}):([PN]'.+') was killed by ([PN]'(.+)'|[PN]'(.+)',){1,}.", RegexOptions.Compiled ); protected Regex m_MobileRegex = new Regex( @"^([PN])'(.+)'", RegexOptions.Compiled ); protected DateTime m_Time; protected Mobile m_Victim; protected Mobile[] m_Aggressors; #endregion #region Public properties /// <summary> /// The time this message was sent. /// </summary> public DateTime Time { get { return m_Time; } } /// <summary> /// The victim. /// </summary> public Mobile Victim { get { return m_Victim; } } /// <summary> /// Mobiles that aggressed the victim. /// </summary> public Mobile[] Aggressors { get { return m_Aggressors; } } #endregion public ClientKilledMessage() { } public override bool CanParse(string message) { if(m_Regex.IsMatch(message)) return true; return false; } public override void Parse(string message) { if(!CanParse(message)) throw new MessageParserException("Cannot parse this message.", message); Match match = m_Regex.Match(message); if(!match.Success) return; m_Time = DateTime.Parse(match.Groups[1].Value); Mobile victim = new Mobile(); Match victimMatch = m_MobileRegex.Match(match.Groups[2].Value); victim.Type = (victimMatch.Groups[1].Value == "P") ? MobileType.Player : MobileType.Npc; victim.Name = victimMatch.Groups[2].Value; ArrayList aggressors = new ArrayList(); Match aggressMatch = m_MobileRegex.Match(match.Groups[3].Value); string[] tempAggressors = String.Format("{0}{1}", aggressMatch.Groups[1].Value, aggressMatch.Groups[0]).Split(','); foreach (string i in tempAggressors) { Mobile aggressor = new Mobile(); aggressor.Type = (i.Substring(1, 1) == "P") ? MobileType.Player : MobileType.Npc; aggressor.Name = i.Substring(3, i.LastIndexOf("'") - 3); aggressors.Add(aggressor); } m_Victim = victim; m_Aggressors = (Mobile[]) aggressors.ToArray(typeof(Mobile)); } public override void Notify(SphereConnection server) { server.OnClientKilled(new ClientKilledEventArgs(this)); } } [Serializable] public class ClientKilledEventArgs : System.EventArgs { protected ClientKilledMessage m_Message; /// <summary> /// Gets the <see cref="Plugin.Messages.ClientKilledMessage"/> object of this event. /// </summary> public ClientKilledMessage Message { get { return m_Message; } } /// <summary> /// Instanciates the <see cref="ClientKilledEventArgs"/> class with a <see cref="ClientKilledMessage"/> object. /// </summary> /// <param name="msg"></param> public ClientKilledEventArgs(ClientKilledMessage msg) { m_Message = msg; } } } --- NEW FILE: ClientKickedMessage.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.Net; using System.Text.RegularExpressions; namespace UltimaOnline.Sphere.Connection.Messages { public delegate void ClientKickedEventHandler(object sender, ClientKickedEventArgs args); /// <summary> /// Summary description for ClientKickedMessage. /// </summary> [Serializable] public class ClientKickedMessage : BaseMessage { #region Members //17:48:A'Koveras' was KICKed by 'Admin Sully' protected Regex m_Regex = new Regex( @"^([0-9]{2}:[0-9]{2}):A'(.+) was KICKed by '(.+)'", RegexOptions.Compiled ); protected Regex m_Regex2 = new Regex( @"^([0-9]{2}:[0-9]{2}):\((.+)\)A'(.+)' was KICKed by '(.+)'", RegexOptions.Compiled ); protected DateTime m_Time; protected string m_Account; protected string m_Staff; #endregion #region Public properties /// <summary> /// The time this message was sent. /// </summary> public DateTime Time { get { return m_Time; } } /// <summary> /// The banned client's Account /// </summary> public string Account { get { return m_Account; } } /// <summary> /// The source of the Ban. /// </summary> public string Staff { get { return m_Staff; } } #endregion public ClientKickedMessage() { } public override bool CanParse(string message) { if(m_Regex.IsMatch(message)) return true; else if (m_Regex2.IsMatch(message)) return true; return false; } public override void Parse(string message) { if(!CanParse(message)) throw new MessageParserException("Cannot parse this message.", message); Match match = m_Regex.Match(message); if(match.Success) { m_Time = DateTime.Parse(match.Groups[1].Value); m_Account = match.Groups[2].Value; m_Staff = match.Groups[3].Value; } else { match = m_Regex2.Match(message); if (!match.Success) return; m_Time = DateTime.Parse(match.Groups[1].Value); m_Account = match.Groups[3].Value; m_Staff = match.Groups[4].Value; } } public override void Notify(SphereConnection server) { server.OnClientKicked(new ClientKickedEventArgs(this)); } } [Serializable] public class ClientKickedEventArgs : System.EventArgs { protected ClientKickedMessage m_Message; /// <summary> /// Gets the <see cref="Plugin.Messages.ClientKICKedMessage"/> object of this event. /// </summary> public ClientKickedMessage Message { get { return m_Message; } } /// <summary> /// Instanciates the <see cref="ClientKICKedEventArgs"/> class with a <see cref="ClientKICKedMessage"/> object. /// </summary> /// <param name="msg"></param> public ClientKickedEventArgs(ClientKickedMessage msg) { m_Message = msg; } } } --- NEW FILE: ClientPageMessage.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.Net; using System.Text.RegularExpressions; namespace UltimaOnline.Sphere.Connection.Messages { public delegate void ClientPageEventHandler(object sender, ClientPageEventArgs args); /// <summary> /// Summary description for ClientPageMessage. /// </summary> public class ClientPageMessage : BaseMessage { #region Members protected Regex m_Regex = new Regex( @"^([0-9]{2}:[0-9]{2}):GM Page from (.+) \[(.+)\] @ (.+) : (.+)", RegexOptions.Compiled ); protected DateTime m_Time; protected string m_Character; protected string m_Serial; protected Position m_Position; protected string m_Page; #endregion #region Public properties /// <summary> /// The time this message was sent. /// </summary> public DateTime Time { get { return m_Time; } } /// <summary> /// Character name. /// </summary> public string Character { get { return m_Character; } } /// <summary> /// Character serial number. /// </summary> public string Serial { get { return m_Serial; } } /// <summary> /// Character position. /// </summary> public Position Position { get { return m_Position; } } /// <summary> /// Page body. /// </summary> public string Page { get { return m_Page; } } #endregion public ClientPageMessage() { } public override bool CanParse(string message) { if(m_Regex.IsMatch(message)) return true; return false; } public override void Parse(string message) { if(!CanParse(message)) throw new MessageParserException("Cannot parse this message.", message); Match match = m_Regex.Match(message); if(!match.Success) return; m_Time = DateTime.Parse(match.Groups[1].Value); m_Character = match.Groups[2].Value; m_Serial = match.Groups[3].Value; m_Position = Position.Parse(match.Groups[4].Value); m_Page = match.Groups[5].Value; } public override void Notify(SphereConnection server) { server.OnClientPage(new ClientPageEventArgs(this)); } } public class ClientPageEventArgs : System.EventArgs { protected ClientPageMessage m_Message; /// <summary> /// Gets the <see cref="Plugin.Messages.ClientPageMessage"/> object of this event. /// </summary> public ClientPageMessage Message { get { return m_Message; } } /// <summary> /// Instanciates the <see cref="ClientPageEventArgs"/> class with a <see cref="ClientPageMessage"/> object. /// </summary> /// <param name="msg"></param> public ClientPageEventArgs(ClientPageMessage msg) { m_Message = msg; } } } --- NEW FILE: ResyncRestartMessage.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.Net; using System.Text.RegularExpressions; namespace UltimaOnline.Sphere.Connection.Messages { public delegate void ResyncRestartEventHandler(object sender, ResyncRestartEventArgs args); /// <summary> /// Summary description for ResyncRestartMessage. /// </summary> [Serializable] public class ResyncRestartMessage : BaseMessage { #region Members protected Regex m_Regex = new Regex( @"^Resync Restart", RegexOptions.Compiled ); #endregion public ResyncRestartMessage() { } public override bool CanParse(string message) { if(m_Regex.IsMatch(message)) return true; return false; } public override void Parse(string message) { if(!CanParse(message)) throw new MessageParserException("Cannot parse this message.", message); } public override void Notify(SphereConnection server) { server.OnResyncRestart(new ResyncRestartEventArgs(this)); } } [Serializable] public class ResyncRestartEventArgs : System.EventArgs { protected ResyncRestartMessage m_Message; /// <summary> /// Gets the <see cref="Plugin.Messages.ResyncRestartMessage"/> object of this event. /// </summary> public ResyncRestartMessage Message { get { return m_Message; } } /// <summary> /// Instanciates the <see cref="ResyncRestartEventArgs"/> class with a <see cref="ResyncRestartMessage"/> object. /// </summary> /// <param name="msg"></param> public ResyncRestartEventArgs(ResyncRestartMessage msg) { m_Message = msg; } } } --- NEW FILE: VerboseModeDisabledMessage.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.Net; using System.Text.RegularExpressions; namespace UltimaOnline.Sphere.Connection.Messages { public delegate void VerboseModeDisabledEventHandler(object sender, VerboseModeDisabledEventArgs args); /// <summary> /// Summary description for VerboseModeDisabledMessage. /// </summary> public class VerboseModeDisabledMessage : BaseMessage { #region Members protected Regex m_Regex = new Regex( @"^Verbose display Disabled.", RegexOptions.Compiled ); #endregion public VerboseModeDisabledMessage() { } public override bool CanParse(string message) { if(m_Regex.IsMatch(message)) return true; return false; } public override void Parse(string message) { if(!CanParse(message)) throw new MessageParserException("Cannot parse this message.", message); } public override void Notify(SphereConnection server) { server.OnVerboseModeDisabled(new VerboseModeDisabledEventArgs(this)); } } public class VerboseModeDisabledEventArgs : System.EventArgs { protected VerboseModeDisabledMessage m_Message; /// <summary> /// Gets the <see cref="Plugin.Messages.VerboseModeDisabledMessage"/> object of this event. /// </summary> public VerboseModeDisabledMessage Message { get { return m_Message; } } /// <summary> /// Instanciates the <see cref="VerboseModeDisabledEventArgs"/> class with a <see cref="VerboseModeDisabledMessage"/> object. /// </summary> /// <param name="msg"></param> public VerboseModeDisabledEventArgs(VerboseModeDisabledMessage msg) { m_Message = msg; } } } --- NEW FILE: ScriptErrorMessage.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.Net; using System.Text.RegularExpressions; namespace UltimaOnline.Sphere.Connection.Messages { public delegate void ScriptErrorEventHandler(object sender, ScriptErrorEventArgs args); /// <summary> /// Summary description for ScriptErrorMessage. /// </summary> public class ScriptErrorMessage : BaseMessage { #region Members protected Regex m_Regex = new Regex( @"^([0-9]{2}:[0-9]{2}):ERROR:\((.+),([0-9]+)\)(.+)", RegexOptions.Compiled ); protected DateTime m_Time; protected static string m_Script; protected static int m_LineNumber; protected static string m_Error; #endregion #region Public Properties public DateTime Time { get { return m_Time; } } public string Script { get { return m_Script; } } public int LineNumber { get { return m_LineNumber; } } public string Error { get { return m_Error; } } #endregion public ScriptErrorMessage() { } public override bool CanParse(string message) { if(m_Regex.IsMatch(message)) return true; return false; } public override void Parse(string message) { if(!CanParse(message)) throw new MessageParserException("Cannot parse this message.", message); if(m_Regex.IsMatch(message)) { Match match = m_Regex.Match(message); if(!match.Success) return; m_Time = DateTime.Parse(match.Groups[1].Value); m_Script = match.Groups[2].Value; m_LineNumber = Int32.Parse(match.Groups[3].Value); m_Error = match.Groups[4].Value; } } public override void Notify(SphereConnection server) { server.OnScriptError(new ScriptErrorEventArgs(this)); } } public class ScriptErrorEventArgs : System.EventArgs { protected ScriptErrorMessage m_Message; /// <summary> /// Gets the <see cref="Plugin.Messages.ScriptErrorMessage"/> object of this event. /// </summary> public ScriptErrorMessage Message { get { return m_Message; } } /// <summary> /// Instanciates the <see cref="ScriptErrorEventArgs"/> class with a <see cref="ScriptErrorMessage"/> object. /// </summary> /// <param name="msg"></param> public ScriptErrorEventArgs(ScriptErrorMessage msg) { m_Message = msg; } } } --- NEW FILE: HttpRequestMessage.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.Net; using System.Text.RegularExpressions; namespace UltimaOnline.Sphere.Connection.Messages { public delegate void HttpRequestEventHandler(object sender, HttpRequestEventArgs args); /// <summary> /// Summary description for HttpRequestMessage. /// </summary> public class HttpRequestMessage : BaseMessage { #region Members protected Regex m_Regex = new Regex( @"^([0-9]{2}:[0-9]{2}):(.+):HTTP Page Request '(.+)', alive=([01])", RegexOptions.Compiled ); protected DateTime m_Time; protected string m_Socket; protected string m_PageRequest; protected bool m_Alive; #endregion #region Public properties /// <summary> /// The time this message was sent. /// </summary> public DateTime Time { get { return m_Time; } } /// <summary> /// The clients socket ID. /// </summary> public string Socket { get { return m_Socket; } } /// <summary> /// Requested page. /// </summary> public string PageRequest { get { return m_PageRequest; } } /// <summary> /// Is the page alive? /// </summary> public bool Alive { get { return m_Alive; } } #endregion public HttpRequestMessage() { } public override bool CanParse(string message) { if(m_Regex.IsMatch(message)) return true; return false; } public override void Parse(string message) { if(!CanParse(message)) throw new MessageParserException("Cannot parse this message.", message); Match match = m_Regex.Match(message); if(!match.Success) return; m_Time = DateTime.Parse(match.Groups[1].Value); m_Socket = match.Groups[2].Value; m_PageRequest = match.Groups[3].Value; m_Alive = (match.Groups[4].Value == "1") ? true : false; } public override void Notify(SphereConnection server) { server.OnHttpRequest(new HttpRequestEventArgs(this)); } } public class HttpRequestEventArgs : System.EventArgs { protected HttpRequestMessage m_Message; /// <summary> /// Gets the <see cref="Plugin.Messages.HttpRequestMessage"/> object of this event. /// </summary> public HttpRequestMessage Message { get { return m_Message; } } /// <summary> /// Instanciates the <see cref="HttpRequestEventArgs"/> class with a <see cref="HttpRequestMessage"/> object. /// </summary> /// <param name="msg"></param> public HttpRequestEventArgs(HttpRequestMessage msg) { m_Message = msg; } } } --- NEW FILE: ShowValueMessage.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.Net; using System.Text.RegularExpressions; namespace UltimaOnline.Sphere.Connection.Messages { public delegate void ShowValueEventHandler(object sender, ShowValueEventArgs args); /// <summary> /// Summary description for ShowValueMessage. /// </summary> public class ShowValueMessage : BaseMessage { #region Members protected Regex m_Regex = new Regex( @"^'(.+)' for '(.+)' is '(.+)'", RegexOptions.Compiled ); protected Regex m_Regex_null = new Regex( @"^'(.+)' for '(.+)' is ''", RegexOptions.Compiled ); protected static string m_Object; protected static string m_Property; protected static string m_Value; #endregion #region Public Properties public string Object { get { return m_Object; } } public string Property { get { return m_Property; } } public string Value { get { return m_Value; } } #endregion public ShowValueMessage() { } public override bool CanParse(string message) { if(m_Regex.IsMatch(message)) return true; else if (m_Regex_null.IsMatch(message)) return true; return false; } public override void Parse(string message) { if(!CanParse(message)) throw new MessageParserException("Cannot parse this message.", message); if(m_Regex.IsMatch(message)) { Match match = m_Regex.Match(message); if(!match.Success) return; m_Object = match.Groups[2].Value; m_Property = match.Groups[1].Value; m_Value = match.Groups[3].Value; } else if (m_Regex_null.IsMatch(message)) { Match match = m_Regex_null.Match(message); if (!match.Success) return; m_Object = match.Groups[2].Value; m_Property = match.Groups[1].Value; m_Value = ""; } } public override void Notify(SphereConnection server) { server.OnShowValue(new ShowValueEventArgs(this)); } } public class ShowValueEventArgs : System.EventArgs { protected ShowValueMessage m_Message; /// <summary> /// Gets the <see cref="Plugin.Messages.ShowValueMessage"/> object of this event. /// </summary> public ShowValueMessage Message { get { return m_Message; } } /// <summary> /// Instanciates the <see cref="ShowValueEventArgs"/> class with a <see cref="ShowValueMessage"/> object. /// </summary> /// <param name="msg"></param> public ShowValueEventArgs(ShowValueMessage msg) { m_Message = msg; } } } --- NEW FILE: ClientConnectedMessage.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.Net; using System.Text.RegularExpressions; namespace UltimaOnline.Sphere.Connection.Messages { public delegate void ClientConnectedEventHandler(object sender, ClientConnectedEventArgs args); /// <summary> /// Summary description for ClientConnectedMessage. /// </summary> public class ClientConnectedMessage : BaseMessage { #region Members protected Regex m_Regex = new Regex( @"^([0-9]{2}:[0-9]{2}):(.+):Client connected \[Total:([0-9]{1,})\] from '(.+)'\.", RegexOptions.Compiled ); protected DateTime m_Time; protected int m_ClientCount; protected string m_Socket; protected IPAddress m_Address; #endregion #region Public properties /// <summary> /// The time this message was sent. /// </summary> public DateTime Time { get { return m_Time; } } /// <summary> /// The client count at the time of this message. /// </summary> public int ClientCount { get { return m_ClientCount; } } /// <summary> /// The clients socket ID. /// </summary> public string Socket { get { return m_Socket; } } /// <summary> /// IP Address of the client. /// </summary> public IPAddress Address { get { return m_Address; } } #endregion public ClientConnectedMessage() { } public override bool CanParse(string message) { if(m_Regex.IsMatch(message)) return true; return false; } public override void Parse(string message) { if(!CanParse(message)) throw new MessageParserException("Cannot parse this message.", message); Match match = m_Regex.Match(message); if(!match.Success) return; m_Time = DateTime.Parse(match.Groups[1].Value); m_ClientCount = Int32.Parse(match.Groups[3].Value); m_Socket = match.Groups[2].Value; m_Address = IPAddress.Parse(match.Groups[4].Value); } public override void Notify(SphereConnection server) { server.OnClientConnected(new ClientConnectedEventArgs(this)); } } [Serializable] public class ClientConnectedEventArgs : System.EventArgs { protected ClientConnectedMessage m_Message; /// <summary> /// Gets the <see cref="Plugin.Messages.ClientConnectedMessage"/> object of this event. /// </summary> public ClientConnectedMessage Message { get { return m_Message; } } /// <summary> /// Instanciates the <see cref="ClientConnectedEventArgs"/> class with a <see cref="ClientConnectedMessage"/> object. /// </summary> /// <param name="msg"></param> public ClientConnectedEventArgs(ClientConnectedMessage msg) { m_Message = msg; } } } --- NEW FILE: ClientCharacterSelectedMessage.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.Net; using System.Text.RegularExpressions; namespace UltimaOnline.Sphere.Connection.Messages { public delegate void ClientCharacterSelectedEventHandler(object sender, ClientCharacterSelectedEventArgs args); /// <summary> /// Summary description for ClientCharacterSelectedMessage. /// </summary> [Serializable] public class ClientCharacterSelectedMessage : BaseMessage { #region Members protected Regex m_Regex = new Regex( @"^([0-9]{2}:[0-9]{2}):(.+):Setup_Start acct='(.+)', char='(.+)'", RegexOptions.Compiled ); protected DateTime m_Time; protected string m_Socket; protected string m_Account; protected string m_Character; #endregion #region Public properties /// <summary> /// The time this message was sent. /// </summary> public DateTime Time { get { return m_Time; } } /// <summary> /// The clients socket ID. /// </summary> public string Socket { get { return m_Socket; } } /// <summary> /// Account name. /// </summary> public string Account { get { return m_Account; } } /// <summary> /// Character name. /// </summary> public string Character { get { return m_Character; } } #endregion public ClientCharacterSelectedMessage() { } public override bool CanParse(string message) { if(m_Regex.IsMatch(message)) return true; return false; } public override void Parse(string message) { if(!CanParse(message)) throw new MessageParserException("Cannot parse this message.", message); Match match = m_Regex.Match(message); if(!match.Success) return; m_Time = DateTime.Parse(match.Groups[1].Value); m_Socket = match.Groups[2].Value; m_Account = match.Groups[3].Value; m_Character = match.Groups[4].Value; } public override void Notify(SphereConnection server) { server.OnClientCharacterSelected(new ClientCharacterSelectedEventArgs(this)); } } [Serializable] public class ClientCharacterSelectedEventArgs : System.EventArgs { protected ClientCharacterSelectedMessage m_Message; /// <summary> /// Gets the <see cref="Plugin.Messages.ClientCharacterSelectedMessage"/> object of this event. /// </summary> public ClientCharacterSelectedMessage Message { get { return m_Message; } } /// <summary> /// Instanciates the <see cref="ClientCharacterSelectedEventArgs"/> class with a <see cref="ClientCharacterSelectedMessage"/> object. /// </summary> /// <param name="msg"></param> public ClientCharacterSelectedEventArgs(ClientCharacterSelectedMessage msg) { m_Message = msg; } } } --- NEW FILE: ClientLoginMessage.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.Net; using System.Text.RegularExpressions; namespace UltimaOnline.Sphere.Connection.Messages { public delegate void ClientLoginEventHandler(object sender, ClientLoginEventArgs args); /// <summary> /// Summary description for ClientLoginMessage. /// </summary> public class ClientLoginMessage : BaseMessage { #region Members protected Regex m_Regex = new Regex( @"^([0-9]{2}:[0-9]{2}):(.+):Login '(.+)'", RegexOptions.Compiled ); protected DateTime m_Time; protected string m_Socket; protected string m_Account; #endregion #region Public properties /// <summary> /// The time this message was sent. /// </summary> public DateTime Time { get { return m_Time; } } /// <summary> /// The clients socket ID. /// </summary> public string Socket { get { return m_Socket; } } /// <summary> /// Account name. /// </summary> public string Account { get { return m_Account; } } #endregion public ClientLoginMessage() { } public override bool CanParse(string message) { if(m_Regex.IsMatch(message)) return true; return false; } public override void Parse(string message) { if(!CanParse(message)) throw new MessageParserException("Cannot parse this message.", message); Match match = m_Regex.Match(message); if(!match.Success) return; m_Time = DateTime.Parse(match.Groups[1].Value); m_Socket = match.Groups[2].Value; m_Account = match.Groups[3].Value; } public override void Notify(SphereConnection server) { server.OnClientLogin(new ClientLoginEventArgs(this)); } } public class ClientLoginEventArgs : System.EventArgs { protected ClientLoginMessage m_Message; /// <summary> /// Gets the <see cref="Plugin.Messages.ClientLoginMessage"/> object of this event. /// </summary> public ClientLoginMessage Message { get { return m_Message; } } /// <summary> /// Instanciates the <see cref="ClientLoginEventArgs"/> class with a <see cref="ClientLoginMessage"/> object. /// </summary> /// <param name="msg"></param> public ClientLoginEventArgs(ClientLoginMessage msg) { m_Message = msg; } } } --- NEW FILE: ClientDisconnectedMessage.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.Net; using System.Text.RegularExpressions; namespace UltimaOnline.Sphere.Connection.Messages { public delegate void ClientDisconnectedEventHandler(object sender, ClientDisconnectedEventArgs args); /// <summary> /// Summary description for ClientDisconnectedMessage. /// </summary> [Serializable] public class ClientDisconnectedMessage : BaseMessage { #region Members protected Regex m_Regex = new Regex( @"^([0-9]{2}:[0-9]{2}):(.+):Client disconnected \[Total:([0-9]{1,})\]", RegexOptions.Compiled ); protected DateTime m_Time; protected string m_Socket; protected int m_ClientCount; #endregion #region Public properties /// <summary> /// The time this message was sent. /// </summary> public DateTime Time { get { return m_Time; } } /// <summary> /// The clients socket ID. /// </summary> public string Socket { get { return m_Socket; } } /// <summary> /// New client count. /// </summary> public int ClientCount { get { return m_ClientCount; } } #endregion public ClientDisconnectedMessage() { } public override bool CanParse(string message) { if(m_Regex.IsMatch(message)) return true; return false; } public override void Parse(string message) { if(!CanParse(message)) throw new MessageParserException("Cannot parse this message.", message); Match match = m_Regex.Match(message); if(!match.Success) return; m_Time = DateTime.Parse(match.Groups[1].Value); m_Socket = match.Groups[2].Value; m_ClientCount = Int32.Parse(match.Groups[3].Value); } public override void Notify(SphereConnection server) { server.OnClientDisconnected(new ClientDisconnectedEventArgs(this)); } } [Serializable] public class ClientDisconnectedEventArgs : System.EventArgs { protected ClientDisconnectedMessage m_Message; /// <summary> /// Gets the <see cref="Plugin.Messages.ClientDisconnectedMessage"/> object of this event. /// </summary> public ClientDisconnectedMessage Message { get { return m_Message; } } /// <summary> /// Instanciates the <see cref="ClientDisconnectedEventArgs"/> class with a <see cref="ClientDisconnectedMessage"/> object. /// </summary> /// <param name="msg"></param> public ClientDisconnectedEventArgs(ClientDisconnectedMessage msg) { m_Message = msg; } } } --- NEW FILE: BaseMessage.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; namespace UltimaOnline.Sphere.Connection.Messages { /// <summary> /// Summary description for BaseMessage. /// </summary> public abstract class BaseMessage { /// <summary> /// Can this message handler parse the message? /// </summary> /// <param name="message">Message to parse.</param> /// <returns>true if parsable, false if not.</returns> public abstract bool CanParse(string message); /// <summary> /// Parses the message into this message object. /// </summary> /// <param name="message">Message to parse.</param> public abstract void Parse(string message); /// <summary> /// Notifies the plugin of the event. /// </summary> /// <param name="plugin"></param> public abstract void Notify(SphereConnection plugin); } } --- NEW FILE: ServerInfoMessage.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.Net; using System.Text.RegularExpressions; namespace UltimaOnline.Sphere.Connection.Messages { public delegate void ServerInfoEventHandler(object sender, ServerInfoEventArgs args); /// <summary> /// Summary description for ServerInfoMessage. /// </summary> public class ServerInfoMessage : BaseMessage { #region Members protected Regex m_Regex = new Regex( @"^Sphere, Name=(.+), Age=([0-9]{1,}), Clients=([0-9]{1,}), Items=([0-9]{1,}), Chars=([0-9]{1,}), Mem=0K", RegexOptions.Compiled ); protected Regex m_Regex2 = new Regex( @"^Admin=(.*), URL=(.*), Lang=(.+), TZ=([0-9]{1,})", RegexOptions.Compiled ); protected static bool m_FirstDone; protected static bool m_SecondDone; protected static string m_ServerName; protected static string m_Admin; protected static string m_Url; protected static string m_Lang; protected static int m_TimeZone; protected static int m_Age; protected static int m_ClientCount; protected static int m_ItemCount; protected static int m_CharCount; #endregion #region Public properties public string ServerName { get { return m_ServerName; } } public string Admin { get { return m_Admin; } } public string Url { get { return m_Url; } } public string Language { get { return m_Lang; } } public int TimeZone { get { return m_TimeZone; } } public int Age { get { return m_Age; } } public int ClientCount { get { return m_ClientCount; } } public int ItemCount { get { return m_ItemCount; } } public int CharCount { get { return m_CharCount; } } #endregion public ServerInfoMessage() { } public override bool CanParse(string message) { if(m_Regex.IsMatch(message) || m_Regex2.IsMatch(message)) return true; return false; } public override void Parse(string message) { if(!CanParse(message)) throw new MessageParserException("Cannot parse this message.", message); if(m_Regex.IsMatch(message)) { Match match = m_Regex.Match(message); if(!match.Success) return; m_ServerName = match.Groups[1].Value; m_Age = Int32.Parse(match.Groups[2].Value); m_ClientCount = Int32.Parse(match.Groups[3].Value); m_ItemCount = Int32.Parse(match.Groups[4].Value); m_CharCount = Int32.Parse(match.Groups[5].Value); m_FirstDone = true; } else if(m_Regex2.IsMatch(message)) { Match match = m_Regex2.Match(message); if(!match.Success) return; m_Admin = match.Groups[1].Value; m_Url = match.Groups[2].Value; m_Lang = match.Groups[3].Value; m_TimeZone = Int32.Parse(match.Groups[4].Value); m_SecondDone = true; } } public override void Notify(SphereConnection server) { if(m_FirstDone && m_SecondDone) server.OnServerInfo(new ServerInfoEventArgs(this)); } } public class ServerInfoEventArgs : System.EventArgs { protected ServerInfoMessage m_Message; /// <summary> /// Gets the <see cref="Plugin.Messages.ServerInfoMessage"/> object of this event. /// </summary> public ServerInfoMessage Message { get { return m_Message; } } /// <summary> /// Instanciates the <see cref="ServerInfoEventArgs"/> class with a <see cref="ServerInfoMessage"/> object. /// </summary> /// <param name="msg"></param> public ServerInfoEventArgs(ServerInfoMessage msg) { m_Message= msg; } } } --- NEW FILE: SecureModeDisabledMessage.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.Net; using System.Text.RegularExpressions; namespace UltimaOnline.Sphere.Connection.Messages { public delegate void SecureModeDisabledEventHandler(object sender, SecureModeDisabledEventArgs args); /// <summary> /// Summary description for SecureModeDisabledMessage. /// </summary> public class SecureModeDisabledMessage : BaseMessage { #region Members protected Regex m_Regex = new Regex( @"^Secure mode disabled.", RegexOptions.Compiled ); #endregion public SecureModeDisabledMessage() { } public override bool CanParse(string message) { if(m_Regex.IsMatch(message)) return true; return false; } public override void Parse(string message) { if(!CanParse(message)) throw new MessageParserException("Cannot parse this message.", message); } public override void Notify(SphereConnection server) { server.OnSecureModeDisabled(new SecureModeDisabledEventArgs(this)); } } public class SecureModeDisabledEventArgs : System.EventArgs { protected SecureModeDisabledMessage m_Message; /// <summary> /// Gets the <see cref="Plugin.Messages.SecureModeDisabledMessage"/> object of this event. /// </summary> public SecureModeDisabledMessage Message { get { return m_Message; } } /// <summary> /// Instanciates the <see cref="SecureModeDisabledEventArgs"/> class with a <see cref="SecureModeDisabledMessage"/> object. /// </summary> /// <param name="msg"></param> public SecureModeDisabledEventArgs(SecureModeDisabledMessage msg) { m_Message = msg; } } } --- NEW FILE: WorldSaveMessage.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.Net; using System.Text.RegularExpressions; namespace UltimaOnline.Sphere.Connection.Messages { public delegate void WorldSaveEventHandler(object sender, WorldSaveEventArgs args); /// <summary> /// Summary description for WorldSaveMessage. /// </summary> public class WorldSaveMessage : BaseMessage { #region Members protected Regex m_Regex = new Regex( @"^([0-9]{2}:[0-9]{2}):World data saved \((.+)\).", RegexOptions.Compiled ); protected DateTime m_Time; protected string m_SaveFile; #endregion #region Public properties /// <summary> /// The time this message was sent. /// </summary> public DateTime Time { get { return m_Time; } } /// <summary> /// Worldsave file. /// </summary> public string SaveFile { get { return m_SaveFile; } } #endregion public WorldSaveMessage() { } public override bool CanParse(string message) { if(m_Regex.IsMatch(message)) return true; return false; } public override void Parse(string message) { if(!CanParse(message)) throw new MessageParserException("Cannot parse this message.", message); Match match = m_Regex.Match(message); if(!match.Success) return; m_Time = DateTime.Parse(match.Groups[1].Value); m_SaveFile = match.Groups[2].Value; } public override void Notify(SphereConnection server) { server.OnWorldSave(new WorldSaveEventArgs(this)); } } public class WorldSaveEventArgs : System.EventArgs { protected WorldSaveMessage m_Message; /// <summary> /// Gets the <see cref="Plugin.Messages.WorldSaveMessage"/> object of this event. /// </summary> public WorldSaveMessage Message { get { return m_Message; } } /// <summary> /// Instanciates the <see cref="WorldSaveEventArgs"/> class with a <see cref="WorldSaveMessage"/> object. /// </summary> /// <param name="msg"></param> public WorldSaveEventArgs(WorldSaveMessage msg) { m_Message = msg; } } } --- NEW FILE: ResyncCompleteMessage.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.Net; using System.Text.RegularExpressions; namespace UltimaOnline.Sphere.Connection.Messages { public delegate void ResyncCompleteEventHandler(object sender, ResyncCompleteEventArgs args); /// <summary> /// Summary description for ResyncCompleteMessage. /// </summary> [Serializable] public class ResyncCompleteMessage : BaseMessage { #region Members protected Regex m_Regex = new Regex( @"^Resync Complete!", RegexOptions.Compiled ); #endregion public ResyncCompleteMessage() { } public override bool CanParse(string message) { if(m_Regex.IsMatch(message)) return true; return false; } public override void Parse(string message) { if(!CanParse(message)) throw new MessageParserException("Cannot parse this message.", message); } public override void Notify(SphereConnection server) { server.OnResyncComplete(new ResyncCompleteEventArgs(this)); } } [Serializable] public class ResyncCompleteEventArgs : System.EventArgs { protected ResyncCompleteMessage m_Message; /// <summary> /// Gets the <see cref="Plugin.Messages.ResyncCompleteMessage"/> object of this event. /// </summary> public ResyncCompleteMessage Message { get { return m_Message; } } /// <summary> /// Instanciates the <see cref="ResyncCompleteEventArgs"/> class with a <see cref="ResyncCompleteMessage"/> object. /// </summary> /// <param name="msg"></param> public ResyncCompleteEventArgs(ResyncCompleteMessage msg) { m_Message = msg; } } } --- NEW FILE: SecureModeEnabledMessage.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.Net; using System.Text.RegularExpressions; namespace UltimaOnline.Sphere.Connection.Messages { public delegate void SecureModeEnabledEventHandler(object sender, SecureModeEnabledEventArgs args); /// <summary> /// Summary description for SecureModeEnabledMessage. /// </summary> public class SecureModeEnabledMessage : BaseMessage { #region Members protected Regex m_Regex = new Regex( @"^Secure mode re-enabled.", RegexOptions.Compiled ); #endregion public SecureModeEnabledMessage() { } public override bool CanParse(string message) { if(m_Regex.IsMatch(message)) return true; return false; } public override void Parse(string message) { if(!CanParse(message)) throw new MessageParserException("Cannot parse this message.", message); } public override void Notify(SphereConnection server) { server.OnSecureModeEnabled(new SecureModeEnabledEventArgs(this)); } } public class SecureModeEnabledEventArgs : System.EventArgs { protected SecureModeEnabledMessage m_Message; /// <summary> /// Gets the <see cref="Plugin.Messages.SecureModeEnabledMessage"/> object of this event. /// </summary> public SecureModeEnabledMessage Message { get { return m_Message; } } /// <summary> /// Instanciates the <see cref="SecureModeEnabledEventArgs"/> class with a <see cref="SecureModeEnabledMessage"/> object. /// </summary> /// <param name="msg"></param> public SecureModeEnabledEventArgs(SecureModeEnabledMessage msg) { m_Message = msg; } } } --- NEW FILE: ClientBadPasswordMessage.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.Net; using System.Text.RegularExpressions; namespace UltimaOnline.Sphere.Connection.Messages { public delegate void ClientBadPasswordEventHandler(object sender, ClientBadPasswordEventArgs args); /// <summary> /// Summary description for ClientBadPasswordMessage. /// </summary> public class ClientBadPasswordMessage : BaseMessage { #region Members protected Regex m_Regex = new Regex( @"^([0-9]{2}:[0-9]{2}):(.+): '(.+)' bad password", RegexOptions.Compiled ); protected DateTime m_Time; protected string m_Socket; protected string m_Account; #endregion #region Public properties /// <summary> /// The time this message was sent. /// </summary> public DateTime Time { get { return m_Time; } } /// <summary> /// The clients socket ID. /// </summary> public string Socket { get { return m_Socket; } } /// <summary> /// Account name. /// </summary> public string Account { get { return m_Account; } } #endregion public ClientBadPasswordMessage() { } public override bool CanParse(string message) { if(m_Regex.IsMatch(message)) return true; return false; } ... [truncated message content] |
From: Iain M. <iai...@us...> - 2005-07-17 21:54:50
|
Update of /cvsroot/bobbot/Other/UltimaOnline.Sphere.Connection/Messages In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv808/Messages Log Message: Directory /cvsroot/bobbot/Other/UltimaOnline.Sphere.Connection/Messages added to the repository |
From: Iain M. <iai...@us...> - 2005-07-17 21:53:24
|
Update of /cvsroot/bobbot/Other/UltimaOnline.Sphere.Connection In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv541/UltimaOnline.Sphere.Connection Log Message: Directory /cvsroot/bobbot/Other/UltimaOnline.Sphere.Connection added to the repository |
From: Iain M. <iai...@us...> - 2005-07-17 21:53:23
|
Update of /cvsroot/bobbot/Other/UltimaOnline.Sphere.WorldParser In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv541/UltimaOnline.Sphere.WorldParser Log Message: Directory /cvsroot/bobbot/Other/UltimaOnline.Sphere.WorldParser added to the repository |
Update of /cvsroot/bobbot/Other/SphereConnection/Messages In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv32641/SphereConnection/Messages Removed Files: AccountDoesNotExistMessage.cs AdminAccountInUseMessage.cs AdminBadPasswordMessage.cs AdminWelcomeMessage.cs BaseMessage.cs ClientBadPasswordMessage.cs ClientCharacterSelectedMessage.cs ClientCommandMessage.cs ClientConnectedMessage.cs ClientDisconnectedMessage.cs ClientKICKedMessage.cs ClientKilledMessage.cs ClientLoginMessage.cs ClientPageMessage.cs CustomLogMessage.cs HttpRequestMessage.cs ResyncCompleteMessage.cs ResyncPauseMessage.cs ResyncRestartMessage.cs RideLostMessage.cs ScriptErrorMessage.cs SecureModeDisabledMessage.cs SecureModeEnabledMessage.cs ServerInfoMessage.cs ShowValueMessage.cs UnknownCommandMessage.cs VerboseModeDisabledMessage.cs VerboseModeEnabledMessage.cs WorldSaveMessage.cs Log Message: Changes: - Removed Bot.Other.SphereConnection because it has been renamed to UltimaOnline.Sphere.Connection --- AccountDoesNotExistMessage.cs DELETED --- --- ClientKilledMessage.cs DELETED --- --- ClientPageMessage.cs DELETED --- --- ResyncRestartMessage.cs DELETED --- --- VerboseModeDisabledMessage.cs DELETED --- --- ScriptErrorMessage.cs DELETED --- --- HttpRequestMessage.cs DELETED --- --- ShowValueMessage.cs DELETED --- --- ClientConnectedMessage.cs DELETED --- --- ClientCharacterSelectedMessage.cs DELETED --- --- ClientLoginMessage.cs DELETED --- --- ClientDisconnectedMessage.cs DELETED --- --- BaseMessage.cs DELETED --- --- ServerInfoMessage.cs DELETED --- --- SecureModeDisabledMessage.cs DELETED --- --- WorldSaveMessage.cs DELETED --- --- ResyncCompleteMessage.cs DELETED --- --- SecureModeEnabledMessage.cs DELETED --- --- ClientBadPasswordMessage.cs DELETED --- --- ClientKICKedMessage.cs DELETED --- --- UnknownCommandMessage.cs DELETED --- --- ClientCommandMessage.cs DELETED --- --- RideLostMessage.cs DELETED --- --- CustomLogMessage.cs DELETED --- --- VerboseModeEnabledMessage.cs DELETED --- --- AdminBadPasswordMessage.cs DELETED --- --- AdminWelcomeMessage.cs DELETED --- --- ResyncPauseMessage.cs DELETED --- --- AdminAccountInUseMessage.cs DELETED --- |
From: Iain M. <iai...@us...> - 2005-07-17 21:50:59
|
Update of /cvsroot/bobbot/Other/SphereConnection In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv32641/SphereConnection Removed Files: AssemblyInfo.cs MessageParseException.cs SphereConnection.cs Types.cs Log Message: Changes: - Removed Bot.Other.SphereConnection because it has been renamed to UltimaOnline.Sphere.Connection --- Types.cs DELETED --- --- SphereConnection.cs DELETED --- --- AssemblyInfo.cs DELETED --- --- MessageParseException.cs DELETED --- |
Update of /cvsroot/bobbot/Plugins/Sphere/Messages In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv31505/Sphere/Messages Modified Files: HouseKillingMessage.cs PlayerJailedMessage.cs PlayerPunishedMessage.cs PlayerReleasedMessage.cs ResKillingMessage.cs SkillNukeMessage.cs Log Message: Changes: - Updated namespaces to reflect change in SphereConnection assembly Index: SkillNukeMessage.cs =================================================================== RCS file: /cvsroot/bobbot/Plugins/Sphere/Messages/SkillNukeMessage.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** SkillNukeMessage.cs 17 Jul 2005 21:08:56 -0000 1.3 --- SkillNukeMessage.cs 17 Jul 2005 21:46:27 -0000 1.4 *************** *** 27,32 **** using Bot.Plugins.Sphere; ! using Bot.Other.Sphere; ! using Bot.Other.Sphere.Messages; namespace Bot.Plugins.Sphere.Messages --- 27,32 ---- using Bot.Plugins.Sphere; ! using UltimaOnline.Sphere.Connection; ! using UltimaOnline.Sphere.Connection.Messages; namespace Bot.Plugins.Sphere.Messages Index: PlayerReleasedMessage.cs =================================================================== RCS file: /cvsroot/bobbot/Plugins/Sphere/Messages/PlayerReleasedMessage.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** PlayerReleasedMessage.cs 16 Jan 2005 01:24:00 -0000 1.2 --- PlayerReleasedMessage.cs 17 Jul 2005 21:46:27 -0000 1.3 *************** *** 27,32 **** using Bot.Plugins.Sphere; ! using Bot.Other.Sphere; ! using Bot.Other.Sphere.Messages; namespace Bot.Plugins.Sphere.Messages --- 27,32 ---- using Bot.Plugins.Sphere; ! using UltimaOnline.Sphere.Connection; ! using UltimaOnline.Sphere.Connection.Messages; namespace Bot.Plugins.Sphere.Messages Index: HouseKillingMessage.cs =================================================================== RCS file: /cvsroot/bobbot/Plugins/Sphere/Messages/HouseKillingMessage.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** HouseKillingMessage.cs 17 Jul 2005 21:08:56 -0000 1.4 --- HouseKillingMessage.cs 17 Jul 2005 21:46:27 -0000 1.5 *************** *** 27,32 **** using Bot.Plugins.Sphere; ! using Bot.Other.Sphere; ! using Bot.Other.Sphere.Messages; namespace Bot.Plugins.Sphere.Messages --- 27,32 ---- using Bot.Plugins.Sphere; ! using UltimaOnline.Sphere.Connection; ! using UltimaOnline.Sphere.Connection.Messages; namespace Bot.Plugins.Sphere.Messages Index: PlayerPunishedMessage.cs =================================================================== RCS file: /cvsroot/bobbot/Plugins/Sphere/Messages/PlayerPunishedMessage.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** PlayerPunishedMessage.cs 17 Jul 2005 21:08:56 -0000 1.1 --- PlayerPunishedMessage.cs 17 Jul 2005 21:46:27 -0000 1.2 *************** *** 27,32 **** using Bot.Plugins.Sphere; ! using Bot.Other.Sphere; ! using Bot.Other.Sphere.Messages; namespace Bot.Plugins.Sphere.Messages --- 27,32 ---- using Bot.Plugins.Sphere; ! using UltimaOnline.Sphere.Connection; ! using UltimaOnline.Sphere.Connection.Messages; namespace Bot.Plugins.Sphere.Messages Index: ResKillingMessage.cs =================================================================== RCS file: /cvsroot/bobbot/Plugins/Sphere/Messages/ResKillingMessage.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** ResKillingMessage.cs 17 Jul 2005 21:08:56 -0000 1.1 --- ResKillingMessage.cs 17 Jul 2005 21:46:27 -0000 1.2 *************** *** 27,32 **** using Bot.Plugins.Sphere; ! using Bot.Other.Sphere; ! using Bot.Other.Sphere.Messages; namespace Bot.Plugins.Sphere.Messages --- 27,32 ---- using Bot.Plugins.Sphere; ! using UltimaOnline.Sphere.Connection; ! using UltimaOnline.Sphere.Connection.Messages; namespace Bot.Plugins.Sphere.Messages Index: PlayerJailedMessage.cs =================================================================== RCS file: /cvsroot/bobbot/Plugins/Sphere/Messages/PlayerJailedMessage.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** PlayerJailedMessage.cs 20 Feb 2005 18:41:34 -0000 1.3 --- PlayerJailedMessage.cs 17 Jul 2005 21:46:27 -0000 1.4 *************** *** 27,32 **** using Bot.Plugins.Sphere; ! using Bot.Other.Sphere; ! using Bot.Other.Sphere.Messages; namespace Bot.Plugins.Sphere.Messages --- 27,32 ---- using Bot.Plugins.Sphere; ! using UltimaOnline.Sphere.Connection; ! using UltimaOnline.Sphere.Connection.Messages; namespace Bot.Plugins.Sphere.Messages |
From: Iain M. <iai...@us...> - 2005-07-17 21:47:05
|
Update of /cvsroot/bobbot/Plugins/Sphere/LogManagement In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv31505/Sphere/LogManagement Modified Files: LogEntry.cs LogManager.cs Log Message: Changes: - Updated namespaces to reflect change in SphereConnection assembly Index: LogManager.cs =================================================================== RCS file: /cvsroot/bobbot/Plugins/Sphere/LogManagement/LogManager.cs,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** LogManager.cs 17 Jul 2005 21:08:55 -0000 1.7 --- LogManager.cs 17 Jul 2005 21:46:27 -0000 1.8 *************** *** 14,19 **** using Bot.Plugins.Sphere.Messages; ! using Bot.Other.Sphere; ! using Bot.Other.Sphere.Messages; namespace Bot.Plugins.Sphere.LogManagement --- 14,19 ---- using Bot.Plugins.Sphere.Messages; ! using UltimaOnline.Sphere.Connection; ! using UltimaOnline.Sphere.Connection.Messages; namespace Bot.Plugins.Sphere.LogManagement *************** *** 94,98 **** } ! Bot.Other.Sphere.Messages.BaseMessage msg = SphereConnection.Instance.ParseMessage( args.Message ); if (msg is HouseKillingMessage) --- 94,98 ---- } ! UltimaOnline.Sphere.Connection.Messages.BaseMessage msg = SphereConnection.Instance.ParseMessage( args.Message ); if (msg is HouseKillingMessage) Index: LogEntry.cs =================================================================== RCS file: /cvsroot/bobbot/Plugins/Sphere/LogManagement/LogEntry.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** LogEntry.cs 17 Jul 2005 21:08:55 -0000 1.2 --- LogEntry.cs 17 Jul 2005 21:46:27 -0000 1.3 *************** *** 6,11 **** using Bot.Plugins.Sphere.Messages; ! using Bot.Other.Sphere; ! using Bot.Other.Sphere.Messages; namespace Bot.Plugins.Sphere.LogManagement --- 6,11 ---- using Bot.Plugins.Sphere.Messages; ! using UltimaOnline.Sphere.Connection; ! using UltimaOnline.Sphere.Connection.Messages; namespace Bot.Plugins.Sphere.LogManagement |
From: Iain M. <iai...@us...> - 2005-07-17 21:47:05
|
Update of /cvsroot/bobbot/Plugins/Sphere/Accounting In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv31505/Sphere/Accounting Modified Files: AccountRegistration.cs Log Message: Changes: - Updated namespaces to reflect change in SphereConnection assembly Index: AccountRegistration.cs =================================================================== RCS file: /cvsroot/bobbot/Plugins/Sphere/Accounting/AccountRegistration.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** AccountRegistration.cs 26 Feb 2005 22:42:43 -0000 1.4 --- AccountRegistration.cs 17 Jul 2005 21:46:26 -0000 1.5 *************** *** 31,35 **** using Bot.Plugins.Sphere.Messages; ! using Bot.Other.Sphere; namespace Bot.Plugins.Sphere.Accounting --- 31,35 ---- using Bot.Plugins.Sphere.Messages; ! using UltimaOnline.Sphere.Connection; namespace Bot.Plugins.Sphere.Accounting |
From: Iain M. <iai...@us...> - 2005-07-17 21:46:39
|
Update of /cvsroot/bobbot/Plugins/Sphere In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv31505/Sphere Modified Files: SpherePlugin.cs Log Message: Changes: - Updated namespaces to reflect change in SphereConnection assembly Index: SpherePlugin.cs =================================================================== RCS file: /cvsroot/bobbot/Plugins/Sphere/SpherePlugin.cs,v retrieving revision 1.23 retrieving revision 1.24 diff -C2 -d -r1.23 -r1.24 *** SpherePlugin.cs 17 Jul 2005 21:08:55 -0000 1.23 --- SpherePlugin.cs 17 Jul 2005 21:46:29 -0000 1.24 *************** *** 1,3 **** ! #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.Collections.Specialized; using System.Configuration; using System.Text.RegularExpressions; 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.PunishSystem; using Bot.Plugins.Sphere.Accounting; using Bot.Plugins.Sphere.LogManagement; 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 m_JailSystem; private BanSystem m_BanSystem; private LogManager m_LogManager; private MultiAccountSearch m_MultiAccountSearch; private AccountsReader m_AccountsReader; 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_LastKillTimer; private StringCollection m_AccountWatch = new StringCollection(); private StringCollection m_IPWatch = new StringCollection(); private Regex m_IPRegex = new Regex( @"^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$", RegexOptions.Compiled); private StringCollection m_IgnoreList = new StringCollection(); private Timer m_WatchTimer = new Timer(100); private int m_WatchTime = 10000; private Timer m_Timer; private DateTime m_LogNextOpen; 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 = ""; StreamReader peakRead; if (File.Exists("peak.txt")) { 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(); } if (File.Exists("accountwatch.txt")) { m_AccountWatch = new StringCollection(); peakRead = File.OpenText("accountwatch.txt"); string line = peakRead.ReadLine(); while (line != null) { if (line.StartsWith("ACCT")) { m_AccountWatch.Add( line.Remove(0, 5) ); } line = peakRead.ReadLine(); } peakRead.Close(); } if (File.Exists("ipwatch.txt")) { m_IPWatch = new StringCollection(); peakRead = File.OpenText("ipwatch.txt"); string line = peakRead.ReadLine(); while (line != null) { if (line.StartsWith("IP")) { m_IPWatch.Add( line.Remove(0, 3) ); } 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_WatchTimer.AutoReset = false; m_WatchTimer.Interval = m_WatchTime; m_WatchTimer.Elapsed += new ElapsedEventHandler(OnWatchTimerElapsed); m_LastKillTimer = new Timer(); m_LastKillTimer.Interval = 300000; m_LastKillTimer.AutoReset = false; m_LastKillTimer.Elapsed += new ElapsedEventHandler(OnLastKillTimerElapsed); 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_Server.ClientConnected += new ClientConnectedEventHandler(OnClientConnected); m_Server.ClientLogin += new ClientLoginEventHandler(OnClientLogin); m_Server.RegisterHandler(typeof(HouseKillingMessage)); m_Server.RegisterHandler(typeof(PlayerJailedMessage)); m_Server.RegisterHandler(typeof(PlayerReleasedMessage)); m_Server.RegisterHandler(typeof(SkillNukeMessage)); m_Server.RegisterHandler(typeof(PlayerPunishedMessage)); m_Server.RegisterHandler(typeof(ResKillingMessage)); 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); if (this.m_Config.JailDatabase != "-1") m_JailSystem = new JailSystem(this, m_Config.JailDatabase); if (this.m_Config.BanDatabase != "-1") m_BanSystem = new BanSystem(this, m_Config.BanDatabase); m_Accounting = new AccountRegistration(m_Server, m_Config.AccountDatabase); m_SphereAuth = new SphereAuth(this); m_LogManager = new LogManager(m_Server, m_Config.LogDatabase); } 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) { m_PageCount++; 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); } 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); m_JailSystem.SaveDatabase(); m_BanSystem.SaveDatabase(); m_LogManager.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_AccountWatch != null) { if (File.Exists("accountwatch.txt")) File.Delete("accountwatch.txt"); peakWrite = File.CreateText("accountwatch.txt"); foreach (string account in m_AccountWatch) peakWrite.WriteLine( "ACCT={0}", account ); peakWrite.Close(); Log.WriteLine("Sphere", "Written Account List ({0} Accounts)", m_AccountWatch.Count); } if (m_IPWatch != null) { if (File.Exists("ipwatch.txt")) File.Delete("ipwatch.txt"); peakWrite = File.CreateText("ipwatch.txt"); foreach (string ip in m_IPWatch) peakWrite.WriteLine( "IP={0}", ip ); peakWrite.Close(); Log.WriteLine("Sphere", "Written IP List ({0} IPs)", m_IPWatch.Count); } if (m_Timer.Interval == 1) { m_Timer.Stop(); m_Timer.Interval = m_Config.ResyncPeriod; m_Timer.Start(); } MultiAccountSearch.WriteAuthorisedMultis( m_Config.MultiFile ); } private void OnClientConnected(object sender, ClientConnectedEventArgs args) --- 1,3 ---- ! #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.Collections.Specialized; using System.Configuration; using System.Text.RegularExpressions; 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.PunishSystem; using Bot.Plugins.Sphere.Accounting; using Bot.Plugins.Sphere.LogManagement; using UltimaOnline.Sphere.Connection; using UltimaOnline.Sphere.Connection.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 m_JailSystem; private BanSystem m_BanSystem; private LogManager m_LogManager; private MultiAccountSearch m_MultiAccountSearch; private AccountsReader m_AccountsReader; 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_LastKillTimer; private StringCollection m_AccountWatch = new StringCollection(); private StringCollection m_IPWatch = new StringCollection(); private Regex m_IPRegex = new Regex( @"^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$", RegexOptions.Compiled); private StringCollection m_IgnoreList = new StringCollection(); private Timer m_WatchTimer = new Timer(100); private int m_WatchTime = 10000; private Timer m_Timer; private DateTime m_LogNextOpen; 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 = ""; StreamReader peakRead; if (File.Exists("peak.txt")) { 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(); } if (File.Exists("accountwatch.txt")) { m_AccountWatch = new StringCollection(); peakRead = File.OpenText("accountwatch.txt"); string line = peakRead.ReadLine(); while (line != null) { if (line.StartsWith("ACCT")) { m_AccountWatch.Add( line.Remove(0, 5) ); } line = peakRead.ReadLine(); } peakRead.Close(); } if (File.Exists("ipwatch.txt")) { m_IPWatch = new StringCollection(); peakRead = File.OpenText("ipwatch.txt"); string line = peakRead.ReadLine(); while (line != null) { if (line.StartsWith("IP")) { m_IPWatch.Add( line.Remove(0, 3) ); } 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_WatchTimer.AutoReset = false; m_WatchTimer.Interval = m_WatchTime; m_WatchTimer.Elapsed += new ElapsedEventHandler(OnWatchTimerElapsed); m_LastKillTimer = new Timer(); m_LastKillTimer.Interval = 300000; m_LastKillTimer.AutoReset = false; m_LastKillTimer.Elapsed += new ElapsedEventHandler(OnLastKillTimerElapsed); 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_Server.ClientConnected += new ClientConnectedEventHandler(OnClientConnected); m_Server.ClientLogin += new ClientLoginEventHandler(OnClientLogin); m_Server.RegisterHandler(typeof(HouseKillingMessage)); m_Server.RegisterHandler(typeof(PlayerJailedMessage)); m_Server.RegisterHandler(typeof(PlayerReleasedMessage)); m_Server.RegisterHandler(typeof(SkillNukeMessage)); m_Server.RegisterHandler(typeof(PlayerPunishedMessage)); m_Server.RegisterHandler(typeof(ResKillingMessage)); 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); if (this.m_Config.JailDatabase != "-1") m_JailSystem = new JailSystem(this, m_Config.JailDatabase); if (this.m_Config.BanDatabase != "-1") m_BanSystem = new BanSystem(this, m_Config.BanDatabase); m_Accounting = new AccountRegistration(m_Server, m_Config.AccountDatabase); m_SphereAuth = new SphereAuth(this); m_LogManager = new LogManager(m_Server, m_Config.LogDatabase); } 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) { m_PageCount++; 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); } 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); m_JailSystem.SaveDatabase(); m_BanSystem.SaveDatabase(); m_LogManager.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_AccountWatch != null) { if (File.Exists("accountwatch.txt")) File.Delete("accountwatch.txt"); peakWrite = File.CreateText("accountwatch.txt"); foreach (string account in m_AccountWatch) peakWrite.WriteLine( "ACCT={0}", account ); peakWrite.Close(); Log.WriteLine("Sphere", "Written Account List ({0} Accounts)", m_AccountWatch.Count); } if (m_IPWatch != null) { if (File.Exists("ipwatch.txt")) File.Delete("ipwatch.txt"); peakWrite = File.CreateText("ipwatch.txt"); foreach (string ip in m_IPWatch) peakWrite.WriteLine( "IP={0}", ip ); peakWrite.Close(); Log.WriteLine("Sphere", "Written IP List ({0} IPs)", m_IPWatch.Count); } if (m_Timer.Interval == 1) { m_Timer.Stop(); m_Timer.Interval = m_Config.ResyncPeriod; m_Timer.Start(); } MultiAccountSearch.WriteAuthorisedMultis( m_Config.MultiFile ); } private void OnClientConnected(object sender, ClientConnectedEventArgs args) |
From: Iain M. <iai...@us...> - 2005-07-17 21:46:38
|
Update of /cvsroot/bobbot/Plugins/Sphere/PunishSystem In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv31505/Sphere/PunishSystem Modified Files: BanSystem.cs JailSystem.cs Log Message: Changes: - Updated namespaces to reflect change in SphereConnection assembly Index: BanSystem.cs =================================================================== RCS file: /cvsroot/bobbot/Plugins/Sphere/PunishSystem/BanSystem.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** BanSystem.cs 15 Feb 2005 21:47:28 -0000 1.2 --- BanSystem.cs 17 Jul 2005 21:46:27 -0000 1.3 *************** *** 34,39 **** using Bot.Plugins.Sphere.Accounting; ! using Bot.Other.Sphere; ! using Bot.Other.Sphere.Messages; namespace Bot.Plugins.Sphere.PunishSystem --- 34,39 ---- using Bot.Plugins.Sphere.Accounting; ! using UltimaOnline.Sphere.Connection; ! using UltimaOnline.Sphere.Connection.Messages; namespace Bot.Plugins.Sphere.PunishSystem *************** *** 101,105 **** //m_Server.CustomEvent += new EventHandler(OnCustomEvent); ! m_Server.ClientKICKed += new ClientKICKedEventHandler(OnClientKICKed); } #endregion --- 101,105 ---- //m_Server.CustomEvent += new EventHandler(OnCustomEvent); ! m_Server.ClientKicked += new ClientKickedEventHandler(OnClientKicked); } #endregion *************** *** 372,376 **** #endregion ! private void OnClientKICKed(object sender, ClientKICKedEventArgs args) { if (!AddEntry(args.Message.Account, null, args.Message.Staff, "")) --- 372,376 ---- #endregion ! private void OnClientKicked(object sender, ClientKickedEventArgs args) { if (!AddEntry(args.Message.Account, null, args.Message.Staff, "")) Index: JailSystem.cs =================================================================== RCS file: /cvsroot/bobbot/Plugins/Sphere/PunishSystem/JailSystem.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** JailSystem.cs 17 Feb 2005 02:29:28 -0000 1.3 --- JailSystem.cs 17 Jul 2005 21:46:28 -0000 1.4 *************** *** 34,39 **** using Bot.Plugins.Sphere.Accounting; ! using Bot.Other.Sphere; ! using Bot.Other.Sphere.Messages; namespace Bot.Plugins.Sphere.PunishSystem --- 34,39 ---- using Bot.Plugins.Sphere.Accounting; ! using UltimaOnline.Sphere.Connection; ! using UltimaOnline.Sphere.Connection.Messages; namespace Bot.Plugins.Sphere.PunishSystem |
From: Mr S. C. <mrs...@us...> - 2005-07-17 21:09:12
|
Update of /cvsroot/bobbot/Plugins/Sphere/LogManagement In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24008/Sphere/LogManagement Modified Files: LogEntry.cs LogManager.cs Log Message: - Added Accounting.AccountsReader for reading accounts directly from a Sphere Accounts File - Added Accounting.MultiAccountSearch for finding accounts with matching IPs or Passwords. - Added more log messages to find with 'log list' - Added ability o disable Jail and Bans systems by placing '-1' as their database file paths. - Updated Messages from sphere console. Index: LogManager.cs =================================================================== RCS file: /cvsroot/bobbot/Plugins/Sphere/LogManagement/LogManager.cs,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** LogManager.cs 26 Feb 2005 22:41:38 -0000 1.6 --- LogManager.cs 17 Jul 2005 21:08:55 -0000 1.7 *************** *** 108,111 **** --- 108,114 ---- m_LogEntries.Add(new LogEntry(msg, args.Message)); + else if (msg is PlayerPunishedMessage) + m_LogEntries.Add(new LogEntry(msg, args.Message)); + *************** *** 275,289 **** { 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; --- 278,302 ---- { 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); ! } ! else if (entry.Entry is PlayerPunishedMessage) ! { ! PlayerPunishedMessage msg = (PlayerPunishedMessage)entry.Entry; ! return String.Format("{0} Player Jailed. {1} GM={2} Player={3} Length={4} Was At={5}", entry.Time.ToString("[dd/MM/yy - HH:mm]"), handle, msg.GMAccount, msg.PlayerAccount, msg.Length, msg.Position); ! } ! else if (entry.Entry is ResKillingMessage) ! { ! ResKillingMessage msg = (ResKillingMessage)entry.Entry; ! return String.Format("{0} Player Res-Killing. {1} Player={2}", entry.Time.ToString("[dd/MM/yy - HH:mm]"), handle, msg.PlayerAccount); } return null; Index: LogEntry.cs =================================================================== RCS file: /cvsroot/bobbot/Plugins/Sphere/LogManagement/LogEntry.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** LogEntry.cs 15 Feb 2005 21:47:30 -0000 1.1 --- LogEntry.cs 17 Jul 2005 21:08:55 -0000 1.2 *************** *** 121,129 **** m_Entry = SphereConnection.Instance.ParseMessage(m_EntryRaw); - m_EntryType = m_Entry.GetType(); if (m_Entry == null) return false; return true; } --- 121,129 ---- m_Entry = SphereConnection.Instance.ParseMessage(m_EntryRaw); if (m_Entry == null) return false; + m_EntryType = m_Entry.GetType(); return true; } |
From: Mr S. C. <mrs...@us...> - 2005-07-17 21:09:09
|
Update of /cvsroot/bobbot/Plugins/Sphere/Messages In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24008/Sphere/Messages Modified Files: HouseKillingMessage.cs SkillNukeMessage.cs Added Files: PlayerPunishedMessage.cs ResKillingMessage.cs Log Message: - Added Accounting.AccountsReader for reading accounts directly from a Sphere Accounts File - Added Accounting.MultiAccountSearch for finding accounts with matching IPs or Passwords. - Added more log messages to find with 'log list' - Added ability o disable Jail and Bans systems by placing '-1' as their database file paths. - Updated Messages from sphere console. Index: SkillNukeMessage.cs =================================================================== RCS file: /cvsroot/bobbot/Plugins/Sphere/Messages/SkillNukeMessage.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** SkillNukeMessage.cs 20 Feb 2005 18:41:34 -0000 1.2 --- SkillNukeMessage.cs 17 Jul 2005 21:08:56 -0000 1.3 *************** *** 41,47 **** #region Members ! protected Regex m_Regex = new Regex( @"^([0-9]{2}:[0-9]{2}):\((.+)\)'(.+)' \((.+)\) nukes their (.+) skill from (.+)", RegexOptions.Compiled ); --- 41,52 ---- #region Members ! /* protected Regex m_Regex = new Regex( @"^([0-9]{2}:[0-9]{2}):\((.+)\)'(.+)' \((.+)\) nukes their (.+) skill from (.+)", RegexOptions.Compiled + );*/ + + protected Regex m_Regex = new Regex( + @"^([0-9]{2}:[0-9]{2}):\((.+)\)'(.+)' \((.+)\) nukes 10% from their (.+) skill from (.+)", + RegexOptions.Compiled ); Index: HouseKillingMessage.cs =================================================================== RCS file: /cvsroot/bobbot/Plugins/Sphere/Messages/HouseKillingMessage.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** HouseKillingMessage.cs 21 Feb 2005 03:52:11 -0000 1.3 --- HouseKillingMessage.cs 17 Jul 2005 21:08:56 -0000 1.4 *************** *** 42,46 **** protected Regex m_Regex = new Regex( ! @"^([0-9]{2}:[0-9]{2}):\((.+)\)\(Confirmed\) (.+) house killing\? \(Victim=(.+) Uid=(.+) P=(.+) \((.+)\), Aggressor=(.+) Uid=(.+) P=(.+) \((.+)\)\)", RegexOptions.Compiled ); --- 42,46 ---- protected Regex m_Regex = new Regex( ! @"^([0-9]{2}:[0-9]{2}):\((.+)\)\(Confirmed\) (.+) house killing \(Victim=(.+) Uid=(.+) P=(.+) \((.+)\), Aggressor=(.+) Uid=(.+) P=(.+) \((.+)\), DamageFlags=(.+)\)", RegexOptions.Compiled ); *************** *** 57,60 **** --- 57,62 ---- protected string m_AggressorP; + protected string m_DamageFlags; + #endregion *************** *** 103,106 **** --- 105,113 ---- } + public string DamageFlags + { + get { return m_DamageFlags; } + } + #endregion *************** *** 137,140 **** --- 144,149 ---- m_AggressorUid = match.Groups[9].Value; m_AggressorP = String.Format("{0} ({1})", match.Groups[10].Value, match.Groups[11].Value); + + m_DamageFlags = match.Groups[12].Value; } --- NEW FILE: PlayerPunishedMessage.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.Net; using System.Globalization; using System.Text.RegularExpressions; using Bot.Plugins.Sphere; using Bot.Other.Sphere; using Bot.Other.Sphere.Messages; namespace Bot.Plugins.Sphere.Messages { public delegate void PlayerPunishedEventHandler(object sender, PlayerPunishedEventArgs args); /// <summary> /// Summary description for PlayerPunishedMessage. /// </summary> public class PlayerPunishedMessage : BaseMessage { #region Members protected Regex m_Regex = new Regex( @"^([0-9]{2}:[0-9]{2}):\(.+\)(.+) \((.+)\) jails (.+) \((.+)\) for (.+). \(Jailed From: (.+)\)", RegexOptions.Compiled ); //08:43:(msc_punish_system.scp,199)Admin Pilz-e (Pilz-eGM) jails Drake (vaughan) for 72 hours. protected DateTime m_Time; // 1 protected string m_GMName; // 2 protected string m_GMAccount; // 3 protected string m_PlayerName; // 4 protected string m_PlayerAccount; // 5 protected string m_Length; // 6 protected string m_Position; // 7 #endregion #region Public properties /// <summary> /// The time this message was sent. /// </summary> public DateTime Time { get { return m_Time; } } public string GMName { get { return m_GMName; } } public string GMAccount { get { return m_GMAccount; } } public string PlayerName { get { return m_PlayerName; } } public string PlayerAccount { get { return m_PlayerAccount; } } public string Length { get { return m_Length; } } public string Position { get { return m_Position; } } #endregion public PlayerPunishedMessage() { } public override bool CanParse(string message) { if(m_Regex.IsMatch(message)) return true; return false; } public override void Parse(string message) { if(!CanParse(message)) throw new MessageParserException("Cannot parse this message.", message); Match match = m_Regex.Match(message); if(!match.Success) return; m_Time = DateTime.Parse(match.Groups[1].Value); m_GMName = match.Groups[2].Value; m_GMAccount = match.Groups[3].Value; m_PlayerName = match.Groups[4].Value; m_PlayerAccount = match.Groups[5].Value; m_Length = match.Groups[6].Value; m_Position = match.Groups[7].Value; } public override void Notify(SphereConnection server) { server.OnCustomEvent(new PlayerPunishedEventArgs(this)); } } public class PlayerPunishedEventArgs : System.EventArgs { protected PlayerPunishedMessage m_Message; /// <summary> /// Gets the <see cref="Plugin.Messages.PlayerPunishedMessage"/> object of this event. /// </summary> public PlayerPunishedMessage Message { get { return m_Message; } } /// <summary> /// Instanciates the <see cref="PlayerPunishedEventArgs"/> class with a <see cref="PlayerPunishedMessage"/> object. /// </summary> /// <param name="msg"></param> public PlayerPunishedEventArgs(PlayerPunishedMessage msg) { m_Message = msg; } } } --- NEW FILE: ResKillingMessage.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.Net; using System.Globalization; using System.Text.RegularExpressions; using Bot.Plugins.Sphere; using Bot.Other.Sphere; using Bot.Other.Sphere.Messages; namespace Bot.Plugins.Sphere.Messages { public delegate void ResKillingEventHandler(object sender, ResKillingEventArgs args); /// <summary> /// Summary description for ResKillingMessage. /// </summary> public class ResKillingMessage : BaseMessage { #region Members protected Regex m_Regex = new Regex( @"^([0-9]{2}:[0-9]{2}):\((.+)\)(.+) \((.+)\ is jailed for 24 hours for Res-Killing!", RegexOptions.Compiled ); protected DateTime m_Time; protected string m_PlayerName; protected string m_PlayerAccount; #endregion #region Public properties /// <summary> /// The time this message was sent. /// </summary> public DateTime Time { get { return m_Time; } } public string PlayerName { get { return m_PlayerName; } } public string PlayerAccount { get { return m_PlayerAccount; } } #endregion public ResKillingMessage() { } public override bool CanParse(string message) { if(m_Regex.IsMatch(message)) return true; return false; } public override void Parse(string message) { if(!CanParse(message)) throw new MessageParserException("Cannot parse this message.", message); Match match = m_Regex.Match(message); if(!match.Success) return; m_Time = DateTime.Parse(match.Groups[1].Value); m_PlayerName = match.Groups[2].Value; m_PlayerAccount = match.Groups[3].Value; } public override void Notify(SphereConnection server) { server.OnCustomEvent(new ResKillingEventArgs(this)); } } public class ResKillingEventArgs : System.EventArgs { protected ResKillingMessage m_Message; /// <summary> /// Gets the <see cref="Plugin.Messages.ResKillingMessage"/> object of this event. /// </summary> public ResKillingMessage Message { get { return m_Message; } } /// <summary> /// Instanciates the <see cref="ResKillingEventArgs"/> class with a <see cref="ResKillingMessage"/> object. /// </summary> /// <param name="msg"></param> public ResKillingEventArgs(ResKillingMessage msg) { m_Message = msg; } } } |
From: Mr S. C. <mrs...@us...> - 2005-07-17 21:09:04
|
Update of /cvsroot/bobbot/Plugins/Sphere In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24008/Sphere Modified Files: SphereConfig.cs SpherePlugin.cs Log Message: - Added Accounting.AccountsReader for reading accounts directly from a Sphere Accounts File - Added Accounting.MultiAccountSearch for finding accounts with matching IPs or Passwords. - Added more log messages to find with 'log list' - Added ability o disable Jail and Bans systems by placing '-1' as their database file paths. - Updated Messages from sphere console. Index: SpherePlugin.cs =================================================================== RCS file: /cvsroot/bobbot/Plugins/Sphere/SpherePlugin.cs,v retrieving revision 1.22 retrieving revision 1.23 diff -C2 -d -r1.22 -r1.23 *** SpherePlugin.cs 26 Feb 2005 22:41:38 -0000 1.22 --- SpherePlugin.cs 17 Jul 2005 21:08:55 -0000 1.23 *************** *** 1,3 **** ! #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.PunishSystem; using Bot.Plugins.Sphere.Accounting; using Bot.Plugins.Sphere.LogManagement; 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 m_JailSystem; private BanSystem m_BanSystem; private LogManager m_LogManager; 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 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_Server.ClientConnected += new ClientConnectedEventHandler(OnClientConnected); m_Server.RegisterHandler(typeof(HouseKillingMessage)); m_Server.RegisterHandler(typeof(PlayerJailedMessage)); m_Server.RegisterHandler(typeof(PlayerReleasedMessage)); m_Server.RegisterHandler(typeof(SkillNukeMessage)); Bot.Core.Kernel.Instance.Network.Welcome += new WelcomeReplyEventHandler(OnNetworkWelcome); 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(this, m_Config.JailDatabase); m_BanSystem = new BanSystem(this, m_Config.BanDatabase); m_Accounting = new AccountRegistration(m_Server, m_Config.AccountDatabase); m_SphereAuth = new SphereAuth(this); m_LogManager = new LogManager(m_Server, m_Config.LogDatabase); } 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) { m_PageCount++; 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); } 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); m_JailSystem.SaveDatabase(); m_BanSystem.SaveDatabase(); m_LogManager.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(); } } private void OnClientConnected(object sender, ClientConnectedEventArgs args) --- 1,3 ---- ! #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.Collections.Specialized; using System.Configuration; using System.Text.RegularExpressions; 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.PunishSystem; using Bot.Plugins.Sphere.Accounting; using Bot.Plugins.Sphere.LogManagement; 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 m_JailSystem; private BanSystem m_BanSystem; private LogManager m_LogManager; private MultiAccountSearch m_MultiAccountSearch; private AccountsReader m_AccountsReader; 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_LastKillTimer; private StringCollection m_AccountWatch = new StringCollection(); private StringCollection m_IPWatch = new StringCollection(); private Regex m_IPRegex = new Regex( @"^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$", RegexOptions.Compiled); private StringCollection m_IgnoreList = new StringCollection(); private Timer m_WatchTimer = new Timer(100); private int m_WatchTime = 10000; private Timer m_Timer; private DateTime m_LogNextOpen; 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 = ""; StreamReader peakRead; if (File.Exists("peak.txt")) { 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(); } if (File.Exists("accountwatch.txt")) { m_AccountWatch = new StringCollection(); peakRead = File.OpenText("accountwatch.txt"); string line = peakRead.ReadLine(); while (line != null) { if (line.StartsWith("ACCT")) { m_AccountWatch.Add( line.Remove(0, 5) ); } line = peakRead.ReadLine(); } peakRead.Close(); } if (File.Exists("ipwatch.txt")) { m_IPWatch = new StringCollection(); peakRead = File.OpenText("ipwatch.txt"); string line = peakRead.ReadLine(); while (line != null) { if (line.StartsWith("IP")) { m_IPWatch.Add( line.Remove(0, 3) ); } 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_WatchTimer.AutoReset = false; m_WatchTimer.Interval = m_WatchTime; m_WatchTimer.Elapsed += new ElapsedEventHandler(OnWatchTimerElapsed); m_LastKillTimer = new Timer(); m_LastKillTimer.Interval = 300000; m_LastKillTimer.AutoReset = false; m_LastKillTimer.Elapsed += new ElapsedEventHandler(OnLastKillTimerElapsed); 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_Server.ClientConnected += new ClientConnectedEventHandler(OnClientConnected); m_Server.ClientLogin += new ClientLoginEventHandler(OnClientLogin); m_Server.RegisterHandler(typeof(HouseKillingMessage)); m_Server.RegisterHandler(typeof(PlayerJailedMessage)); m_Server.RegisterHandler(typeof(PlayerReleasedMessage)); m_Server.RegisterHandler(typeof(SkillNukeMessage)); m_Server.RegisterHandler(typeof(PlayerPunishedMessage)); m_Server.RegisterHandler(typeof(ResKillingMessage)); 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); if (this.m_Config.JailDatabase != "-1") m_JailSystem = new JailSystem(this, m_Config.JailDatabase); if (this.m_Config.BanDatabase != "-1") m_BanSystem = new BanSystem(this, m_Config.BanDatabase); m_Accounting = new AccountRegistration(m_Server, m_Config.AccountDatabase); m_SphereAuth = new SphereAuth(this); m_LogManager = new LogManager(m_Server, m_Config.LogDatabase); } 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) { m_PageCount++; 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); } 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); m_JailSystem.SaveDatabase(); m_BanSystem.SaveDatabase(); m_LogManager.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_AccountWatch != null) { if (File.Exists("accountwatch.txt")) File.Delete("accountwatch.txt"); peakWrite = File.CreateText("accountwatch.txt"); foreach (string account in m_AccountWatch) peakWrite.WriteLine( "ACCT={0}", account ); peakWrite.Close(); Log.WriteLine("Sphere", "Written Account List ({0} Accounts)", m_AccountWatch.Count); } if (m_IPWatch != null) { if (File.Exists("ipwatch.txt")) File.Delete("ipwatch.txt"); peakWrite = File.CreateText("ipwatch.txt"); foreach (string ip in m_IPWatch) peakWrite.WriteLine( "IP={0}", ip ); peakWrite.Close(); Log.WriteLine("Sphere", "Written IP List ({0} IPs)", m_IPWatch.Count); } if (m_Timer.Interval == 1) { m_Timer.Stop(); m_Timer.Interval = m_Config.ResyncPeriod; m_Timer.Start(); } MultiAccountSearch.WriteAuthorisedMultis( m_Config.MultiFile ); } private void OnClientConnected(object sender, ClientConnectedEventArgs args) *************** *** 7,17 **** if (args.Message.ClientCount > m_ClientPeak) m_ClientPeak = args.Message.ClientCount; - } #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 #region Connection Commands [AllowCondition("LothStaff", AccountPriv.GM, AllowConditionUsage.GreaterThanOrEqual, AllowConditionTarget.User)] [AllowCondition("StaffChannel", true, AllowConditionUsage.Equals, AllowConditionTarget.Channel)] [ChannelCommand("!recon")] private void ReconCommand(NetworkChannel chan, NetworkUser user, string[] args) { 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)] [AllowCondition("StaffChannel", true, AllowConditionUsage.Equals, AllowConditionTarget.Channel)] [ChannelCommand("!discon")] private void DisconCommand(NetworkChannel chan, NetworkUser user, string[] args) { if (m_Server.IsConnected) m_Server.Disconnect(); else chan.SendMessage("Not Connected To Server."); } #endregion #region Misc Commands [AllowCondition("LothStaff", AccountPriv.Admin, AllowConditionUsage.GreaterThanOrEqual, AllowConditionTarget.User)] [AllowCondition("StaffChannel", true, AllowConditionUsage.Equals, AllowConditionTarget.Channel)] [ChannelCommand("!resync")] private void ResyncCommand(NetworkChannel chan, NetworkUser user, string[] args) { if (!m_Server.IsConnected) { chan.SendMessage("Not Connected To Server"); return; } m_Server.WriteLine("r"); m_Server.WriteLine("r"); chan.SendMessage("Done."); } [AllowCondition("LothStaff", AccountPriv.GM, AllowConditionUsage.GreaterThanOrEqual, AllowConditionTarget.User)] [AllowCondition("StaffChannel", true, AllowConditionUsage.Equals, AllowConditionTarget.Channel)] [ChannelCommand("!broadcast")] private void BroadcastCommand(NetworkChannel chan, NetworkUser user, string[] args) { if (args.Length < 1) { chan.SendMessage("You didn't specify a message to send."); return; } if (!m_Server.IsConnected) { chan.SendMessage("Not Connected To Server"); return; } string message = ""; foreach (string i in args) message += " " + i; Kernel.Instance.Network.SendChannelMessage(m_Config.PublicChannel, "Broadcast: {0}", message); Log.WriteLine("Sphere", "Broadcast:{0}", message); if (message.Length < 70) { m_Server.WriteLine("b" + message); } else { message = message.Trim(); while (message.Length > 70) { m_Server.WriteLine("b " + message.Substring(0, 70)); message = message.Remove(0, 70); } m_Server.WriteLine("b " + message); } } [AllowCondition("LothStaff", AccountPriv.GM, AllowConditionUsage.GreaterThanOrEqual, AllowConditionTarget.User)] [AllowCondition("StaffChannel", true, AllowConditionUsage.Equals, AllowConditionTarget.Channel)] [ChannelCommand("!broadcastirc")] private void BroadcastIrcCommand(NetworkChannel chan, NetworkUser user, string[] args) { if (args.Length < 1) { Kernel.Instance.Network.SendChannelMessage(chan, "You didn't specify a message to send."); return; } if (!m_Server.IsConnected) { chan.SendMessage("Not Connected To Server"); 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)] [AllowCondition("StaffChannel", true, AllowConditionUsage.Equals, AllowConditionTarget.Channel)] [ChannelCommand("!go")] private void GoCommand(NetworkChannel chan, NetworkUser user, string[] args) { if (args.Length < 2) { chan.SendMessage("Usage: !Go <uid> <message>"); return; } if (!m_Server.IsConnected) { chan.SendMessage("Not Connected To Server"); return; } string message = ""; foreach (string i in args) { if (i != args[0]) message += " " + i; } if (message.Length > 50) { chan.SendMessage("The specified message is too long. You cannot use more than 50 characters."); return; } m_Server.WriteLine("var.lothbot_target={0}", args[0]); m_Server.WriteLine("uid.{0}.respondtoplayer {1}", m_LothBotUid, message.Trim()); } [AllowCondition("LothStaff", AccountPriv.GM, AllowConditionUsage.GreaterThanOrEqual)] [PrivateCommand("admin listlog")] private void AdminListLogCommand(NetworkUser user, string[] args) { 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 (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; } } } #endregion #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 #region Ban Commands [PrivateCommand("ban")] private void BanCommand(NetworkUser user, string[] args) { if (args.Length <= 0) { user.SendNotice("Incorrect Usage. (Ban <command> [<arguments>])"); user.SendNotice("Following commands are available to you"); user.SendNotice("Use 'Ban Help <command>' for more information"); user.SendNotice("------------------------------------------------"); user.SendNotice("Ban Info Displays ban entry information"); user.SendNotice("Ban List Displays full list of banned accounts."); if (m_SphereAuth.IsStaff(user)) { user.SendNotice("Ban Add Bans an account."); if (m_SphereAuth.GetStaffPriv(user) < AccountPriv.GM) return; user.SendNotice("Ban Edit Edits a ban entry."); if (m_SphereAuth.GetStaffPriv(user) < AccountPriv.Admin) return; user.SendNotice("Ban Del Unbans an account."); user.SendNotice("Ban Save Forces the Ban 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 < 2) { user.SendNotice("Incorrect Arguments: 'Ban Add <Account> [<Reason>]'"); return; } if (m_BanSystem.IsBanned(args[1])) { user.SendNotice("Account '{0}' is already banned!", args[1]); return; } string banargs = ""; for (int i = 2; i < args.Length; i++) banargs += " " + args[i]; if (m_BanSystem.Ban(args[1], null, user.Nickname, banargs.Trim())) user.SendNotice("'{0}' banned!", args[1]); else user.SendNotice("Unable to ban '{0}'", args[1]); return; } case "del": { if (!m_SphereAuth.IsStaff(user) || (m_SphereAuth.GetStaffPriv(user) < AccountPriv.Admin)) { user.SendNotice("You cannot use this command."); return; } if (args.Length < 2) { user.SendNotice("Incorrect Arguments: 'Ban Del <Account>'"); return; } if (!m_BanSystem.IsBanned(args[1])) { user.SendNotice("Account '{0}' wasn't banned!", args[1]); return; } if (m_BanSystem.UnBan(args[1], user.Nickname)) user.SendNotice("'{0}' unbanned!", args[1]); else user.SendNotice("Unable to unban '{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: 'Ban Edit <Account> <Reason>'"); return; } if (!m_BanSystem.IsBanned(args[1])) { user.SendNotice("Account '{0}' wasn't banned!", args[1]); return; } string banargs = ""; for (int i = 2; i < args.Length; i++) banargs += " " + args[i]; if (m_BanSystem.EditBan(args[1], user.Nickname, banargs.Trim())) user.SendNotice("'{0}'s ban entry is edited!", args[1]); else user.SendNotice("Unable to edit ban entry '{0}'!", args[1]); return; } case "list": { if (m_BanSystem.BannedAccounts <= 0) { user.SendNotice("No Accounts are Banned!"); return; } foreach (BanEntry entry in m_BanSystem.GetBanEntryList()) { user.SendNotice("Account: {0}", entry.Account); } return; } case "info": { if (args.Length < 2) { user.SendNotice("Incorrect Arguments: 'Ban Info <Account>'"); return; } BanEntry entry = m_BanSystem.GetBanEntry(args[1]); if (entry != null) { user.SendNotice("Account: {0}", entry.Account); user.SendNotice("Character: {0}", entry.Character); user.SendNotice("Banned By: {0}", entry.BannedBy); user.SendNotice("Ban Date: {0}", entry.BannedOn); user.SendNotice("Reason: {0}", entry.Reason); } else user.SendNotice("Account '{0}' Not Banned!", 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_BanSystem.SaveDatabase()) user.SendNotice("Database Saved Successfully."); else user.SendNotice("Database Failed to Save!"); return; } case "help": { if (args.Length < 2) { user.SendNotice("Incorrect Arguments: 'Ban 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} Ban Add <Account> [<Reason>]", Kernel.Instance.Network.Nickname); user.SendNotice("Adds a new ban database entry for <Account>. The account will"); user.SendNotice("automatically be banned ingame."); 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} Ban Add myAccount", Kernel.Instance.Network.Nickname); user.SendNotice(" /msg {0} Ban Add myAccount Banned for injection abuse.", Kernel.Instance.Network.Nickname); return; } case "del": { 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} Ban Del <Account>", Kernel.Instance.Network.Nickname); user.SendNotice("Deletes the entry for <Account> from the database. The account"); user.SendNotice("will automatically be unbanned ingame."); user.SendNotice("Example: /msg {0} Ban 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} Ban Edit <Account> <Reason>", Kernel.Instance.Network.Nickname); user.SendNotice("Edits the entry for <Account> in the database, exchanging the."); user.SendNotice("current Reason to <Reason>."); user.SendNotice("The 'Banned By' property of the ban 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(" /msg {0} Ban Edit myAccount Banned for injection 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} Ban Save", Kernel.Instance.Network.Nickname); user.SendNotice("Forces the Ban Database to be saved immediately. Unsaved ban"); user.SendNotice("entries will result in players not being released if the Bot"); user.SendNotice("is restarted."); user.SendNotice("Example: /msg {0} Ban Save", Kernel.Instance.Network.Nickname); return; } case "list": { user.SendNotice("/msg {0} Ban List", Kernel.Instance.Network.Nickname); user.SendNotice("Displays a list of all the currently banned accounts, along with"); user.SendNotice("their release dates. For more information on a ban entry, use"); user.SendNotice("Ban Info"); user.SendNotice("Example: /msg {0} Ban List", Kernel.Instance.Network.Nickname); return; } case "info": { user.SendNotice("/msg {0} Ban Info <Account>", Kernel.Instance.Network.Nickname); user.SendNotice("Displays information on <Account>'s ban entry."); user.SendNotice("Example: /msg {0} Ban 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 'Ban Help <command>' for more information"); user.SendNotice("------------------------------------------------"); user.SendNotice("Ban Info Displays ban entry information"); user.SendNotice("Ban List Displays full list of banned accounts."); if (m_SphereAuth.IsStaff(user)) { user.SendNotice("Ban Add Bans an account."); if (m_SphereAuth.GetStaffPriv(user) < AccountPriv.GM) return; user.SendNotice("Ban Edit Edits a ban entry."); if (m_SphereAuth.GetStaffPriv(user) < AccountPriv.Admin) return; user.SendNotice("Ban Del Unbans an account."); user.SendNotice("Ban Save Forces the Ban Database to be saved."); } return; } } } #endregion #region Page Commands /* [AllowCondition("LothStaff", AccountPriv.Counselor, AllowConditionUsage.GreaterThanOrEqual, AllowConditionTarget.User)] [AllowCondition("StaffChannel", true, AllowConditionUsage.Equals, AllowConditionTarget.Channel)] [ChannelCommand("!pages")] private void PagesCommand(NetworkChannel chan, NetworkUser user, string[] args) { if (!m_Server.IsConnected) { chan.SendMessage("Not Connected To Server"); return; } int pages = (int)m_Server.GetProperty("GMPAGES", typeof(int)); if (pages <= 0) { user.SendNotice("There are no pages to list!"); return; } user.SendNotice("Pages: {0}", pages); for (int i = 0; i < pages; i++) { user.SendNotice( "{0}. Time=\"{1} minutes ago\" Account=\"{2}\" Reason=\"{3}\"", (i + 1), (Int32.Parse((string)m_Server.GetProperty(String.Format("GMPAGE.{0}.TIME", i)), System.Globalization.NumberStyles.HexNumber) / 60), (string)m_Server.GetProperty(String.Format("GMPAGE.{0}.ACCOUNT", i)), (string)m_Server.GetProperty(String.Format("GMPAGE.{0}.REASON", i)) ); } } [AllowCondition("LothStaff", AccountPriv.Counselor, AllowConditionUsage.GreaterThanOrEqual, AllowConditionTarget.User)] [AllowCondition("StaffChannel", true, AllowConditionUsage.Equals, AllowConditionTarget.Channel)] [ChannelCommand("!page delete")] private void PageCommand(NetworkChannel chan, NetworkUser user, string[] args) { if (!m_Server.IsConnected) { chan.SendMessage("Not Connected To Server"); return; } if (args.Length <= 0) { PagesCommand(chan, user, args); return; } int page; try {page = Int32.Parse(args[0]) - 1; } catch { return; } if (page < 0) { chan.SendMe... [truncated message content] |
From: Mr S. C. <mrs...@us...> - 2005-07-17 21:09:04
|
Update of /cvsroot/bobbot/Plugins/Sphere/Accounting In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24008/Sphere/Accounting Modified Files: Account.cs Added Files: AccountsReader.cs MultiAccountSearch.cs Log Message: - Added Accounting.AccountsReader for reading accounts directly from a Sphere Accounts File - Added Accounting.MultiAccountSearch for finding accounts with matching IPs or Passwords. - Added more log messages to find with 'log list' - Added ability o disable Jail and Bans systems by placing '-1' as their database file paths. - Updated Messages from sphere console. Index: Account.cs =================================================================== RCS file: /cvsroot/bobbot/Plugins/Sphere/Accounting/Account.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** Account.cs 16 Jan 2005 20:07:49 -0000 1.2 --- Account.cs 17 Jul 2005 21:08:54 -0000 1.3 *************** *** 21,24 **** --- 21,26 ---- using System; + using System.Collections; + using System.Globalization; namespace Bot.Plugins.Sphere.Accounting *************** *** 41,59 **** protected string m_Name; ! protected string m_Password; ! protected AccountPriv m_Plevel; ! protected int m_Priv; ! protected int m_TotalConnectTime; ! protected int m_LastConnectTime; ! protected int m_LastCharUID; protected DateTime m_FirstConnectDate; ! protected string m_FirstIP; protected DateTime m_LastConnectDate; ! protected string m_LastIP; ! protected string m_ChatName; ! protected string m_Lang; ! protected int m_Chars; ! protected bool m_Jailed; ! protected bool m_Blocked; #endregion --- 43,62 ---- protected string m_Name; ! protected string m_Password = ""; ! protected AccountPriv m_Plevel = AccountPriv.Player; ! protected int m_Priv = 0; ! protected int m_TotalConnectTime = 0; ! protected int m_LastConnectTime = 0; ! protected int m_LastCharUID = 0; protected DateTime m_FirstConnectDate; ! protected string m_FirstIP = ""; protected DateTime m_LastConnectDate; ! protected string m_LastIP = ""; ! protected string m_ChatName = ""; ! protected string m_Lang = ""; ! protected int m_Chars = 0; ! protected bool m_Jailed = false; ! protected bool m_Blocked = false; ! protected ArrayList m_CharUIDs; #endregion *************** *** 131,135 **** public int Chars { ! get { return m_Chars; } } --- 134,144 ---- public int Chars { ! get ! { ! if (m_CharUIDs == null) ! return m_Chars; ! ! return m_CharUIDs.Count; ! } } *************** *** 144,151 **** --- 153,176 ---- } + public int[] CharUIDs + { + get + { + if (m_CharUIDs == null) + return null; + + return (int[])m_CharUIDs.ToArray(typeof(int)); + } + } + #endregion #region Constructor + public Account(string name) + { + this.m_Name = name; + } + public Account(string name, string password, AccountPriv plevel, int priv, int totalconnect, int lastconnect, int lastcharuid, DateTime firstconnectdate, DateTime lastconnectdate, string firstip, string lastip, string chatname, string lang, int chars, bool jail, bool block) { *************** *** 230,234 **** #endregion ! #region Public methods public static AccountPriv StringToPriv(string priv) --- 255,259 ---- #endregion ! #region Static methods public static AccountPriv StringToPriv(string priv) *************** *** 317,320 **** --- 342,444 ---- #endregion + + #region Public methods + + public void SetProp( string property , string value ) + { + property = property.ToLower(); + switch (property) + { + case "plevel": + { + this.m_Plevel = Account.StringToPriv( value ); + break; + } + case "charuid": + { + if (this.m_CharUIDs == null) + m_CharUIDs = new ArrayList(); + + m_CharUIDs.Add(Int32.Parse( value, NumberStyles.HexNumber )); + break; + } + case "lastcharuid": + { + m_LastCharUID = Int32.Parse( value, NumberStyles.HexNumber ); + break; + } + case "totalconnecttime": + { + m_TotalConnectTime = Int32.Parse( value ); + break; + } + case "priv": + { + m_Priv = Int32.Parse( value, NumberStyles.HexNumber ); + break; + } + case "password": + { + m_Password = value; + break; + } + case "lastconnecttime": + { + m_LastConnectTime = Int32.Parse( value ); + break; + } + case "firstconnectdate": + { + m_FirstConnectDate = DateTime.Parse( value ); + break; + } + case "lastconnectdate": + { + m_LastConnectDate = DateTime.Parse( value ); + break; + } + case "firstip": + { + m_FirstIP = value; + break; + } + case "lastip": + { + m_LastIP = value; + break; + } + case "chatname": + { + m_ChatName = value; + break; + } + case "lang": + { + m_Lang = value; + break; + } + case "block": + { + m_Blocked = (value == "1"); + break; + } + case "jail": + { + m_Jailed = (value == "1"); + break; + } + } + } + + public string GetDisplayName() + { + if (m_Blocked) + return string.Format("4 {0}", m_Name); + else if (m_Jailed) + return string.Format("3 {0}", m_Name); + return m_Name; + } + + #endregion } } --- NEW FILE: AccountsReader.cs --- using System; using System.Collections; using System.IO; using System.Text.RegularExpressions; namespace Bot.Plugins.Sphere.Accounting { public class AccountsReader { #region Private members private string m_AccountsFile; private StreamReader m_AccountsReader; private ArrayList m_Accounts; private Regex m_RegexAccount = new Regex(@"^\[(.+)\]", RegexOptions.Compiled); private Regex m_RegexAccountProp = new Regex(@"^(.+)=(.+)", RegexOptions.Compiled); #endregion #region Public properties public string AccountsFile { get { return m_AccountsFile; } } public Account[] Accounts { get { return (Account[])m_Accounts.ToArray(typeof(Account)); } } public DateTime AccountsDate { get { return new FileInfo(m_AccountsFile).LastWriteTime; } } #endregion #region Constructor public AccountsReader(string file) { m_AccountsFile = file; } #endregion #region Public methods public Account[] Read() { m_Accounts = new ArrayList(); m_AccountsReader = File.OpenText(m_AccountsFile); string line = m_AccountsReader.ReadLine(); Account account; while (line != null) { if (m_RegexAccount.IsMatch( line )) { account = new Account( m_RegexAccount.Match( line ).Groups[1].Value ); line = m_AccountsReader.ReadLine(); while ((line != null) && !(m_RegexAccount.IsMatch( line ))) { if (m_RegexAccountProp.IsMatch( line )) { Match match = m_RegexAccountProp.Match( line ); account.SetProp( match.Groups[1].Value , match.Groups[2].Value ); } line = m_AccountsReader.ReadLine(); } m_Accounts.Add( account ); continue; } line = m_AccountsReader.ReadLine(); } m_AccountsReader.Close(); return (Account[])m_Accounts.ToArray(typeof(Account)); } #endregion } } --- NEW FILE: MultiAccountSearch.cs --- using System; using System.Collections; using System.IO; namespace Bot.Plugins.Sphere.Accounting { public class MultiAccountSearch { #region Private members private Account[] m_Accounts; private static AuthorisedMulti[] AuthorisedMultis; #endregion #region Constructor public MultiAccountSearch(Account[] accounts) { m_Accounts = accounts; } internal MultiAccountSearch(Account[] accounts, AuthorisedMulti[] multis) { m_Accounts = accounts; AuthorisedMultis = multis; } #endregion #region Static Methods internal static int ReadAuthorisedMultis(string filename) { if (!File.Exists(filename)) return 0; AuthorisedMulti[] multis = null; StreamReader file = File.OpenText( filename ); multis = new AuthorisedMulti[ int.Parse(file.ReadLine()) ]; int index = 0; while (index < multis.Length) { multis[index] = new AuthorisedMulti( file.ReadLine().Split(',') ); index++; } file.Close(); AuthorisedMultis = multis; return multis.Length; } internal static void WriteAuthorisedMultis(string filename) { if (AuthorisedMultis == null) return; if (File.Exists(filename)) File.Delete(filename); StreamWriter file = File.CreateText( filename ); file.WriteLine("{0}", AuthorisedMultis.Length); foreach (AuthorisedMulti multi in AuthorisedMultis) file.WriteLine("{0}", multi.GetAccountString()); file.Close(); } internal static string AddMulti(string[] accts, int start) { if (accts.Length < (start + 2)) return "You must specify at least 2 accounts to add to the authorised multi account list."; string[] accounts = new string[accts.Length - start]; Array.Copy( accts, start, accounts, 0, accts.Length - start); foreach (string account in accounts) { foreach (AuthorisedMulti multi in AuthorisedMultis) { if (multi.ContainsAccount( account )) return string.Format("Account '{0}' has already been added to the authorised multis list.", account); } } ArrayList multis = new ArrayList( AuthorisedMultis ); multis.Add( new AuthorisedMulti( accounts )); AuthorisedMultis = (AuthorisedMulti[])multis.ToArray(typeof(AuthorisedMulti)); return string.Format("Accounts have been authorised for use from the same location. (ID: {0})", (AuthorisedMultis.Length - 1) ); } internal static string DelMulti(string account) { foreach (AuthorisedMulti multi in AuthorisedMultis) { if (multi.ContainsAccount( account )) { if (multi.Accounts.Length <= 2) { ArrayList multis = new ArrayList( AuthorisedMultis ); multis.Remove( multi ); AuthorisedMultis = (AuthorisedMulti[])multis.ToArray(typeof(AuthorisedMulti)); } else multi.RemoveAccount( account ); return string.Format("Account '{0}' has been remove from the authorised list of accounts.", account); } } return string.Format("The account '{0}' was not authorised for multiple accounts!", account); } internal static string[] GetAuthorisedAccounts(int record) { if (AuthorisedMultis == null || AuthorisedMultis.Length <= 0 || record < 0 || record >= AuthorisedMultis.Length) return null; return AuthorisedMultis[record].Accounts; } #endregion #region Public methods #region Password Scan public Account[] ScanPassword(string account) { account = account.ToLower(); foreach (Account acct in m_Accounts) { if (acct.Name.ToLower() == account) return ScanPassword(acct); } return null; } public Account[] ScanPassword(Account acct) { string password = acct.Password.ToLower(); ArrayList accounts = new ArrayList(); foreach (Account account in m_Accounts) { if (account.Password.ToLower() == password) { accounts.Add( account ); } } return (Account[])accounts.ToArray(typeof(Account)); } #endregion #region IP Scan public Account[] ScanMultiIP(string account) { account = account.ToLower(); foreach (Account acct in m_Accounts) { if (acct.Name.ToLower() == account) return ScanMultiIP(acct); } return null; } public Account[] ScanMultiIP(Account account) { ArrayList accounts = new ArrayList(); ArrayList ips = new ArrayList(); accounts.Add( account ); ips.Add(account.FirstIP); if (account.FirstIP != account.LastIP) ips.Add(account.LastIP); bool search = true; while (search) { search = false; foreach (Account i in m_Accounts) { if (accounts.Contains( i )) continue; if (i.FirstIP == null || i.FirstIP.Trim() == "") continue; if (ips.Contains(i.FirstIP) || ips.Contains(i.LastIP)) { if (!accounts.Contains( i )) accounts.Add( i ); if (!ips.Contains( i.FirstIP )) ips.Add( i.FirstIP ); if (!ips.Contains( i.LastIP )) ips.Add( i.LastIP ); search = true; } } } return (Account[])accounts.ToArray(typeof(Account)); } #endregion #region Authorised Multis public bool IsAuthorised( string account ) { if (AuthorisedMultis == null) return false; foreach (AuthorisedMulti multi in AuthorisedMultis) { if (multi.ContainsAccount( account )) return true; } return false; } public int GetAuthorisedMultiCode( string account ) { if (AuthorisedMultis == null) return -1; for (int i = 0; i < AuthorisedMultis.Length; i++) { if (AuthorisedMultis[i].ContainsAccount( account )) return i; } return -1; } #endregion #endregion #region Internal Classes internal class AuthorisedMulti { #region Private members protected string[] m_Accounts; #endregion #region Constructor public AuthorisedMulti(string[] accounts) { m_Accounts = new string[ accounts.Length ]; for (int i = 0; i < accounts.Length; i++) m_Accounts[i] = accounts[i].ToLower(); } public AuthorisedMulti(Account[] accounts) { m_Accounts = new string[ accounts.Length ]; for (int i = 0; i < accounts.Length; i++) m_Accounts[i] = accounts[i].Name.ToLower(); } #endregion #region Public properties public string[] Accounts { get { return m_Accounts; } } #endregion #region Public methods public bool ContainsAccount(string account) { account = account.ToLower(); foreach (string acct in m_Accounts) { if (acct == account) return true; } return false; } public string GetAccountString() { if (m_Accounts == null || m_Accounts.Length <= 0) return ""; string ret = ""; foreach (string account in m_Accounts) { ret += string.Format(",{0}", account); } return ret.Remove(0, 1); } public void RemoveAccount(string account) { if (!ContainsAccount(account)) return; ArrayList accounts = new ArrayList( m_Accounts ); accounts.Remove( account ); m_Accounts = (string[])accounts.ToArray(typeof(string)); return; } #endregion } #endregion } } |
From: Iain M. <iai...@us...> - 2005-02-28 01:55:59
|
Update of /cvsroot/bobbot/Plugins/Quakenet In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv13523/Quakenet Added Files: AssemblyInfo.cs QNetConfig.cs QNetPlugin.cs Log Message: New plugin for Quakenet specific functionality. At the moment it only hands Q authentication. Add the following config block to your Bob.exe.config file: <QNetConfig type="Bot.Plugins.Quakenet.QNetConfig, Bot.Plugins.Quakenet"> <AuthEnabled>true</AuthEnabled> <AuthUser>[user]</AuthUser> <AuthPass>[password]</AuthPass> <AuthTarget>Q...@CS...</AuthTarget> </QNetConfig> --- NEW FILE: QNetPlugin.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.Runtime; using System.Configuration; using Bot.Core; using Bot.Core.Irc; using Bot.Core.Irc.Messages; namespace Bot.Plugins.Quakenet { /// <summary> /// Summary description for Class1. /// </summary> public class QNetPlugin : MarshalByRefObject, IPlugin { #region Private members private QNetConfig m_Config; private NetworkConnection m_Network; #endregion #region Constructor public QNetPlugin() { } #endregion #region IPlugin implementation public string Author { get { return "Iain Mckay <jo...@wi...>"; } } public string Name { get { return "Quakenet Stuff"; } } public void Start() { m_Network = Kernel.Instance.Network; m_Config = (QNetConfig) ConfigurationSettings.GetConfig("QNetConfig"); m_Network.Welcome += new WelcomeReplyEventHandler(OnNetworkWelcome); } public void Stop() { } #endregion #region Event handlers private void OnNetworkWelcome(NetworkConnection sender, WelcomeReplyEventArgs args) { if(m_Config.AuthEnabled == false) { return; } m_Network.SendRawMessage("PRIVMSG {0} :auth {1} {2}", m_Config.AuthTarget, m_Config.AuthUser, m_Config.AuthPass); } #endregion } } --- NEW FILE: QNetConfig.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.Net; using System.Xml; using System.Xml.Serialization; namespace Bot.Plugins.Quakenet { /// <summary> /// Summary description for Config. /// </summary> [XmlRoot("QNetConfig")] public class QNetConfig { #region Public members public bool AuthEnabled; public string AuthUser; public string AuthPass; public string AuthTarget; #endregion #region Constructor public QNetConfig() { } #endregion } } --- NEW FILE: AssemblyInfo.cs --- using System.Reflection; using System.Runtime.CompilerServices; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] |