From be20f41637b6c06ce3ab16bc25851b6e43468e12 Mon Sep 17 00:00:00 2001 From: Adam Frisby Date: Wed, 30 Apr 2008 21:43:47 +0000 Subject: * Cruft removal step #1. Cleaning Modules directory. --- .../Environment/Modules/Avatar/Chat/ChatModule.cs | 349 ++-- .../Currency/SampleMoney/SampleMoneyModule.cs | 1847 ++++++++++---------- .../Modules/Avatar/Friends/FriendsModule.cs | 165 +- .../Modules/Avatar/Groups/GroupsModule.cs | 111 +- .../Avatar/InstantMessage/InstantMessageModule.cs | 75 +- .../Modules/Avatar/Inventory/InventoryModule.cs | 104 +- .../Avatar/Profiles/AvatarProfilesModule.cs | 6 +- .../Voice/AsterixVoice/AsteriskVoiceModule.cs | 81 +- .../Avatar/Voice/SIPVoice/SIPVoiceModule.cs | 47 +- 9 files changed, 1405 insertions(+), 1380 deletions(-) (limited to 'OpenSim/Region/Environment/Modules/Avatar') diff --git a/OpenSim/Region/Environment/Modules/Avatar/Chat/ChatModule.cs b/OpenSim/Region/Environment/Modules/Avatar/Chat/ChatModule.cs index 1281873..966f5f3 100644 --- a/OpenSim/Region/Environment/Modules/Avatar/Chat/ChatModule.cs +++ b/OpenSim/Region/Environment/Modules/Avatar/Chat/ChatModule.cs @@ -44,21 +44,21 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat public class ChatModule : IRegionModule, ISimChat { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private List m_scenes = new List(); - - private int m_whisperdistance = 10; - private int m_saydistance = 30; - private int m_shoutdistance = 100; + private string m_defaultzone = null; private IRCChatModule m_irc = null; + private Thread m_irc_connector = null; - private string m_last_new_user = null; private string m_last_leaving_user = null; - private string m_defaultzone = null; + private string m_last_new_user = null; + private int m_saydistance = 30; + private List m_scenes = new List(); + private int m_shoutdistance = 100; internal object m_syncInit = new object(); internal object m_syncLogout = new object(); - private Thread m_irc_connector=null; + private int m_whisperdistance = 10; + + #region IRegionModule Members public void Initialise(Scene scene, IConfigSource config) { @@ -85,14 +85,17 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat try { - m_defaultzone = config.Configs["IRC"].GetString("nick","Sim"); + m_defaultzone = config.Configs["IRC"].GetString("nick", "Sim"); } catch (Exception) { } // setup IRC Relay - if (m_irc == null) { m_irc = new IRCChatModule(config); } + if (m_irc == null) + { + m_irc = new IRCChatModule(config); + } if (m_irc_connector == null) { m_irc_connector = new Thread(IRCConnectRun); @@ -142,83 +145,9 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat get { return true; } } - public void NewClient(IClientAPI client) - { - try - { - client.OnChatFromViewer += SimChat; + #endregion - if ((m_irc.Enabled) && (m_irc.Connected)) - { - string clientName = client.FirstName + " " + client.LastName; - // handles simple case. May not work for hundred connecting in per second. - // and the NewClients calles getting interleved - // but filters out multiple reports - if (clientName != m_last_new_user) - { - m_last_new_user = clientName; - string clientRegion = FindClientRegion(client.FirstName, client.LastName); - m_irc.PrivMsg(m_irc.Nick, "Sim", "notices " + clientName + " in "+clientRegion); - } - } - client.OnLogout += ClientLoggedOut; - client.OnConnectionClosed += ClientLoggedOut; - client.OnLogout += ClientLoggedOut; - } - catch (Exception ex) - { - m_log.Error("[IRC]: NewClient exception trap:" + ex.ToString()); - } - } - - public void ClientLoggedOut(IClientAPI client) - { - lock (m_syncLogout) - { - try - { - if ((m_irc.Enabled) && (m_irc.Connected)) - { - string clientName = client.FirstName + " " + client.LastName; - string clientRegion = FindClientRegion(client.FirstName, client.LastName); - // handles simple case. May not work for hundred connecting in per second. - // and the NewClients calles getting interleved - // but filters out multiple reports - if (clientName != m_last_leaving_user) - { - m_last_leaving_user = clientName; - m_irc.PrivMsg(m_irc.Nick, "Sim", "notices " + clientName + " left " + clientRegion); - m_log.Info("[IRC]: IRC watcher notices " + clientName + " left " + clientRegion); - } - } - } - catch (Exception ex) - { - m_log.Error("[IRC]: ClientLoggedOut exception trap:" + ex.ToString()); - } - } - } - - private void TrySendChatMessage(ScenePresence presence, LLVector3 fromPos, LLVector3 regionPos, - LLUUID fromAgentID, string fromName, ChatTypeEnum type, string message) - { - if (!presence.IsChildAgent) - { - LLVector3 fromRegionPos = fromPos + regionPos; - LLVector3 toRegionPos = presence.AbsolutePosition + regionPos; - int dis = Math.Abs((int) Util.GetDistanceTo(toRegionPos, fromRegionPos)); - - if (type == ChatTypeEnum.Whisper && dis > m_whisperdistance || - type == ChatTypeEnum.Say && dis > m_saydistance || - type == ChatTypeEnum.Shout && dis > m_shoutdistance) - { - return; - } - - // TODO: should change so the message is sent through the avatar rather than direct to the ClientView - presence.ControllingClient.SendChatMessage(message, (byte) type, fromPos, fromName, fromAgentID); - } - } + #region ISimChat Members public void SimChat(Object sender, ChatFromViewerArgs e) { @@ -289,7 +218,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat m_irc.PrivMsg(fromName, scene.RegionInfo.RegionName, e.Message); } } - + foreach (Scene s in m_scenes) { s.ForEachScenePresence(delegate(ScenePresence presence) @@ -301,12 +230,92 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat } } + #endregion + + public void NewClient(IClientAPI client) + { + try + { + client.OnChatFromViewer += SimChat; + + if ((m_irc.Enabled) && (m_irc.Connected)) + { + string clientName = client.FirstName + " " + client.LastName; + // handles simple case. May not work for hundred connecting in per second. + // and the NewClients calles getting interleved + // but filters out multiple reports + if (clientName != m_last_new_user) + { + m_last_new_user = clientName; + string clientRegion = FindClientRegion(client.FirstName, client.LastName); + m_irc.PrivMsg(m_irc.Nick, "Sim", "notices " + clientName + " in " + clientRegion); + } + } + client.OnLogout += ClientLoggedOut; + client.OnConnectionClosed += ClientLoggedOut; + client.OnLogout += ClientLoggedOut; + } + catch (Exception ex) + { + m_log.Error("[IRC]: NewClient exception trap:" + ex.ToString()); + } + } + + public void ClientLoggedOut(IClientAPI client) + { + lock (m_syncLogout) + { + try + { + if ((m_irc.Enabled) && (m_irc.Connected)) + { + string clientName = client.FirstName + " " + client.LastName; + string clientRegion = FindClientRegion(client.FirstName, client.LastName); + // handles simple case. May not work for hundred connecting in per second. + // and the NewClients calles getting interleved + // but filters out multiple reports + if (clientName != m_last_leaving_user) + { + m_last_leaving_user = clientName; + m_irc.PrivMsg(m_irc.Nick, "Sim", "notices " + clientName + " left " + clientRegion); + m_log.Info("[IRC]: IRC watcher notices " + clientName + " left " + clientRegion); + } + } + } + catch (Exception ex) + { + m_log.Error("[IRC]: ClientLoggedOut exception trap:" + ex.ToString()); + } + } + } + + private void TrySendChatMessage(ScenePresence presence, LLVector3 fromPos, LLVector3 regionPos, + LLUUID fromAgentID, string fromName, ChatTypeEnum type, string message) + { + if (!presence.IsChildAgent) + { + LLVector3 fromRegionPos = fromPos + regionPos; + LLVector3 toRegionPos = presence.AbsolutePosition + regionPos; + int dis = Math.Abs((int) Util.GetDistanceTo(toRegionPos, fromRegionPos)); + + if (type == ChatTypeEnum.Whisper && dis > m_whisperdistance || + type == ChatTypeEnum.Say && dis > m_saydistance || + type == ChatTypeEnum.Shout && dis > m_shoutdistance) + { + return; + } + + // TODO: should change so the message is sent through the avatar rather than direct to the ClientView + presence.ControllingClient.SendChatMessage(message, (byte) type, fromPos, fromName, fromAgentID); + } + } + // if IRC is enabled then just keep trying using a monitor thread public void IRCConnectRun() { - while(true) + while (true) { - if ((m_irc.Enabled)&&(!m_irc.Connected)) + if ((m_irc.Enabled) && (!m_irc.Connected)) { m_irc.Connect(m_scenes); } @@ -314,54 +323,76 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat } } - public string FindClientRegion(string client_FirstName,string client_LastName) + public string FindClientRegion(string client_FirstName, string client_LastName) { string sourceRegion = null; foreach (Scene s in m_scenes) { s.ForEachScenePresence(delegate(ScenePresence presence) { - if ((presence.IsChildAgent==false) - &&(presence.Firstname==client_FirstName) - &&(presence.Lastname==client_LastName)) + if ((presence.IsChildAgent == false) + && (presence.Firstname == client_FirstName) + && (presence.Lastname == client_LastName)) { sourceRegion = presence.Scene.RegionInfo.RegionName; //sourceRegion= s.RegionInfo.RegionName; } }); - if (sourceRegion != null) return sourceRegion; + if (sourceRegion != null) return sourceRegion; + } + if (m_defaultzone == null) + { + m_defaultzone = "Sim"; } - if (m_defaultzone == null) { m_defaultzone = "Sim"; } return m_defaultzone; } } internal class IRCChatModule { + #region ErrorReplies enum + + public enum ErrorReplies + { + NotRegistered = 451, // ":You have not registered" + NicknameInUse = 433 // " :Nickname is already in use" + } + + #endregion + + #region Replies enum + + public enum Replies + { + MotdStart = 375, // ":- Message of the day - " + Motd = 372, // ":- " + EndOfMotd = 376 // ":End of /MOTD command" + } + + #endregion + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + private Thread listener; - private string m_server = null; - private uint m_port = 6668; - private string m_user = "USER OpenSimBot 8 * :I'm a OpenSim to irc bot"; - private string m_nick = null; private string m_basenick = null; private string m_channel = null; + private bool m_connected = false; + private bool m_enabled = false; + private List m_last_scenes = null; + private string m_nick = null; + private uint m_port = 6668; private string m_privmsgformat = "PRIVMSG {0} :<{1} in {2}>: {3}"; + private StreamReader m_reader; + private List m_scenes = null; + private string m_server = null; private NetworkStream m_stream; + internal object m_syncConnect = new object(); private TcpClient m_tcp; + private string m_user = "USER OpenSimBot 8 * :I'm a OpenSim to irc bot"; private StreamWriter m_writer; - private StreamReader m_reader; private Thread pingSender; - private Thread listener; - internal object m_syncConnect = new object(); - - private bool m_enabled = false; - private bool m_connected = false; - - private List m_scenes = null; - private List m_last_scenes = null; public IRCChatModule(IConfigSource config) { @@ -412,6 +443,21 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat } } + public bool Enabled + { + get { return m_enabled; } + } + + public bool Connected + { + get { return m_connected; } + } + + public string Nick + { + get { return m_nick; } + } + public bool Connect(List scenes) { lock (m_syncConnect) @@ -420,9 +466,12 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat { if (m_connected) return true; m_scenes = scenes; - if (m_last_scenes == null) { m_last_scenes = scenes; } + if (m_last_scenes == null) + { + m_last_scenes = scenes; + } - m_tcp = new TcpClient(m_server, (int)m_port); + m_tcp = new TcpClient(m_server, (int) m_port); m_log.Info("[IRC]: Connecting..."); m_stream = m_tcp.GetStream(); m_log.Info("[IRC]: Connected to " + m_server); @@ -458,21 +507,6 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat } } - public bool Enabled - { - get { return m_enabled; } - } - - public bool Connected - { - get { return m_connected; } - } - - public string Nick - { - get { return m_nick; } - } - public void Reconnect() { m_connected = false; @@ -481,7 +515,10 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat m_writer.Close(); m_reader.Close(); m_tcp.Close(); - if (m_enabled) { Connect(m_last_scenes); } + if (m_enabled) + { + Connect(m_last_scenes); + } } public void PrivMsg(string from, string region, string msg) @@ -627,7 +664,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat } } - public void BroadcastSim(string message,string sender) + public void BroadcastSim(string message, string sender) { LLVector3 pos = new LLVector3(128, 128, 20); try @@ -652,23 +689,10 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat } } - public enum ErrorReplies - { - NotRegistered = 451, // ":You have not registered" - NicknameInUse = 433 // " :Nickname is already in use" - } - - public enum Replies - { - MotdStart = 375, // ":- Message of the day - " - Motd = 372, // ":- " - EndOfMotd = 376 // ":End of /MOTD command" - } - public void ProcessIRCCommand(string command) { //m_log.Info("[IRC]: ProcessIRCCommand:" + command); - + string[] commArgs = new string[command.Split(' ').Length]; string c_server = m_server; @@ -690,7 +714,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat if (commArgs[0] == "ERROR") { - m_log.Error("[IRC]: IRC SERVER ERROR:" + command); + m_log.Error("[IRC]: IRC SERVER ERROR:" + command); } if (commArgs[0] == "PING") @@ -713,7 +737,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat Int32 commandCode = Int32.Parse(commArgs[1]); switch (commandCode) { - case (int)ErrorReplies.NicknameInUse: + case (int) ErrorReplies.NicknameInUse: // Gen a new name m_nick = m_basenick + Util.RandomClass.Next(1, 99); m_log.Error("[IRC]: IRC SERVER reports NicknameInUse, trying " + m_nick); @@ -723,9 +747,9 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat m_writer.WriteLine("JOIN " + m_channel); m_writer.Flush(); break; - case (int)ErrorReplies.NotRegistered: + case (int) ErrorReplies.NotRegistered: break; - case (int)Replies.EndOfMotd: + case (int) Replies.EndOfMotd: break; } } @@ -733,19 +757,32 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat { } } - else - { + else + { // Normal message string commAct = commArgs[1]; switch (commAct) { - case "JOIN": eventIrcJoin(commArgs); break; - case "PART": eventIrcPart(commArgs); break; - case "MODE": eventIrcMode(commArgs); break; - case "NICK": eventIrcNickChange(commArgs); break; - case "KICK": eventIrcKick(commArgs); break; - case "QUIT": eventIrcQuit(commArgs); break; - case "PONG": break; // that's nice + case "JOIN": + eventIrcJoin(commArgs); + break; + case "PART": + eventIrcPart(commArgs); + break; + case "MODE": + eventIrcMode(commArgs); + break; + case "NICK": + eventIrcNickChange(commArgs); + break; + case "KICK": + eventIrcKick(commArgs); + break; + case "QUIT": + eventIrcQuit(commArgs); + break; + case "PONG": + break; // that's nice } } } @@ -797,7 +834,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat { KickMessage += commArgs[i] + " "; } - BroadcastSim(UserKicker + " kicked " + UserKicked +" on "+IrcChannel+" saying "+KickMessage, m_nick); + BroadcastSim(UserKicker + " kicked " + UserKicked + " on " + IrcChannel + " saying " + KickMessage, m_nick); if (UserKicked == m_nick) { BroadcastSim("Hey, that was me!!!", m_nick); diff --git a/OpenSim/Region/Environment/Modules/Avatar/Currency/SampleMoney/SampleMoneyModule.cs b/OpenSim/Region/Environment/Modules/Avatar/Currency/SampleMoney/SampleMoneyModule.cs index 0e058ec..181984e 100644 --- a/OpenSim/Region/Environment/Modules/Avatar/Currency/SampleMoney/SampleMoneyModule.cs +++ b/OpenSim/Region/Environment/Modules/Avatar/Currency/SampleMoney/SampleMoneyModule.cs @@ -53,7 +53,6 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Currency.SampleMoney /// Centralized grid structure example using OpenSimWi Redux revision 9+ /// svn co https://opensimwiredux.svn.sourceforge.net/svnroot/opensimwiredux /// - public delegate void ObjectPaid(LLUUID objectID, LLUUID agentID, int amount); public interface IMoneyModule : IRegionModule @@ -65,37 +64,39 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Currency.SampleMoney public class SampleMoneyModule : IMoneyModule { - public event ObjectPaid OnObjectPaid; - - private ObjectPaid handerOnObjectPaid; - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - /// - /// Region UUIDS indexed by AgentID - /// - Dictionary m_rootAgents = new Dictionary(); - + /// - /// Scenes by Region Handle + /// Where Stipends come from and Fees go to. /// - private Dictionary m_scenel = new Dictionary(); + private LLUUID EconomyBaseAccount = LLUUID.Zero; + + private float EnergyEfficiency = 0f; + private bool gridmode = false; + private ObjectPaid handerOnObjectPaid; + private bool m_enabled = true; private IConfigSource m_gConfig; private bool m_keepMoneyAcrossLogins = true; + private Dictionary m_KnownClientFunds = new Dictionary(); + private string m_LandAddress = String.Empty; private int m_minFundsBeforeRefresh = 100; + private string m_MoneyAddress = String.Empty; - private int m_stipend = 1000; + /// + /// Region UUIDS indexed by AgentID + /// + private Dictionary m_rootAgents = new Dictionary(); - private bool m_enabled = true; + /// + /// Scenes by Region Handle + /// + private Dictionary m_scenel = new Dictionary(); - private Dictionary m_KnownClientFunds = new Dictionary(); + private int m_stipend = 1000; - private bool gridmode = false; - private Scene XMLRPCHandler; - private float EnergyEfficiency = 0f; private int ObjectCapacity = 45000; private int ObjectCount = 0; private int PriceEnergyUnit = 0; @@ -111,16 +112,14 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Currency.SampleMoney private int PriceRentLight = 0; private int PriceUpload = 0; private int TeleportMinPrice = 0; + + private float TeleportPriceExponent = 0f; private int UserLevelPaysFees = 2; - private string m_MoneyAddress = String.Empty; - private string m_LandAddress = String.Empty; + private Scene XMLRPCHandler; - float TeleportPriceExponent = 0f; + #region IMoneyModule Members - /// - /// Where Stipends come from and Fees go to. - /// - LLUUID EconomyBaseAccount = LLUUID.Zero; + public event ObjectPaid OnObjectPaid; /// /// Startup @@ -130,12 +129,12 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Currency.SampleMoney public void Initialise(Scene scene, IConfigSource config) { m_gConfig = config; - + IConfig startupConfig = m_gConfig.Configs["Startup"]; IConfig economyConfig = m_gConfig.Configs["Economy"]; - + scene.RegisterModuleInterface(this); - + ReadConfigAndPopulate(scene, startupConfig, "Startup"); ReadConfigAndPopulate(scene, economyConfig, "Economy"); @@ -167,8 +166,6 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Currency.SampleMoney scene.AddXmlRPCHandler("preflightBuyLandPrep", preflightBuyLandPrep_func); scene.AddXmlRPCHandler("buyLandPrep", landBuy_func); } - - } if (m_scenel.ContainsKey(scene.RegionInfo.RegionHandle)) @@ -180,7 +177,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Currency.SampleMoney m_scenel.Add(scene.RegionInfo.RegionHandle, scene); } } - + scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnMoneyTransfer += MoneyTransferAction; scene.EventManager.OnClientClosed += ClientClosed; @@ -189,9 +186,41 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Currency.SampleMoney scene.EventManager.OnClientClosed += ClientLoggedOut; scene.EventManager.OnValidateLandBuy += ValidateLandBuy; scene.EventManager.OnLandBuy += processLandBuy; - } } + + public bool ObjectGiveMoney(LLUUID objectID, LLUUID fromID, LLUUID toID, int amount) + { + string description = String.Format("Object {0} pays {1}", resolveObjectName(objectID), resolveAgentName(toID)); + + bool give_result = doMoneyTransfer(fromID, toID, amount, 2, description); + + if (m_MoneyAddress.Length == 0) + BalanceUpdate(fromID, toID, give_result, description); + + return give_result; + } + + public void PostInitialise() + { + } + + public void Close() + { + } + + public string Name + { + get { return "BetaGridLikeMoneyModule"; } + } + + public bool IsSharedModule + { + get { return true; } + } + + #endregion + /// /// Parse Configuration /// @@ -207,7 +236,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Currency.SampleMoney } if (config == "Economy" && startupConfig != null) - { + { ObjectCapacity = startupConfig.GetInt("ObjectCapacity", 45000); PriceEnergyUnit = startupConfig.GetInt("PriceEnergyUnit", 100); PriceObjectClaim = startupConfig.GetInt("PriceObjectClaim", 10); @@ -225,7 +254,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Currency.SampleMoney PriceParcelRent = startupConfig.GetInt("PriceParcelRent", 1); PriceGroupCreate = startupConfig.GetInt("PriceGroupCreate", -1); string EBA = startupConfig.GetString("EconomyBaseAccount", LLUUID.Zero.ToString()); - Helpers.TryParse(EBA,out EconomyBaseAccount); + Helpers.TryParse(EBA, out EconomyBaseAccount); UserLevelPaysFees = startupConfig.GetInt("UserLevelPaysFees", -1); m_stipend = startupConfig.GetInt("UserStipend", 500); @@ -234,7 +263,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Currency.SampleMoney m_MoneyAddress = startupConfig.GetString("CurrencyServer", String.Empty); m_LandAddress = startupConfig.GetString("LandServer", String.Empty); } - + // Send ObjectCapacity to Scene.. Which sends it to the SimStatsReporter. scene.SetObjectCapacity(ObjectCapacity); } @@ -253,7 +282,6 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Currency.SampleMoney { if (m_MoneyAddress.Length == 0) { - CheckExistAndRefreshFunds(client.AgentId); } else @@ -273,15 +301,16 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Currency.SampleMoney //s.RegionInfo.RegionHandle; LLUUID agentID = LLUUID.Zero; int funds = 0; - - Hashtable hbinfo = GetBalanceForUserFromMoneyServer(client.AgentId, client.SecureSessionId, s.RegionInfo.originRegionID.ToString(), s.RegionInfo.regionSecret); - if ((bool)hbinfo["success"] == true) - { - Helpers.TryParse((string)hbinfo["agentId"], out agentID); + Hashtable hbinfo = + GetBalanceForUserFromMoneyServer(client.AgentId, client.SecureSessionId, s.RegionInfo.originRegionID.ToString(), + s.RegionInfo.regionSecret); + if ((bool) hbinfo["success"] == true) + { + Helpers.TryParse((string) hbinfo["agentId"], out agentID); try { - funds = (Int32)hbinfo["funds"]; + funds = (Int32) hbinfo["funds"]; } catch (ArgumentException) { @@ -303,1189 +332,1139 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Currency.SampleMoney } else { - m_log.WarnFormat("[MONEY]: Getting Money for user {0} failed with the following message:{1}", agentID, (string)hbinfo["errorMessage"]); - client.SendAlertMessage((string)hbinfo["errorMessage"]); + m_log.WarnFormat("[MONEY]: Getting Money for user {0} failed with the following message:{1}", agentID, + (string) hbinfo["errorMessage"]); + client.SendAlertMessage((string) hbinfo["errorMessage"]); } SendMoneyBalance(client, agentID, client.SessionId, LLUUID.Zero); - } } - } else { CheckExistAndRefreshFunds(client.AgentId); } - + // Subscribe to Money messages client.OnEconomyDataRequest += EconomyDataRequestHandler; client.OnMoneyBalanceRequest += SendMoneyBalance; client.OnRequestPayPrice += requestPayPrice; client.OnLogout += ClientClosed; - - - } - - #region event Handlers - - public void requestPayPrice(IClientAPI client, LLUUID objectID) - { - Scene scene=LocateSceneClientIn(client.AgentId); - if(scene == null) - return; - - SceneObjectPart task=scene.GetSceneObjectPart(objectID); - if(task == null) - return; - SceneObjectGroup group=task.ParentGroup; - SceneObjectPart root=group.RootPart; - - client.SendPayPrice(objectID, root.PayPrice); - } - - /// - /// When the client closes the connection we remove their accounting info from memory to free up resources. - /// - /// - public void ClientClosed(LLUUID AgentID) - { - lock (m_KnownClientFunds) - { - if (m_keepMoneyAcrossLogins && m_MoneyAddress.Length == 0) - { - } - else - { - m_KnownClientFunds.Remove(AgentID); - } - } } /// - /// Event called Economy Data Request handler. + /// Transfer money /// - /// - public void EconomyDataRequestHandler(LLUUID agentId) - { - IClientAPI user = LocateClientObject(agentId); - - if (user != null) - { - user.SendEconomyData(EnergyEfficiency, ObjectCapacity, ObjectCount, PriceEnergyUnit, PriceGroupCreate, - PriceObjectClaim, PriceObjectRent, PriceObjectScaleFactor, PriceParcelClaim, PriceParcelClaimFactor, - PriceParcelRent, PricePublicObjectDecay, PricePublicObjectDelete, PriceRentLight, PriceUpload, - TeleportMinPrice, TeleportPriceExponent); - } - } - - private void ValidateLandBuy (Object osender, EventManager.LandBuyArgs e) + /// + /// + /// + /// + private bool doMoneyTransfer(LLUUID Sender, LLUUID Receiver, int amount, int transactiontype, string description) { - if (m_MoneyAddress.Length == 0) + bool result = false; + if (amount >= 0) { lock (m_KnownClientFunds) { - if (m_KnownClientFunds.ContainsKey(e.agentId)) + // If we don't know about the sender, then the sender can't + // actually be here and therefore this is likely fraud or outdated. + if (m_MoneyAddress.Length == 0) { - // Does the sender have enough funds to give? - if (m_KnownClientFunds[e.agentId] >= e.parcelPrice) + if (m_KnownClientFunds.ContainsKey(Sender)) { - lock(e) + // Does the sender have enough funds to give? + if (m_KnownClientFunds[Sender] >= amount) + { + // Subtract the funds from the senders account + m_KnownClientFunds[Sender] -= amount; + + // do we know about the receiver? + if (!m_KnownClientFunds.ContainsKey(Receiver)) + { + // Make a record for them so they get the updated balance when they login + CheckExistAndRefreshFunds(Receiver); + } + if (m_enabled) + { + //Add the amount to the Receiver's funds + m_KnownClientFunds[Receiver] += amount; + result = true; + } + } + else { - e.economyValidated=true; + // These below are redundant to make this clearer to read + result = false; } } + else + { + result = false; + } } - } - } - else - { - if(GetRemoteBalance(e.agentId) >= e.parcelPrice) - { - lock(e) + else { - e.economyValidated=true; + result = TransferMoneyonMoneyServer(Sender, Receiver, amount, transactiontype, description); } } } + return result; } - private void processLandBuy(Object osender, EventManager.LandBuyArgs e) + + /// + /// Sends the the stored money balance to the client + /// + /// + /// + /// + /// + public void SendMoneyBalance(IClientAPI client, LLUUID agentID, LLUUID SessionID, LLUUID TransactionID) { - lock(e) + if (client.AgentId == agentID && client.SessionId == SessionID) { - if(e.economyValidated == true && e.transactionID == 0) - { - e.transactionID=Util.UnixTimeSinceEpoch(); + int returnfunds = 0; - if(doMoneyTransfer(e.agentId, e.parcelOwnerID, e.parcelPrice, 0, "Land purchase")) - { - lock (e) - { - e.amountDebited = e.parcelPrice; - } - } + try + { + returnfunds = GetFundsForAgentID(agentID); + } + catch (Exception e) + { + client.SendAlertMessage(e.Message + " "); } + + client.SendMoneyBalance(TransactionID, true, new byte[0], returnfunds); + } + else + { + client.SendAlertMessage("Unable to send your money balance to you!"); } } /// - /// THis method gets called when someone pays someone else as a gift. + /// Gets the current balance for the user from the Grid Money Server /// - /// - /// - private void MoneyTransferAction (Object osender, EventManager.MoneyTransferArgs e) + /// + /// + /// + /// + /// + public Hashtable GetBalanceForUserFromMoneyServer(LLUUID agentId, LLUUID secureSessionID, LLUUID regionId, string regionSecret) { - IClientAPI sender = null; - IClientAPI receiver = null; - - if(m_MoneyAddress.Length > 0) // Handled on server - e.description=String.Empty; - - if(e.transactiontype == 5008) // Object gets paid - { - sender = LocateClientObject(e.sender); - if (sender != null) - { - SceneObjectPart part=findPrim(e.receiver); - if(part == null) - return; - - string name=resolveAgentName(part.OwnerID); - if(name == String.Empty) - name="(hippos)"; + Hashtable MoneyBalanceRequestParams = new Hashtable(); + MoneyBalanceRequestParams["agentId"] = agentId.ToString(); + MoneyBalanceRequestParams["secureSessionId"] = secureSessionID.ToString(); + MoneyBalanceRequestParams["regionId"] = regionId.ToString(); + MoneyBalanceRequestParams["secret"] = regionSecret; + MoneyBalanceRequestParams["currencySecret"] = ""; // per - region/user currency secret gotten from the money system - receiver = LocateClientObject(part.OwnerID); + Hashtable MoneyRespData = genericCurrencyXMLRPCRequest(MoneyBalanceRequestParams, "simulatorUserBalanceRequest"); - string description=String.Format("Paid {0} via object {1}", name, e.description); - bool transactionresult = doMoneyTransfer(e.sender, part.OwnerID, e.amount, e.transactiontype, description); + return MoneyRespData; + } - if(transactionresult) - { - ObjectPaid handlerOnObjectPaid = OnObjectPaid; - if(handlerOnObjectPaid != null) - { - handlerOnObjectPaid(e.receiver, e.sender, e.amount); - } - } - if (e.sender != e.receiver) - { - sender.SendMoneyBalance(LLUUID.Random(), transactionresult, Helpers.StringToField(e.description), GetFundsForAgentID(e.sender)); - } - if(receiver != null) - { - receiver.SendMoneyBalance(LLUUID.Random(), transactionresult, Helpers.StringToField(e.description), GetFundsForAgentID(part.OwnerID)); - } - } - return; + /// + /// Generic XMLRPC client abstraction + /// + /// Hashtable containing parameters to the method + /// Method to invoke + /// Hashtable with success=>bool and other values + public Hashtable genericCurrencyXMLRPCRequest(Hashtable ReqParams, string method) + { + ArrayList SendParams = new ArrayList(); + SendParams.Add(ReqParams); + // Send Request + XmlRpcResponse MoneyResp; + try + { + XmlRpcRequest BalanceRequestReq = new XmlRpcRequest(method, SendParams); + MoneyResp = BalanceRequestReq.Send(m_MoneyAddress, 30000); } + catch (WebException ex) + { + m_log.ErrorFormat( + "[MONEY]: Unable to connect to Money Server {0}. Exception {1}", + m_MoneyAddress, ex); - sender = LocateClientObject(e.sender); - if (sender != null) + Hashtable ErrorHash = new Hashtable(); + ErrorHash["success"] = false; + ErrorHash["errorMessage"] = "Unable to manage your money at this time. Purchases may be unavailable"; + ErrorHash["errorURI"] = ""; + + return ErrorHash; + //throw (ex); + } + catch (SocketException ex) { - receiver = LocateClientObject(e.receiver); + m_log.ErrorFormat( + "[MONEY]: Unable to connect to Money Server {0}. Exception {1}", + m_MoneyAddress, ex); - bool transactionresult = doMoneyTransfer(e.sender, e.receiver, e.amount, e.transactiontype, e.description); + Hashtable ErrorHash = new Hashtable(); + ErrorHash["success"] = false; + ErrorHash["errorMessage"] = "Unable to manage your money at this time. Purchases may be unavailable"; + ErrorHash["errorURI"] = ""; - if (e.sender != e.receiver) - { - if (sender != null) - { - sender.SendMoneyBalance(LLUUID.Random(), transactionresult, Helpers.StringToField(e.description), GetFundsForAgentID(e.sender)); - } - } + return ErrorHash; + //throw (ex); + } + catch (XmlException ex) + { + m_log.ErrorFormat( + "[MONEY]: Unable to connect to Money Server {0}. Exception {1}", + m_MoneyAddress, ex); - if (receiver != null) - { - receiver.SendMoneyBalance(LLUUID.Random(), transactionresult, Helpers.StringToField(e.description), GetFundsForAgentID(e.receiver)); - } + Hashtable ErrorHash = new Hashtable(); + ErrorHash["success"] = false; + ErrorHash["errorMessage"] = "Unable to manage your money at this time. Purchases may be unavailable"; + ErrorHash["errorURI"] = ""; + + return ErrorHash; } - else + if (MoneyResp.IsFault) { - m_log.Warn("[MONEY]: Potential Fraud Warning, got money transfer request for avatar that isn't in this simulator - Details; Sender:" + e.sender.ToString() + " Receiver: " + e.receiver.ToString() + " Amount: " + e.amount.ToString()); + Hashtable ErrorHash = new Hashtable(); + ErrorHash["success"] = false; + ErrorHash["errorMessage"] = "Unable to manage your money at this time. Purchases may be unavailable"; + ErrorHash["errorURI"] = ""; + + return ErrorHash; } + Hashtable MoneyRespData = (Hashtable) MoneyResp.Value; + + return MoneyRespData; } /// - /// Event Handler for when a root agent becomes a child agent + /// This informs the Money Grid Server that the avatar is in this simulator /// - /// - private void MakeChildAgent(ScenePresence avatar) + /// + /// + /// + /// + /// + public Hashtable claim_user(LLUUID agentId, LLUUID secureSessionID, LLUUID regionId, string regionSecret) { - lock (m_rootAgents) + Hashtable MoneyBalanceRequestParams = new Hashtable(); + MoneyBalanceRequestParams["agentId"] = agentId.ToString(); + MoneyBalanceRequestParams["secureSessionId"] = secureSessionID.ToString(); + MoneyBalanceRequestParams["regionId"] = regionId.ToString(); + MoneyBalanceRequestParams["secret"] = regionSecret; + + Hashtable MoneyRespData = genericCurrencyXMLRPCRequest(MoneyBalanceRequestParams, "simulatorClaimUserRequest"); + IClientAPI sendMoneyBal = LocateClientObject(agentId); + if (sendMoneyBal != null) { - if (m_rootAgents.ContainsKey(avatar.UUID)) + SendMoneyBalance(sendMoneyBal, agentId, sendMoneyBal.SessionId, LLUUID.Zero); + } + return MoneyRespData; + } + + private SceneObjectPart findPrim(LLUUID objectID) + { + lock (m_scenel) + { + foreach (Scene s in m_scenel.Values) { - if (m_rootAgents[avatar.UUID] == avatar.Scene.RegionInfo.originRegionID) + SceneObjectPart part = s.GetSceneObjectPart(objectID); + if (part != null) { - m_rootAgents.Remove(avatar.UUID); - m_log.Info("[MONEY]: Removing " + avatar.Firstname + " " + avatar.Lastname + " as a root agent"); + return part; } - } } - + return null; } - /// - /// Event Handler for when the client logs out. - /// - /// - private void ClientLoggedOut(LLUUID AgentId) + private string resolveObjectName(LLUUID objectID) { - lock (m_rootAgents) + SceneObjectPart part = findPrim(objectID); + if (part != null) { - if (m_rootAgents.ContainsKey(AgentId)) - { - m_rootAgents.Remove(AgentId); - //m_log.Info("[MONEY]: Removing " + AgentId + ". Agent logged out."); - } + return part.Name; } + return String.Empty; } - /// - /// Call this when the client disconnects. - /// - /// - public void ClientClosed(IClientAPI client) + private string resolveAgentName(LLUUID agentID) { - ClientClosed(client.AgentId); + // try avatar username surname + Scene scene = GetRandomScene(); + UserProfileData profile = scene.CommsManager.UserService.GetUserProfile(agentID); + if (profile != null) + { + string avatarname = profile.FirstName + " " + profile.SurName; + return avatarname; + } + return String.Empty; } - /// - /// Event Handler for when an Avatar enters one of the parcels in the simulator. - /// - /// - /// - /// - private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, LLUUID regionID) + private void BalanceUpdate(LLUUID senderID, LLUUID receiverID, bool transactionresult, string description) { - lock (m_rootAgents) + IClientAPI sender = LocateClientObject(senderID); + IClientAPI receiver = LocateClientObject(receiverID); + + if (senderID != receiverID) { - if (m_rootAgents.ContainsKey(avatar.UUID)) + if (sender != null) { - if (avatar.Scene.RegionInfo.originRegionID != m_rootAgents[avatar.UUID]) - { - m_rootAgents[avatar.UUID] = avatar.Scene.RegionInfo.originRegionID; - //m_log.Info("[MONEY]: Claiming " + avatar.Firstname + " " + avatar.Lastname + " in region:" + avatar.RegionHandle + "."); - // Claim User! my user! Mine mine mine! - if (m_MoneyAddress.Length > 0) - { - Scene RegionItem = GetSceneByUUID(regionID); - if (RegionItem != null) - { - Hashtable hresult = claim_user(avatar.UUID, avatar.ControllingClient.SecureSessionId, regionID, RegionItem.RegionInfo.regionSecret); - if ((bool)hresult["success"] == true) - { - int funds = 0; - try - { - funds = (Int32)hresult["funds"]; - } - catch (InvalidCastException) - { - - } - SetLocalFundsForAgentID(avatar.UUID, funds); - } - else - { - avatar.ControllingClient.SendAgentAlertMessage((string)hresult["errorMessage"], true); - } - } - } - } + sender.SendMoneyBalance(LLUUID.Random(), transactionresult, Helpers.StringToField(description), GetFundsForAgentID(senderID)); } - else - { - lock (m_rootAgents) - { - m_rootAgents.Add(avatar.UUID, avatar.Scene.RegionInfo.originRegionID); - } - if (m_MoneyAddress.Length > 0) - { - Scene RegionItem = GetSceneByUUID(regionID); - if (RegionItem != null) - { - Hashtable hresult = claim_user(avatar.UUID, avatar.ControllingClient.SecureSessionId, regionID, RegionItem.RegionInfo.regionSecret); - if ((bool)hresult["success"] == true) - { - int funds = 0; - try - { - funds = (Int32)hresult["funds"]; - } - catch (InvalidCastException) - { - } - SetLocalFundsForAgentID(avatar.UUID, funds); - } - else - { - avatar.ControllingClient.SendAgentAlertMessage((string)hresult["errorMessage"], true); - } - } - } - - //m_log.Info("[MONEY]: Claiming " + avatar.Firstname + " " + avatar.Lastname + " in region:" + avatar.RegionHandle + "."); + if (receiver != null) + { + receiver.SendMoneyBalance(LLUUID.Random(), transactionresult, Helpers.StringToField(description), GetFundsForAgentID(receiverID)); } } - //m_log.Info("[FRIEND]: " + avatar.Name + " status:" + (!avatar.IsChildAgent).ToString()); } - #endregion - /// - /// Transfer money + /// Informs the Money Grid Server of a transfer. /// - /// - /// + /// + /// /// /// - private bool doMoneyTransfer(LLUUID Sender, LLUUID Receiver, int amount, int transactiontype, string description) + public bool TransferMoneyonMoneyServer(LLUUID sourceId, LLUUID destId, int amount, int transactiontype, string description) { - bool result = false; - if (amount >= 0) + int aggregatePermInventory = 0; + int aggregatePermNextOwner = 0; + int flags = 0; + bool rvalue = false; + + IClientAPI cli = LocateClientObject(sourceId); + if (cli != null) { - lock (m_KnownClientFunds) + Scene userScene = null; + lock (m_rootAgents) { - // If we don't know about the sender, then the sender can't - // actually be here and therefore this is likely fraud or outdated. - if (m_MoneyAddress.Length == 0) - { - if (m_KnownClientFunds.ContainsKey(Sender)) - { - // Does the sender have enough funds to give? - if (m_KnownClientFunds[Sender] >= amount) - { - // Subtract the funds from the senders account - m_KnownClientFunds[Sender] -= amount; - - // do we know about the receiver? - if (!m_KnownClientFunds.ContainsKey(Receiver)) - { - // Make a record for them so they get the updated balance when they login - CheckExistAndRefreshFunds(Receiver); - } - if (m_enabled) - { - //Add the amount to the Receiver's funds - m_KnownClientFunds[Receiver] += amount; - result = true; - } + userScene = GetSceneByUUID(m_rootAgents[sourceId]); + } + if (userScene != null) + { + Hashtable ht = new Hashtable(); + ht["agentId"] = sourceId.ToString(); + ht["secureSessionId"] = cli.SecureSessionId.ToString(); + ht["regionId"] = userScene.RegionInfo.originRegionID.ToString(); + ht["secret"] = userScene.RegionInfo.regionSecret; + ht["currencySecret"] = " "; + ht["destId"] = destId.ToString(); + ht["cash"] = amount; + ht["aggregatePermInventory"] = aggregatePermInventory; + ht["aggregatePermNextOwner"] = aggregatePermNextOwner; + ht["flags"] = flags; + ht["transactionType"] = transactiontype; + ht["description"] = description; + + Hashtable hresult = genericCurrencyXMLRPCRequest(ht, "regionMoveMoney"); + + if ((bool) hresult["success"] == true) + { + int funds1 = 0; + int funds2 = 0; + try + { + funds1 = (Int32) hresult["funds"]; + } + catch (InvalidCastException) + { + funds1 = 0; + } + SetLocalFundsForAgentID(sourceId, funds1); + if (m_KnownClientFunds.ContainsKey(destId)) + { + try + { + funds2 = (Int32) hresult["funds2"]; } - else + catch (InvalidCastException) { - // These below are redundant to make this clearer to read - result = false; + funds2 = 0; } + SetLocalFundsForAgentID(destId, funds2); } - else - { - result = false; - } + + + rvalue = true; } else { - result = TransferMoneyonMoneyServer(Sender, Receiver, amount, transactiontype, description); + cli.SendAgentAlertMessage((string) hresult["errorMessage"], true); } } } - return result; + else + { + m_log.ErrorFormat("[MONEY]: Client {0} not found", sourceId.ToString()); + } + + return rvalue; } - #region Utility Helpers - /// - /// Locates a IClientAPI for the client specified - /// - /// - /// - private IClientAPI LocateClientObject(LLUUID AgentID) + public int GetRemoteBalance(LLUUID agentId) { - ScenePresence tPresence = null; - IClientAPI rclient = null; + int funds = 0; - lock (m_scenel) + IClientAPI aClient = LocateClientObject(agentId); + if (aClient != null) { - foreach (Scene _scene in m_scenel.Values) + Scene s = LocateSceneClientIn(agentId); + if (s != null) { - tPresence = _scene.GetScenePresence(AgentID); - if (tPresence != null) + if (m_MoneyAddress.Length > 0) { - if (!tPresence.IsChildAgent) + Hashtable hbinfo = + GetBalanceForUserFromMoneyServer(aClient.AgentId, aClient.SecureSessionId, s.RegionInfo.originRegionID.ToString(), + s.RegionInfo.regionSecret); + if ((bool) hbinfo["success"] == true) { - rclient = tPresence.ControllingClient; + try + { + funds = (Int32) hbinfo["funds"]; + } + catch (ArgumentException) + { + } + catch (FormatException) + { + } + catch (OverflowException) + { + m_log.ErrorFormat("[MONEY]: While getting the Currency for user {0}, the return funds overflowed.", agentId); + aClient.SendAlertMessage("Unable to get your money balance, money operations will be unavailable"); + } + catch (InvalidCastException) + { + funds = 0; + } + } + else + { + m_log.WarnFormat("[MONEY]: Getting Money for user {0} failed with the following message:{1}", agentId, + (string) hbinfo["errorMessage"]); + aClient.SendAlertMessage((string) hbinfo["errorMessage"]); } } - if (rclient != null) - { - return rclient; - } - } + SetLocalFundsForAgentID(agentId, funds); + SendMoneyBalance(aClient, agentId, aClient.SessionId, LLUUID.Zero); + } + else + { + m_log.Debug("[MONEY]: Got balance request update for agent that is here, but couldn't find which scene."); + } } - return null; + else + { + m_log.Debug("[MONEY]: Got balance request update for agent that isn't here."); + } + return funds; } - private Scene LocateSceneClientIn(LLUUID AgentId) + public XmlRpcResponse GridMoneyUpdate(XmlRpcRequest request) { - lock (m_scenel) + m_log.Debug("[MONEY]: Dynamic balance update called."); + Hashtable requestData = (Hashtable) request.Params[0]; + + if (requestData.ContainsKey("agentId")) { - foreach (Scene _scene in m_scenel.Values) - { - ScenePresence tPresence = _scene.GetScenePresence(AgentId); - if (tPresence != null) - { - if (!tPresence.IsChildAgent) - { - return _scene; - } - } + LLUUID agentId = LLUUID.Zero; + Helpers.TryParse((string) requestData["agentId"], out agentId); + if (agentId != LLUUID.Zero) + { + GetRemoteBalance(agentId); + } + else + { + m_log.Debug("[MONEY]: invalid agentId specified, dropping."); } - } - return null; - } - - /// - /// Utility function Gets a Random scene in the instance. For when which scene exactly you're doing something with doesn't matter - /// - /// - public Scene GetRandomScene() - { - lock (m_scenel) + else { - foreach (Scene rs in m_scenel.Values) - return rs; + m_log.Debug("[MONEY]: no agentId specified, dropping."); } - return null; + XmlRpcResponse r = new XmlRpcResponse(); + Hashtable rparms = new Hashtable(); + rparms["success"] = true; + r.Value = rparms; + return r; } + /// - /// Utility function to get a Scene by RegionID in a module + /// XMLRPC handler to send alert message and sound to client /// - /// - /// - public Scene GetSceneByUUID(LLUUID RegionID) + public XmlRpcResponse UserAlert(XmlRpcRequest request) { - lock (m_scenel) - { - foreach (Scene rs in m_scenel.Values) - { - if (rs.RegionInfo.originRegionID == RegionID) - { - return rs; - } - } - } - return null; - } - #endregion + XmlRpcResponse ret = new XmlRpcResponse(); + Hashtable retparam = new Hashtable(); + Hashtable requestData = (Hashtable) request.Params[0]; + LLUUID agentId = LLUUID.Zero; + LLUUID soundId = LLUUID.Zero; + Helpers.TryParse((string) requestData["agentId"], out agentId); + Helpers.TryParse((string) requestData["soundId"], out soundId); + string text = (string) requestData["text"]; + string secret = (string) requestData["secret"]; - /// - /// Sends the the stored money balance to the client - /// - /// - /// - /// - /// - public void SendMoneyBalance(IClientAPI client, LLUUID agentID, LLUUID SessionID, LLUUID TransactionID) - { - if (client.AgentId == agentID && client.SessionId == SessionID) + Scene userScene = GetRandomScene(); + if (userScene.RegionInfo.regionSecret.ToString() == secret) { - int returnfunds = 0; - - try + IClientAPI client = LocateClientObject(agentId); + + if (client != null) { - returnfunds = GetFundsForAgentID(agentID); + if (soundId != LLUUID.Zero) + client.SendPlayAttachedSound(soundId, LLUUID.Zero, LLUUID.Zero, 1.0f, 0); + client.SendBlueBoxMessage(LLUUID.Zero, LLUUID.Zero, "", text); + retparam.Add("success", true); } - catch (Exception e) + else { - client.SendAlertMessage(e.Message + " "); + retparam.Add("success", false); } - - client.SendMoneyBalance(TransactionID, true, new byte[0], returnfunds); } else { - client.SendAlertMessage("Unable to send your money balance to you!"); + retparam.Add("success", false); } + ret.Value = retparam; + + return ret; } - #region local Fund Management - /// - /// Ensures that the agent accounting data is set up in this instance. - /// - /// - private void CheckExistAndRefreshFunds(LLUUID agentID) + # region Standalone box enablers only + + public XmlRpcResponse quote_func(XmlRpcRequest request) { - lock (m_KnownClientFunds) + Hashtable requestData = (Hashtable) request.Params[0]; + LLUUID agentId = LLUUID.Zero; + int amount = 0; + Hashtable quoteResponse = new Hashtable(); + XmlRpcResponse returnval = new XmlRpcResponse(); + + if (requestData.ContainsKey("agentId") && requestData.ContainsKey("currencyBuy")) { - if (!m_KnownClientFunds.ContainsKey(agentID)) + Helpers.TryParse((string) requestData["agentId"], out agentId); + try { - m_KnownClientFunds.Add(agentID, m_stipend); + amount = (Int32) requestData["currencyBuy"]; } - else + catch (InvalidCastException) { - if (m_KnownClientFunds[agentID] <= m_minFundsBeforeRefresh) - { - m_KnownClientFunds[agentID] = m_stipend; - } } - } - } - /// - /// Gets the amount of Funds for an agent - /// - /// - /// - private int GetFundsForAgentID(LLUUID AgentID) - { - int returnfunds = 0; - lock (m_KnownClientFunds) - { - if (m_KnownClientFunds.ContainsKey(AgentID)) - { - returnfunds = m_KnownClientFunds[AgentID]; - } - else - { - //throw new Exception("Unable to get funds."); - } - } - return returnfunds; - } - private void SetLocalFundsForAgentID(LLUUID AgentID, int amount) - { - lock (m_KnownClientFunds) - { - if (m_KnownClientFunds.ContainsKey(AgentID)) - { - m_KnownClientFunds[AgentID] = amount; - } - else - { - m_KnownClientFunds.Add(AgentID, amount); - } - } - - } - - #endregion - - /// - /// Gets the current balance for the user from the Grid Money Server - /// - /// - /// - /// - /// - /// - public Hashtable GetBalanceForUserFromMoneyServer(LLUUID agentId, LLUUID secureSessionID, LLUUID regionId, string regionSecret) - { - - Hashtable MoneyBalanceRequestParams = new Hashtable(); - MoneyBalanceRequestParams["agentId"] = agentId.ToString(); - MoneyBalanceRequestParams["secureSessionId"] = secureSessionID.ToString(); - MoneyBalanceRequestParams["regionId"] = regionId.ToString(); - MoneyBalanceRequestParams["secret"] = regionSecret; - MoneyBalanceRequestParams["currencySecret"] = ""; // per - region/user currency secret gotten from the money system - - Hashtable MoneyRespData = genericCurrencyXMLRPCRequest(MoneyBalanceRequestParams, "simulatorUserBalanceRequest"); - - return MoneyRespData; - } - - - - /// - /// Generic XMLRPC client abstraction - /// - /// Hashtable containing parameters to the method - /// Method to invoke - /// Hashtable with success=>bool and other values - public Hashtable genericCurrencyXMLRPCRequest(Hashtable ReqParams, string method) - { - ArrayList SendParams = new ArrayList(); - SendParams.Add(ReqParams); - // Send Request - XmlRpcResponse MoneyResp; - try - { - XmlRpcRequest BalanceRequestReq = new XmlRpcRequest(method, SendParams); - MoneyResp = BalanceRequestReq.Send(m_MoneyAddress, 30000); - } - catch (WebException ex) - { - - m_log.ErrorFormat( - "[MONEY]: Unable to connect to Money Server {0}. Exception {1}", - m_MoneyAddress, ex); - - Hashtable ErrorHash = new Hashtable(); - ErrorHash["success"] = false; - ErrorHash["errorMessage"] = "Unable to manage your money at this time. Purchases may be unavailable"; - ErrorHash["errorURI"] = ""; - - return ErrorHash; - //throw (ex); - } - catch (SocketException ex) - { - - m_log.ErrorFormat( - "[MONEY]: Unable to connect to Money Server {0}. Exception {1}", - m_MoneyAddress, ex); - - Hashtable ErrorHash = new Hashtable(); - ErrorHash["success"] = false; - ErrorHash["errorMessage"] = "Unable to manage your money at this time. Purchases may be unavailable"; - ErrorHash["errorURI"] = ""; - - return ErrorHash; - //throw (ex); - } - catch (XmlException ex) - { - m_log.ErrorFormat( - "[MONEY]: Unable to connect to Money Server {0}. Exception {1}", - m_MoneyAddress, ex); - - Hashtable ErrorHash = new Hashtable(); - ErrorHash["success"] = false; - ErrorHash["errorMessage"] = "Unable to manage your money at this time. Purchases may be unavailable"; - ErrorHash["errorURI"] = ""; - - return ErrorHash; - - } - if (MoneyResp.IsFault) - { - Hashtable ErrorHash = new Hashtable(); - ErrorHash["success"] = false; - ErrorHash["errorMessage"] = "Unable to manage your money at this time. Purchases may be unavailable"; - ErrorHash["errorURI"] = ""; + Hashtable currencyResponse = new Hashtable(); + currencyResponse.Add("estimatedCost", 0); + currencyResponse.Add("currencyBuy", amount); - return ErrorHash; + quoteResponse.Add("success", true); + quoteResponse.Add("currency", currencyResponse); + quoteResponse.Add("confirm", "asdfad9fj39ma9fj"); + returnval.Value = quoteResponse; + return returnval; } - Hashtable MoneyRespData = (Hashtable)MoneyResp.Value; - - return MoneyRespData; - } - /// - /// This informs the Money Grid Server that the avatar is in this simulator - /// - /// - /// - /// - /// - /// - public Hashtable claim_user(LLUUID agentId, LLUUID secureSessionID, LLUUID regionId, string regionSecret) - { - Hashtable MoneyBalanceRequestParams = new Hashtable(); - MoneyBalanceRequestParams["agentId"] = agentId.ToString(); - MoneyBalanceRequestParams["secureSessionId"] = secureSessionID.ToString(); - MoneyBalanceRequestParams["regionId"] = regionId.ToString(); - MoneyBalanceRequestParams["secret"] = regionSecret; - Hashtable MoneyRespData = genericCurrencyXMLRPCRequest(MoneyBalanceRequestParams, "simulatorClaimUserRequest"); - IClientAPI sendMoneyBal = LocateClientObject(agentId); - if (sendMoneyBal != null) - { - SendMoneyBalance(sendMoneyBal, agentId, sendMoneyBal.SessionId, LLUUID.Zero); - } - return MoneyRespData; + quoteResponse.Add("success", false); + quoteResponse.Add("errorMessage", "Invalid parameters passed to the quote box"); + quoteResponse.Add("errorURI", "http://www.opensimulator.org/wiki"); + returnval.Value = quoteResponse; + return returnval; } - private SceneObjectPart findPrim(LLUUID objectID) + public XmlRpcResponse buy_func(XmlRpcRequest request) { - lock (m_scenel) + Hashtable requestData = (Hashtable) request.Params[0]; + LLUUID agentId = LLUUID.Zero; + int amount = 0; + if (requestData.ContainsKey("agentId") && requestData.ContainsKey("currencyBuy")) { - foreach (Scene s in m_scenel.Values) + Helpers.TryParse((string) requestData["agentId"], out agentId); + try + { + amount = (Int32) requestData["currencyBuy"]; + } + catch (InvalidCastException) { - SceneObjectPart part=s.GetSceneObjectPart(objectID); - if(part != null) + } + if (agentId != LLUUID.Zero) + { + lock (m_KnownClientFunds) { - return part; + if (m_KnownClientFunds.ContainsKey(agentId)) + { + m_KnownClientFunds[agentId] += amount; + } + else + { + m_KnownClientFunds.Add(agentId, amount); + } + } + IClientAPI client = LocateClientObject(agentId); + if (client != null) + { + SendMoneyBalance(client, agentId, client.SessionId, LLUUID.Zero); } } } - return null; - } - - private string resolveObjectName(LLUUID objectID) - { - SceneObjectPart part=findPrim(objectID); - if(part != null) - { - return part.Name; - } - return String.Empty; + XmlRpcResponse returnval = new XmlRpcResponse(); + Hashtable returnresp = new Hashtable(); + returnresp.Add("success", true); + returnval.Value = returnresp; + return returnval; } - private string resolveAgentName(LLUUID agentID) + public XmlRpcResponse preflightBuyLandPrep_func(XmlRpcRequest request) { - // try avatar username surname - Scene scene=GetRandomScene(); - UserProfileData profile = scene.CommsManager.UserService.GetUserProfile(agentID); - if (profile != null) - { - string avatarname = profile.FirstName + " " + profile.SurName; - return avatarname; - } - return String.Empty; - } + XmlRpcResponse ret = new XmlRpcResponse(); + Hashtable retparam = new Hashtable(); + Hashtable membershiplevels = new Hashtable(); + ArrayList levels = new ArrayList(); + Hashtable level = new Hashtable(); + level.Add("id", "00000000-0000-0000-0000-000000000000"); + level.Add("description", "some level"); + levels.Add(level); + //membershiplevels.Add("levels",levels); - public bool ObjectGiveMoney(LLUUID objectID, LLUUID fromID, LLUUID toID, int amount) - { - string description=String.Format("Object {0} pays {1}", resolveObjectName(objectID), resolveAgentName(toID)); + Hashtable landuse = new Hashtable(); + landuse.Add("upgrade", false); + landuse.Add("action", "http://invaliddomaininvalid.com/"); - bool give_result = doMoneyTransfer(fromID, toID, amount, 2, description); + Hashtable currency = new Hashtable(); + currency.Add("estimatedCost", 0); - if (m_MoneyAddress.Length == 0) - BalanceUpdate(fromID, toID, give_result, description); + Hashtable membership = new Hashtable(); + membershiplevels.Add("upgrade", false); + membershiplevels.Add("action", "http://invaliddomaininvalid.com/"); + membershiplevels.Add("levels", membershiplevels); - return give_result; + retparam.Add("success", true); + retparam.Add("currency", currency); + retparam.Add("membership", membership); + retparam.Add("landuse", landuse); + retparam.Add("confirm", "asdfajsdkfjasdkfjalsdfjasdf"); + ret.Value = retparam; + return ret; } - private void BalanceUpdate(LLUUID senderID, LLUUID receiverID, bool transactionresult, string description) + + public XmlRpcResponse landBuy_func(XmlRpcRequest request) { - IClientAPI sender = LocateClientObject(senderID); - IClientAPI receiver = LocateClientObject(receiverID); + XmlRpcResponse ret = new XmlRpcResponse(); + Hashtable retparam = new Hashtable(); + Hashtable requestData = (Hashtable) request.Params[0]; - if (senderID != receiverID) + LLUUID agentId = LLUUID.Zero; + int amount = 0; + if (requestData.ContainsKey("agentId") && requestData.ContainsKey("currencyBuy")) { - if (sender != null) + Helpers.TryParse((string) requestData["agentId"], out agentId); + try { - sender.SendMoneyBalance(LLUUID.Random(), transactionresult, Helpers.StringToField(description), GetFundsForAgentID(senderID)); + amount = (Int32) requestData["currencyBuy"]; } - - if (receiver != null) + catch (InvalidCastException) { - receiver.SendMoneyBalance(LLUUID.Random(), transactionresult, Helpers.StringToField(description), GetFundsForAgentID(receiverID)); + } + if (agentId != LLUUID.Zero) + { + lock (m_KnownClientFunds) + { + if (m_KnownClientFunds.ContainsKey(agentId)) + { + m_KnownClientFunds[agentId] += amount; + } + else + { + m_KnownClientFunds.Add(agentId, amount); + } + } + IClientAPI client = LocateClientObject(agentId); + if (client != null) + { + SendMoneyBalance(client, agentId, client.SessionId, LLUUID.Zero); + } } } + retparam.Add("success", true); + ret.Value = retparam; + + return ret; } + #endregion + + #region local Fund Management + /// - /// Informs the Money Grid Server of a transfer. + /// Ensures that the agent accounting data is set up in this instance. /// - /// - /// - /// - /// - public bool TransferMoneyonMoneyServer(LLUUID sourceId, LLUUID destId, int amount, int transactiontype, string description) + /// + private void CheckExistAndRefreshFunds(LLUUID agentID) { - int aggregatePermInventory = 0; - int aggregatePermNextOwner = 0; - int flags = 0; - bool rvalue = false; - - IClientAPI cli = LocateClientObject(sourceId); - if (cli != null) + lock (m_KnownClientFunds) { - - Scene userScene = null; - lock (m_rootAgents) + if (!m_KnownClientFunds.ContainsKey(agentID)) { - userScene = GetSceneByUUID(m_rootAgents[sourceId]); + m_KnownClientFunds.Add(agentID, m_stipend); } - if (userScene != null) - { - Hashtable ht = new Hashtable(); - ht["agentId"] = sourceId.ToString(); - ht["secureSessionId"] = cli.SecureSessionId.ToString(); - ht["regionId"] = userScene.RegionInfo.originRegionID.ToString(); - ht["secret"] = userScene.RegionInfo.regionSecret; - ht["currencySecret"] = " "; - ht["destId"] = destId.ToString(); - ht["cash"] = amount; - ht["aggregatePermInventory"] = aggregatePermInventory; - ht["aggregatePermNextOwner"] = aggregatePermNextOwner; - ht["flags"] = flags; - ht["transactionType"] = transactiontype; - ht["description"] = description; - - Hashtable hresult = genericCurrencyXMLRPCRequest(ht, "regionMoveMoney"); - - if ((bool)hresult["success"] == true) - { - int funds1 = 0; - int funds2 = 0; - try - { - funds1 = (Int32)hresult["funds"]; - } - catch(InvalidCastException) - { - funds1 = 0; - } - SetLocalFundsForAgentID(sourceId, funds1); - if (m_KnownClientFunds.ContainsKey(destId)) - { - try - { - funds2 = (Int32)hresult["funds2"]; - } - catch (InvalidCastException) - { - funds2 = 0; - } - SetLocalFundsForAgentID(destId, funds2); - } - - - rvalue = true; - } - else + else + { + if (m_KnownClientFunds[agentID] <= m_minFundsBeforeRefresh) { - cli.SendAgentAlertMessage((string)hresult["errorMessage"], true); + m_KnownClientFunds[agentID] = m_stipend; } - } } - else - { - m_log.ErrorFormat("[MONEY]: Client {0} not found", sourceId.ToString()); - } - - return rvalue; - } - public int GetRemoteBalance(LLUUID agentId) + /// + /// Gets the amount of Funds for an agent + /// + /// + /// + private int GetFundsForAgentID(LLUUID AgentID) { - int funds = 0; - - IClientAPI aClient = LocateClientObject(agentId); - if (aClient != null) + int returnfunds = 0; + lock (m_KnownClientFunds) { - Scene s = LocateSceneClientIn(agentId); - if (s != null) + if (m_KnownClientFunds.ContainsKey(AgentID)) { - if (m_MoneyAddress.Length > 0) - { - Hashtable hbinfo = GetBalanceForUserFromMoneyServer(aClient.AgentId, aClient.SecureSessionId, s.RegionInfo.originRegionID.ToString(), s.RegionInfo.regionSecret); - if ((bool)hbinfo["success"] == true) - { - try - { - funds = (Int32)hbinfo["funds"]; - } - catch (ArgumentException) - { - } - catch (FormatException) - { - } - catch (OverflowException) - { - m_log.ErrorFormat("[MONEY]: While getting the Currency for user {0}, the return funds overflowed.", agentId); - aClient.SendAlertMessage("Unable to get your money balance, money operations will be unavailable"); - } - catch (InvalidCastException) - { - funds = 0; - } - - } - else - { - m_log.WarnFormat("[MONEY]: Getting Money for user {0} failed with the following message:{1}", agentId, (string)hbinfo["errorMessage"]); - aClient.SendAlertMessage((string)hbinfo["errorMessage"]); - } - } - - SetLocalFundsForAgentID(agentId, funds); - SendMoneyBalance(aClient, agentId, aClient.SessionId, LLUUID.Zero); + returnfunds = m_KnownClientFunds[AgentID]; } else { - m_log.Debug("[MONEY]: Got balance request update for agent that is here, but couldn't find which scene."); + //throw new Exception("Unable to get funds."); } } - else - { - m_log.Debug("[MONEY]: Got balance request update for agent that isn't here."); - } - return funds; + return returnfunds; } - public XmlRpcResponse GridMoneyUpdate(XmlRpcRequest request) + private void SetLocalFundsForAgentID(LLUUID AgentID, int amount) { - m_log.Debug("[MONEY]: Dynamic balance update called."); - Hashtable requestData = (Hashtable)request.Params[0]; - - if (requestData.ContainsKey("agentId")) + lock (m_KnownClientFunds) { - LLUUID agentId = LLUUID.Zero; - - Helpers.TryParse((string)requestData["agentId"], out agentId); - if (agentId != LLUUID.Zero) + if (m_KnownClientFunds.ContainsKey(AgentID)) { - GetRemoteBalance(agentId); - + m_KnownClientFunds[AgentID] = amount; } else { - m_log.Debug("[MONEY]: invalid agentId specified, dropping."); + m_KnownClientFunds.Add(AgentID, amount); } } - else - { - m_log.Debug("[MONEY]: no agentId specified, dropping."); - } - XmlRpcResponse r = new XmlRpcResponse(); - Hashtable rparms = new Hashtable(); - rparms["success"] = true; - - r.Value = rparms; - return r; } + #endregion + + #region Utility Helpers + /// - /// XMLRPC handler to send alert message and sound to client + /// Locates a IClientAPI for the client specified /// - public XmlRpcResponse UserAlert(XmlRpcRequest request) + /// + /// + private IClientAPI LocateClientObject(LLUUID AgentID) { - XmlRpcResponse ret = new XmlRpcResponse(); - Hashtable retparam = new Hashtable(); - Hashtable requestData = (Hashtable)request.Params[0]; - - LLUUID agentId = LLUUID.Zero; - LLUUID soundId = LLUUID.Zero; - - Helpers.TryParse((string)requestData["agentId"], out agentId); - Helpers.TryParse((string)requestData["soundId"], out soundId); - string text=(string)requestData["text"]; - string secret=(string)requestData["secret"]; + ScenePresence tPresence = null; + IClientAPI rclient = null; - Scene userScene = GetRandomScene(); - if(userScene.RegionInfo.regionSecret.ToString() == secret) + lock (m_scenel) { - IClientAPI client = LocateClientObject(agentId); - - if (client != null) + foreach (Scene _scene in m_scenel.Values) { - if(soundId != LLUUID.Zero) - client.SendPlayAttachedSound(soundId, LLUUID.Zero, LLUUID.Zero, 1.0f, 0); - client.SendBlueBoxMessage(LLUUID.Zero, LLUUID.Zero, "", text); - retparam.Add("success", true); + tPresence = _scene.GetScenePresence(AgentID); + if (tPresence != null) + { + if (!tPresence.IsChildAgent) + { + rclient = tPresence.ControllingClient; + } + } + if (rclient != null) + { + return rclient; + } } - else + } + return null; + } + + private Scene LocateSceneClientIn(LLUUID AgentId) + { + lock (m_scenel) + { + foreach (Scene _scene in m_scenel.Values) { - retparam.Add("success", false); + ScenePresence tPresence = _scene.GetScenePresence(AgentId); + if (tPresence != null) + { + if (!tPresence.IsChildAgent) + { + return _scene; + } + } } } - else + return null; + } + + /// + /// Utility function Gets a Random scene in the instance. For when which scene exactly you're doing something with doesn't matter + /// + /// + public Scene GetRandomScene() + { + lock (m_scenel) { - retparam.Add("success", false); + foreach (Scene rs in m_scenel.Values) + return rs; } - ret.Value = retparam; + return null; + } - return ret; + /// + /// Utility function to get a Scene by RegionID in a module + /// + /// + /// + public Scene GetSceneByUUID(LLUUID RegionID) + { + lock (m_scenel) + { + foreach (Scene rs in m_scenel.Values) + { + if (rs.RegionInfo.originRegionID == RegionID) + { + return rs; + } + } + } + return null; } + #endregion - # region Standalone box enablers only + #region event Handlers - public XmlRpcResponse quote_func(XmlRpcRequest request) + public void requestPayPrice(IClientAPI client, LLUUID objectID) { - Hashtable requestData = (Hashtable)request.Params[0]; - LLUUID agentId = LLUUID.Zero; - int amount = 0; - Hashtable quoteResponse = new Hashtable(); - XmlRpcResponse returnval = new XmlRpcResponse(); + Scene scene = LocateSceneClientIn(client.AgentId); + if (scene == null) + return; - if (requestData.ContainsKey("agentId") && requestData.ContainsKey("currencyBuy")) + SceneObjectPart task = scene.GetSceneObjectPart(objectID); + if (task == null) + return; + SceneObjectGroup group = task.ParentGroup; + SceneObjectPart root = group.RootPart; + + client.SendPayPrice(objectID, root.PayPrice); + } + + /// + /// When the client closes the connection we remove their accounting info from memory to free up resources. + /// + /// + public void ClientClosed(LLUUID AgentID) + { + lock (m_KnownClientFunds) { - Helpers.TryParse((string)requestData["agentId"], out agentId); - try + if (m_keepMoneyAcrossLogins && m_MoneyAddress.Length == 0) { - amount = (Int32)requestData["currencyBuy"]; } - catch (InvalidCastException) + else { - + m_KnownClientFunds.Remove(AgentID); } - Hashtable currencyResponse = new Hashtable(); - currencyResponse.Add("estimatedCost", 0); - currencyResponse.Add("currencyBuy", amount); - - quoteResponse.Add("success", true); - quoteResponse.Add("currency", currencyResponse); - quoteResponse.Add("confirm", "asdfad9fj39ma9fj"); - - returnval.Value = quoteResponse; - return returnval; } - - - - quoteResponse.Add("success", false); - quoteResponse.Add("errorMessage", "Invalid parameters passed to the quote box"); - quoteResponse.Add("errorURI", "http://www.opensimulator.org/wiki"); - returnval.Value = quoteResponse; - return returnval; } - public XmlRpcResponse buy_func(XmlRpcRequest request) + + /// + /// Event called Economy Data Request handler. + /// + /// + public void EconomyDataRequestHandler(LLUUID agentId) { + IClientAPI user = LocateClientObject(agentId); - Hashtable requestData = (Hashtable)request.Params[0]; - LLUUID agentId = LLUUID.Zero; - int amount = 0; - if (requestData.ContainsKey("agentId") && requestData.ContainsKey("currencyBuy")) + if (user != null) { - Helpers.TryParse((string)requestData["agentId"], out agentId); - try - { - amount = (Int32)requestData["currencyBuy"]; - } - catch (InvalidCastException) - { + user.SendEconomyData(EnergyEfficiency, ObjectCapacity, ObjectCount, PriceEnergyUnit, PriceGroupCreate, + PriceObjectClaim, PriceObjectRent, PriceObjectScaleFactor, PriceParcelClaim, PriceParcelClaimFactor, + PriceParcelRent, PricePublicObjectDecay, PricePublicObjectDelete, PriceRentLight, PriceUpload, + TeleportMinPrice, TeleportPriceExponent); + } + } - } - if (agentId != LLUUID.Zero) + private void ValidateLandBuy(Object osender, EventManager.LandBuyArgs e) + { + if (m_MoneyAddress.Length == 0) + { + lock (m_KnownClientFunds) { - lock (m_KnownClientFunds) + if (m_KnownClientFunds.ContainsKey(e.agentId)) { - if (m_KnownClientFunds.ContainsKey(agentId)) - { - m_KnownClientFunds[agentId] += amount; - } - else + // Does the sender have enough funds to give? + if (m_KnownClientFunds[e.agentId] >= e.parcelPrice) { - m_KnownClientFunds.Add(agentId, amount); + lock (e) + { + e.economyValidated = true; + } } } - IClientAPI client = LocateClientObject(agentId); - if (client != null) + } + } + else + { + if (GetRemoteBalance(e.agentId) >= e.parcelPrice) + { + lock (e) { - SendMoneyBalance(client, agentId, client.SessionId, LLUUID.Zero); + e.economyValidated = true; } } } - XmlRpcResponse returnval = new XmlRpcResponse(); - Hashtable returnresp = new Hashtable(); - returnresp.Add("success", true); - returnval.Value = returnresp; - return returnval; } - public XmlRpcResponse preflightBuyLandPrep_func(XmlRpcRequest request) + private void processLandBuy(Object osender, EventManager.LandBuyArgs e) { - XmlRpcResponse ret = new XmlRpcResponse(); - Hashtable retparam = new Hashtable(); - Hashtable membershiplevels = new Hashtable(); - ArrayList levels = new ArrayList(); - Hashtable level = new Hashtable(); - level.Add("id", "00000000-0000-0000-0000-000000000000"); - level.Add("description", "some level"); - levels.Add(level); - //membershiplevels.Add("levels",levels); - - Hashtable landuse = new Hashtable(); - landuse.Add("upgrade", false); - landuse.Add("action", "http://invaliddomaininvalid.com/"); + lock (e) + { + if (e.economyValidated == true && e.transactionID == 0) + { + e.transactionID = Util.UnixTimeSinceEpoch(); - Hashtable currency = new Hashtable(); - currency.Add("estimatedCost", 0); + if (doMoneyTransfer(e.agentId, e.parcelOwnerID, e.parcelPrice, 0, "Land purchase")) + { + lock (e) + { + e.amountDebited = e.parcelPrice; + } + } + } + } + } - Hashtable membership = new Hashtable(); - membershiplevels.Add("upgrade", false); - membershiplevels.Add("action", "http://invaliddomaininvalid.com/"); - membershiplevels.Add("levels", membershiplevels); + /// + /// THis method gets called when someone pays someone else as a gift. + /// + /// + /// + private void MoneyTransferAction(Object osender, EventManager.MoneyTransferArgs e) + { + IClientAPI sender = null; + IClientAPI receiver = null; - retparam.Add("success", true); - retparam.Add("currency", currency); - retparam.Add("membership", membership); - retparam.Add("landuse", landuse); - retparam.Add("confirm", "asdfajsdkfjasdkfjalsdfjasdf"); + if (m_MoneyAddress.Length > 0) // Handled on server + e.description = String.Empty; - ret.Value = retparam; + if (e.transactiontype == 5008) // Object gets paid + { + sender = LocateClientObject(e.sender); + if (sender != null) + { + SceneObjectPart part = findPrim(e.receiver); + if (part == null) + return; - return ret; + string name = resolveAgentName(part.OwnerID); + if (name == String.Empty) + name = "(hippos)"; - } - public XmlRpcResponse landBuy_func(XmlRpcRequest request) - { - XmlRpcResponse ret = new XmlRpcResponse(); - Hashtable retparam = new Hashtable(); - Hashtable requestData = (Hashtable)request.Params[0]; + receiver = LocateClientObject(part.OwnerID); - LLUUID agentId = LLUUID.Zero; - int amount = 0; - if (requestData.ContainsKey("agentId") && requestData.ContainsKey("currencyBuy")) - { - Helpers.TryParse((string)requestData["agentId"], out agentId); - try - { - amount = (Int32)requestData["currencyBuy"]; - } - catch (InvalidCastException) - { + string description = String.Format("Paid {0} via object {1}", name, e.description); + bool transactionresult = doMoneyTransfer(e.sender, part.OwnerID, e.amount, e.transactiontype, description); - } - if (agentId != LLUUID.Zero) - { - lock (m_KnownClientFunds) + if (transactionresult) { - if (m_KnownClientFunds.ContainsKey(agentId)) - { - m_KnownClientFunds[agentId] += amount; - } - else + ObjectPaid handlerOnObjectPaid = OnObjectPaid; + if (handlerOnObjectPaid != null) { - m_KnownClientFunds.Add(agentId, amount); + handlerOnObjectPaid(e.receiver, e.sender, e.amount); } } - IClientAPI client = LocateClientObject(agentId); - if (client != null) + + if (e.sender != e.receiver) { - SendMoneyBalance(client, agentId, client.SessionId, LLUUID.Zero); + sender.SendMoneyBalance(LLUUID.Random(), transactionresult, Helpers.StringToField(e.description), GetFundsForAgentID(e.sender)); + } + if (receiver != null) + { + receiver.SendMoneyBalance(LLUUID.Random(), transactionresult, Helpers.StringToField(e.description), GetFundsForAgentID(part.OwnerID)); } } + return; } - retparam.Add("success", true); - ret.Value = retparam; - return ret; + sender = LocateClientObject(e.sender); + if (sender != null) + { + receiver = LocateClientObject(e.receiver); + + bool transactionresult = doMoneyTransfer(e.sender, e.receiver, e.amount, e.transactiontype, e.description); + + if (e.sender != e.receiver) + { + if (sender != null) + { + sender.SendMoneyBalance(LLUUID.Random(), transactionresult, Helpers.StringToField(e.description), GetFundsForAgentID(e.sender)); + } + } + if (receiver != null) + { + receiver.SendMoneyBalance(LLUUID.Random(), transactionresult, Helpers.StringToField(e.description), GetFundsForAgentID(e.receiver)); + } + } + else + { + m_log.Warn("[MONEY]: Potential Fraud Warning, got money transfer request for avatar that isn't in this simulator - Details; Sender:" + + e.sender.ToString() + " Receiver: " + e.receiver.ToString() + " Amount: " + e.amount.ToString()); + } } - #endregion - public void PostInitialise() + /// + /// Event Handler for when a root agent becomes a child agent + /// + /// + private void MakeChildAgent(ScenePresence avatar) { + lock (m_rootAgents) + { + if (m_rootAgents.ContainsKey(avatar.UUID)) + { + if (m_rootAgents[avatar.UUID] == avatar.Scene.RegionInfo.originRegionID) + { + m_rootAgents.Remove(avatar.UUID); + m_log.Info("[MONEY]: Removing " + avatar.Firstname + " " + avatar.Lastname + " as a root agent"); + } + } + } } - public void Close() + /// + /// Event Handler for when the client logs out. + /// + /// + private void ClientLoggedOut(LLUUID AgentId) { + lock (m_rootAgents) + { + if (m_rootAgents.ContainsKey(AgentId)) + { + m_rootAgents.Remove(AgentId); + //m_log.Info("[MONEY]: Removing " + AgentId + ". Agent logged out."); + } + } } - public string Name + /// + /// Call this when the client disconnects. + /// + /// + public void ClientClosed(IClientAPI client) { - get { return "BetaGridLikeMoneyModule"; } + ClientClosed(client.AgentId); } - public bool IsSharedModule + /// + /// Event Handler for when an Avatar enters one of the parcels in the simulator. + /// + /// + /// + /// + private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, LLUUID regionID) { - get { return true; } + lock (m_rootAgents) + { + if (m_rootAgents.ContainsKey(avatar.UUID)) + { + if (avatar.Scene.RegionInfo.originRegionID != m_rootAgents[avatar.UUID]) + { + m_rootAgents[avatar.UUID] = avatar.Scene.RegionInfo.originRegionID; + //m_log.Info("[MONEY]: Claiming " + avatar.Firstname + " " + avatar.Lastname + " in region:" + avatar.RegionHandle + "."); + // Claim User! my user! Mine mine mine! + if (m_MoneyAddress.Length > 0) + { + Scene RegionItem = GetSceneByUUID(regionID); + if (RegionItem != null) + { + Hashtable hresult = + claim_user(avatar.UUID, avatar.ControllingClient.SecureSessionId, regionID, RegionItem.RegionInfo.regionSecret); + if ((bool) hresult["success"] == true) + { + int funds = 0; + try + { + funds = (Int32) hresult["funds"]; + } + catch (InvalidCastException) + { + } + SetLocalFundsForAgentID(avatar.UUID, funds); + } + else + { + avatar.ControllingClient.SendAgentAlertMessage((string) hresult["errorMessage"], true); + } + } + } + } + } + else + { + lock (m_rootAgents) + { + m_rootAgents.Add(avatar.UUID, avatar.Scene.RegionInfo.originRegionID); + } + if (m_MoneyAddress.Length > 0) + { + Scene RegionItem = GetSceneByUUID(regionID); + if (RegionItem != null) + { + Hashtable hresult = claim_user(avatar.UUID, avatar.ControllingClient.SecureSessionId, regionID, RegionItem.RegionInfo.regionSecret); + if ((bool) hresult["success"] == true) + { + int funds = 0; + try + { + funds = (Int32) hresult["funds"]; + } + catch (InvalidCastException) + { + } + SetLocalFundsForAgentID(avatar.UUID, funds); + } + else + { + avatar.ControllingClient.SendAgentAlertMessage((string) hresult["errorMessage"], true); + } + } + } + + //m_log.Info("[MONEY]: Claiming " + avatar.Firstname + " " + avatar.Lastname + " in region:" + avatar.RegionHandle + "."); + } + } + //m_log.Info("[FRIEND]: " + avatar.Name + " status:" + (!avatar.IsChildAgent).ToString()); } + + #endregion } public enum TransactionType : int { - SystemGenerated=0, - RegionMoneyRequest=1, - Gift=2, - Purchase=3 - + SystemGenerated = 0, + RegionMoneyRequest = 1, + Gift = 2, + Purchase = 3 } } \ No newline at end of file diff --git a/OpenSim/Region/Environment/Modules/Avatar/Friends/FriendsModule.cs b/OpenSim/Region/Environment/Modules/Avatar/Friends/FriendsModule.cs index 3b0cc4c..db38d87 100644 --- a/OpenSim/Region/Environment/Modules/Avatar/Friends/FriendsModule.cs +++ b/OpenSim/Region/Environment/Modules/Avatar/Friends/FriendsModule.cs @@ -42,13 +42,12 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + private Dictionary> FriendLists = new Dictionary>(); + private Dictionary m_pendingFriendRequests = new Dictionary(); + private Dictionary m_rootAgents = new Dictionary(); private List m_scene = new List(); - Dictionary m_rootAgents = new Dictionary(); - - Dictionary m_pendingFriendRequests = new Dictionary(); - - Dictionary> FriendLists = new Dictionary>(); + #region IRegionModule Members public void Initialise(Scene scene, IConfigSource config) { @@ -68,11 +67,33 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends scene.EventManager.OnMakeChildAgent += MakeChildAgent; scene.EventManager.OnClientClosed += ClientLoggedOut; } + + public void PostInitialise() + { + } + + public void Close() + { + } + + public string Name + { + get { return "FriendsModule"; } + } + + public bool IsSharedModule + { + get { return true; } + } + + #endregion + public XmlRpcResponse processPresenceUpdate(XmlRpcRequest req) { m_log.Info("[FRIENDS]: Got Notification about a user! OMG"); return new XmlRpcResponse(); } + private void OnNewClient(IClientAPI client) { // All friends establishment protocol goes over instant message @@ -83,7 +104,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends // Generated by LoginService. The friends are retreived from the database by the UserManager // Subscribe to instant messages - + client.OnInstantMessage += OnInstantMessage; client.OnApproveFriendRequest += OnApprovedFriendRequest; client.OnDenyFriendRequest += OnDenyFriendRequest; @@ -99,10 +120,10 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends { fl = FriendLists[client.AgentId]; } - else + else { fl = m_scene[0].GetFriendList(client.AgentId); - + //lock (FriendLists) //{ if (!FriendLists.ContainsKey(client.AgentId)) @@ -110,11 +131,11 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends //} } } - + List UpdateUsers = new List(); foreach (FriendListItem f in fl) - { + { if (m_rootAgents.ContainsKey(f.Friend)) { if (f.onlinestatus == false) @@ -169,10 +190,6 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends onp.AgentBlock = onpb; client.OutPacket(onp, ThrottleOutPacketType.Task); } - - - - } private void ClientLoggedOut(LLUUID AgentId) @@ -182,7 +199,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends if (m_rootAgents.ContainsKey(AgentId)) { m_rootAgents.Remove(AgentId); - m_log.Info("[FRIEND]: Removing " + AgentId + ". Agent logged out."); + m_log.Info("[FRIEND]: Removing " + AgentId + ". Agent logged out."); } } List lfli = new List(); @@ -208,7 +225,6 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends List flfli = new List(); try { - lock (FriendLists) { if (FriendLists.ContainsKey(updateUsers[i])) @@ -231,9 +247,8 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends { flfli[i].onlinestatus = false; } - } - + catch (IndexOutOfRangeException) { // Ignore the index out of range exception. @@ -242,15 +257,13 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends m_log.Info("[FRIEND]: Unable to enumerate last friendlist user. User logged off"); } } - } - + for (int i = 0; i < updateUsers.Count; i++) { ScenePresence av = GetPresenceFromAgentID(updateUsers[i]); if (av != null) { - OfflineNotificationPacket onp = new OfflineNotificationPacket(); OfflineNotificationPacket.AgentBlockBlock[] onpb = new OfflineNotificationPacket.AgentBlockBlock[1]; OfflineNotificationPacket.AgentBlockBlock onpbl = new OfflineNotificationPacket.AgentBlockBlock(); @@ -265,7 +278,6 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends { FriendLists.Remove(AgentId); } - } private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, LLUUID regionID) @@ -282,7 +294,6 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends { JId avatarID = new JId(avatar.JID); // REST Post XMPP Stanzas! - } // Claim User! my user! Mine mine mine! } @@ -295,9 +306,9 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends } //m_log.Info("[FRIEND]: " + avatar.Name + " status:" + (!avatar.IsChildAgent).ToString()); } + private void MakeChildAgent(ScenePresence avatar) { - lock (m_rootAgents) { if (m_rootAgents.ContainsKey(avatar.UUID)) @@ -307,30 +318,53 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends m_rootAgents.Remove(avatar.UUID); m_log.Info("[FRIEND]: Removing " + avatar.Firstname + " " + avatar.Lastname + " as a root agent"); } - } } + } + private ScenePresence GetPresenceFromAgentID(LLUUID AgentID) + { + ScenePresence returnAgent = null; + lock (m_scene) + { + ScenePresence queryagent = null; + for (int i = 0; i < m_scene.Count; i++) + { + queryagent = m_scene[i].GetScenePresence(AgentID); + if (queryagent != null) + { + if (!queryagent.IsChildAgent) + { + returnAgent = queryagent; + break; + } + } + } + } + return returnAgent; } + #region FriendRequestHandling - private void OnInstantMessage(IClientAPI client,LLUUID fromAgentID, + + private void OnInstantMessage(IClientAPI client, LLUUID fromAgentID, LLUUID fromAgentSession, LLUUID toAgentID, LLUUID imSessionID, uint timestamp, string fromAgentName, - string message, byte dialog, bool fromGroup, byte offline, - uint ParentEstateID, LLVector3 Position, LLUUID RegionID, + string message, byte dialog, bool fromGroup, byte offline, + uint ParentEstateID, LLVector3 Position, LLUUID RegionID, byte[] binaryBucket) { // Friend Requests go by Instant Message.. using the dialog param // https://wiki.secondlife.com/wiki/ImprovedInstantMessage // 38 == Offer friendship - if (dialog == (byte)38) + if (dialog == (byte) 38) { LLUUID friendTransactionID = LLUUID.Random(); m_pendingFriendRequests.Add(friendTransactionID, fromAgentID); - m_log.Info("[FRIEND]: 38 - From:" + fromAgentID.ToString() + " To: " + toAgentID.ToString() + " Session:" + imSessionID.ToString() + " Message:" + message); + m_log.Info("[FRIEND]: 38 - From:" + fromAgentID.ToString() + " To: " + toAgentID.ToString() + " Session:" + imSessionID.ToString() + " Message:" + + message); GridInstantMessage msg = new GridInstantMessage(); msg.fromAgentID = fromAgentID.UUID; msg.fromAgentSession = fromAgentSession.UUID; @@ -340,11 +374,11 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends msg.timestamp = timestamp; if (client != null) { - msg.fromAgentName = client.FirstName + " " + client.LastName;// fromAgentName; + msg.fromAgentName = client.FirstName + " " + client.LastName; // fromAgentName; } else { - msg.fromAgentName = "(hippos)";// Added for posterity. This means that we can't figure out who sent it + msg.fromAgentName = "(hippos)"; // Added for posterity. This means that we can't figure out who sent it } msg.message = message; msg.dialog = dialog; @@ -359,15 +393,17 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends } // 39 == Accept Friendship - if (dialog == (byte)39) + if (dialog == (byte) 39) { - m_log.Info("[FRIEND]: 39 - From:" + fromAgentID.ToString() + " To: " + toAgentID.ToString() + " Session:" + imSessionID.ToString() + " Message:" + message); + m_log.Info("[FRIEND]: 39 - From:" + fromAgentID.ToString() + " To: " + toAgentID.ToString() + " Session:" + imSessionID.ToString() + " Message:" + + message); } // 40 == Decline Friendship - if (dialog == (byte)40) + if (dialog == (byte) 40) { - m_log.Info("[FRIEND]: 40 - From:" + fromAgentID.ToString() + " To: " + toAgentID.ToString() + " Session:" + imSessionID.ToString() + " Message:" + message); + m_log.Info("[FRIEND]: 40 - From:" + fromAgentID.ToString() + " To: " + toAgentID.ToString() + " Session:" + imSessionID.ToString() + " Message:" + + message); } } @@ -395,16 +431,16 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends msg.imSessionID = transactionID.UUID; msg.message = agentID.UUID.ToString(); msg.ParentEstateID = 0; - msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); + msg.timestamp = (uint) Util.UnixTimeSinceEpoch(); msg.RegionID = SceneAgentIn.RegionInfo.RegionID.UUID; - msg.dialog = (byte)39;// Approved friend request + msg.dialog = (byte) 39; // Approved friend request msg.Position = new sLLVector3(); - msg.offline = (byte)0; + msg.offline = (byte) 0; msg.binaryBucket = new byte[0]; // We don't really care which scene we pipe it through, it goes to the shared IM Module and/or the database SceneAgentIn.TriggerGridInstantMessage(msg, InstantMessageReceiver.IMModule); - SceneAgentIn.StoreAddFriendship(m_pendingFriendRequests[transactionID], agentID, (uint)1); + SceneAgentIn.StoreAddFriendship(m_pendingFriendRequests[transactionID], agentID, (uint) 1); m_pendingFriendRequests.Remove(transactionID); // TODO: Inform agent that the friend is online @@ -433,11 +469,11 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends msg.imSessionID = transactionID.UUID; msg.message = agentID.UUID.ToString(); msg.ParentEstateID = 0; - msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); + msg.timestamp = (uint) Util.UnixTimeSinceEpoch(); msg.RegionID = SceneAgentIn.RegionInfo.RegionID.UUID; - msg.dialog = (byte)40;// Deny friend request + msg.dialog = (byte) 40; // Deny friend request msg.Position = new sLLVector3(); - msg.offline = (byte)0; + msg.offline = (byte) 0; msg.binaryBucket = new byte[0]; SceneAgentIn.TriggerGridInstantMessage(msg, InstantMessageReceiver.IMModule); m_pendingFriendRequests.Remove(transactionID); @@ -453,52 +489,13 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends private void OnGridInstantMessage(GridInstantMessage msg) { // Trigger the above event handler - OnInstantMessage(null,new LLUUID(msg.fromAgentID), new LLUUID(msg.fromAgentSession), + OnInstantMessage(null, new LLUUID(msg.fromAgentID), new LLUUID(msg.fromAgentSession), new LLUUID(msg.toAgentID), new LLUUID(msg.imSessionID), msg.timestamp, msg.fromAgentName, msg.message, msg.dialog, msg.fromGroup, msg.offline, msg.ParentEstateID, new LLVector3(msg.Position.x, msg.Position.y, msg.Position.z), new LLUUID(msg.RegionID), msg.binaryBucket); } - #endregion - private ScenePresence GetPresenceFromAgentID(LLUUID AgentID) - { - ScenePresence returnAgent = null; - lock (m_scene) - { - ScenePresence queryagent = null; - for (int i = 0; i < m_scene.Count; i++) - { - queryagent = m_scene[i].GetScenePresence(AgentID); - if (queryagent != null) - { - if (!queryagent.IsChildAgent) - { - returnAgent = queryagent; - break; - } - } - } - } - return returnAgent; - - } - - public void PostInitialise() - { - } - - public void Close() - { - } - public string Name - { - get { return "FriendsModule"; } - } - - public bool IsSharedModule - { - get { return true; } - } + #endregion } } \ No newline at end of file diff --git a/OpenSim/Region/Environment/Modules/Avatar/Groups/GroupsModule.cs b/OpenSim/Region/Environment/Modules/Avatar/Groups/GroupsModule.cs index 4b28ad7..c4906d2 100644 --- a/OpenSim/Region/Environment/Modules/Avatar/Groups/GroupsModule.cs +++ b/OpenSim/Region/Environment/Modules/Avatar/Groups/GroupsModule.cs @@ -41,10 +41,12 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Groups { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - private List m_scene = new List(); - private Dictionary m_iclientmap = new Dictionary(); - private Dictionary m_groupmap = new Dictionary(); private Dictionary m_grouplistmap = new Dictionary(); + private Dictionary m_groupmap = new Dictionary(); + private Dictionary m_iclientmap = new Dictionary(); + private List m_scene = new List(); + + #region IRegionModule Members public void Initialise(Scene scene, IConfigSource config) { @@ -58,6 +60,42 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Groups //scene.EventManager. } + public void PostInitialise() + { + } + + public void Close() + { + m_log.Info("[GROUP]: Shutting down group module."); + lock (m_iclientmap) + { + m_iclientmap.Clear(); + } + + lock (m_groupmap) + { + m_groupmap.Clear(); + } + + lock (m_grouplistmap) + { + m_grouplistmap.Clear(); + } + GC.Collect(); + } + + public string Name + { + get { return "GroupsModule"; } + } + + public bool IsSharedModule + { + get { return true; } + } + + #endregion + private void OnNewClient(IClientAPI client) { // All friends establishment protocol goes over instant message @@ -115,7 +153,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Groups string ActiveGroupTitle = ""; bool foundUser = false; - + lock (m_iclientmap) { if (m_iclientmap.ContainsKey(remoteClient.AgentId)) @@ -139,11 +177,9 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Groups } //remoteClient.SendAgentDataUpdate(AgentID, ActiveGroupID, firstname, lastname, ActiveGroupPowers, ActiveGroupName, ActiveGroupTitle); - } } } - } private void OnInstantMessage(IClientAPI client, LLUUID fromAgentID, @@ -183,7 +219,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Groups m_iclientmap.Remove(agentID); } } - + lock (m_groupmap) { if (m_groupmap.ContainsKey(agentID)) @@ -191,7 +227,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Groups m_groupmap.Remove(agentID); } } - + lock (m_grouplistmap) { if (m_grouplistmap.ContainsKey(agentID)) @@ -201,63 +237,16 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Groups } GC.Collect(); } - - public void PostInitialise() - { - } - - public void Close() - { - m_log.Info("[GROUP]: Shutting down group module."); - lock (m_iclientmap) - { - m_iclientmap.Clear(); - } - - lock (m_groupmap) - { - m_groupmap.Clear(); - } - - lock (m_grouplistmap) - { - m_grouplistmap.Clear(); - } - GC.Collect(); - } - - public string Name - { - get { return "GroupsModule"; } - } - - public bool IsSharedModule - { - get { return true; } - } - } public class GroupData { + public string ActiveGroupTitle; public LLUUID GroupID; + public List GroupMembers; public string groupName; - public string ActiveGroupTitle; + public uint groupPowers = (uint) (GroupPowers.LandAllowLandmark | GroupPowers.LandAllowSetHome); public List GroupTitles; - public List GroupMembers; - public uint groupPowers = (uint)(GroupPowers.LandAllowLandmark | GroupPowers.LandAllowSetHome); - - public GroupPowers ActiveGroupPowers - { - set - { - groupPowers = (uint) value; - } - get - { - return (GroupPowers)groupPowers; - } - } public GroupData() { @@ -265,11 +254,17 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Groups GroupMembers = new List(); } + public GroupPowers ActiveGroupPowers + { + set { groupPowers = (uint) value; } + get { return (GroupPowers) groupPowers; } + } } public class GroupList { public List m_GroupList; + public GroupList() { m_GroupList = new List(); diff --git a/OpenSim/Region/Environment/Modules/Avatar/InstantMessage/InstantMessageModule.cs b/OpenSim/Region/Environment/Modules/Avatar/InstantMessage/InstantMessageModule.cs index 1b82837..cb58b4c 100644 --- a/OpenSim/Region/Environment/Modules/Avatar/InstantMessage/InstantMessageModule.cs +++ b/OpenSim/Region/Environment/Modules/Avatar/InstantMessage/InstantMessageModule.cs @@ -38,6 +38,8 @@ namespace OpenSim.Region.Environment.Modules.Avatar.InstantMessage { private readonly List m_scenes = new List(); + #region IRegionModule Members + public void Initialise(Scene scene, IConfigSource config) { lock (m_scenes) @@ -56,27 +58,47 @@ namespace OpenSim.Region.Environment.Modules.Avatar.InstantMessage } } + public void PostInitialise() + { + } + + public void Close() + { + } + + public string Name + { + get { return "InstantMessageModule"; } + } + + public bool IsSharedModule + { + get { return true; } + } + + #endregion + private void OnNewClient(IClientAPI client) { client.OnInstantMessage += OnInstantMessage; } - private void OnInstantMessage(IClientAPI client,LLUUID fromAgentID, + private void OnInstantMessage(IClientAPI client, LLUUID fromAgentID, LLUUID fromAgentSession, LLUUID toAgentID, LLUUID imSessionID, uint timestamp, string fromAgentName, - string message, byte dialog, bool fromGroup, byte offline, - uint ParentEstateID, LLVector3 Position, LLUUID RegionID, + string message, byte dialog, bool fromGroup, byte offline, + uint ParentEstateID, LLVector3 Position, LLUUID RegionID, byte[] binaryBucket) { - bool dialogHandledElsewhere + bool dialogHandledElsewhere = ((dialog == 38) || (dialog == 39) || (dialog == 40) - || dialog == (byte)InstantMessageDialog.InventoryOffered - || dialog == (byte)InstantMessageDialog.InventoryAccepted - || dialog == (byte)InstantMessageDialog.InventoryDeclined); + || dialog == (byte) InstantMessageDialog.InventoryOffered + || dialog == (byte) InstantMessageDialog.InventoryAccepted + || dialog == (byte) InstantMessageDialog.InventoryDeclined); // IM dialogs need to be pre-processed and have their sessionID filled by the server // so the sim can match the transaction on the return packet. - + // Don't send a Friend Dialog IM with a LLUUID.Zero session. if (!(dialogHandledElsewhere && imSessionID == LLUUID.Zero)) { @@ -86,7 +108,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.InstantMessage if (scene.Entities.ContainsKey(toAgentID) && scene.Entities[toAgentID] is ScenePresence) { // Local message - ScenePresence user = (ScenePresence)scene.Entities[toAgentID]; + ScenePresence user = (ScenePresence) scene.Entities[toAgentID]; if (!user.IsChildAgent) { user.ControllingClient.SendInstantMessage(fromAgentID, fromAgentSession, message, @@ -104,54 +126,33 @@ namespace OpenSim.Region.Environment.Modules.Avatar.InstantMessage if (scene.Entities.ContainsKey(toAgentID) && scene.Entities[toAgentID] is ScenePresence) { // Local message - ScenePresence user = (ScenePresence)scene.Entities[toAgentID]; - + ScenePresence user = (ScenePresence) scene.Entities[toAgentID]; + user.ControllingClient.SendInstantMessage(fromAgentID, fromAgentSession, message, toAgentID, imSessionID, fromAgentName, dialog, timestamp); // Message sent return; - } } - } // Still here, try send via Grid // TODO } - + // Trusty OSG1 called method. This method also gets called from the FriendsModule // Turns out the sim has to send an instant message to the user to get it to show an accepted friend. private void OnGridInstantMessage(GridInstantMessage msg) { // Trigger the above event handler - OnInstantMessage(null,new LLUUID(msg.fromAgentID), new LLUUID(msg.fromAgentSession), - new LLUUID(msg.toAgentID), new LLUUID(msg.imSessionID), msg.timestamp, msg.fromAgentName, - msg.message, msg.dialog, msg.fromGroup, msg.offline, msg.ParentEstateID, - new LLVector3(msg.Position.x,msg.Position.y,msg.Position.z), new LLUUID(msg.RegionID), + OnInstantMessage(null, new LLUUID(msg.fromAgentID), new LLUUID(msg.fromAgentSession), + new LLUUID(msg.toAgentID), new LLUUID(msg.imSessionID), msg.timestamp, msg.fromAgentName, + msg.message, msg.dialog, msg.fromGroup, msg.offline, msg.ParentEstateID, + new LLVector3(msg.Position.x, msg.Position.y, msg.Position.z), new LLUUID(msg.RegionID), msg.binaryBucket); - - } - - public void PostInitialise() - { - } - - public void Close() - { - } - - public string Name - { - get { return "InstantMessageModule"; } - } - - public bool IsSharedModule - { - get { return true; } } } } \ No newline at end of file diff --git a/OpenSim/Region/Environment/Modules/Avatar/Inventory/InventoryModule.cs b/OpenSim/Region/Environment/Modules/Avatar/Inventory/InventoryModule.cs index 42c6238..2844450 100644 --- a/OpenSim/Region/Environment/Modules/Avatar/Inventory/InventoryModule.cs +++ b/OpenSim/Region/Environment/Modules/Avatar/Inventory/InventoryModule.cs @@ -38,11 +38,9 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Inventory { public class InventoryModule : IRegionModule { - private static readonly ILog m_log - = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private Scene m_scene; - + private static readonly ILog m_log + = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + /// /// We need to keep track of the pending item offers between clients since the itemId offered only /// occurs in the initial offer message, not the accept message. So this dictionary links @@ -50,10 +48,14 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Inventory /// private IDictionary m_pendingOffers = new Dictionary(); + private Scene m_scene; + + #region IRegionModule Members + public void Initialise(Scene scene, IConfigSource config) - { + { m_scene = scene; - scene.EventManager.OnNewClient += OnNewClient; + scene.EventManager.OnNewClient += OnNewClient; } public void PostInitialise() @@ -73,59 +75,61 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Inventory { get { return false; } } - + + #endregion + private void OnNewClient(IClientAPI client) { // Inventory giving is conducted via instant message client.OnInstantMessage += OnInstantMessage; } - + private void OnInstantMessage(IClientAPI client, LLUUID fromAgentID, LLUUID fromAgentSession, LLUUID toAgentID, LLUUID imSessionID, uint timestamp, string fromAgentName, - string message, byte dialog, bool fromGroup, byte offline, - uint ParentEstateID, LLVector3 Position, LLUUID RegionID, + string message, byte dialog, bool fromGroup, byte offline, + uint ParentEstateID, LLVector3 Position, LLUUID RegionID, byte[] binaryBucket) { - if (dialog == (byte)InstantMessageDialog.InventoryOffered) + if (dialog == (byte) InstantMessageDialog.InventoryOffered) { m_log.DebugFormat( - "[AGENT INVENTORY]: Routing inventory offering message from {0}, {1} to {2}", + "[AGENT INVENTORY]: Routing inventory offering message from {0}, {1} to {2}", client.AgentId, client.Name, toAgentID); - + if (m_scene.Entities.ContainsKey(toAgentID) && m_scene.Entities[toAgentID] is ScenePresence) { - ScenePresence user = (ScenePresence)m_scene.Entities[toAgentID]; - + ScenePresence user = (ScenePresence) m_scene.Entities[toAgentID]; + if (!user.IsChildAgent) { //byte[] rawId = new byte[16]; - + // First byte of the array is probably the item type // Next 16 bytes are the UUID //Array.Copy(binaryBucket, 1, rawId, 0, 16); - + //LLUUID itemId = new LLUUID(new Guid(rawId)); LLUUID itemId = new LLUUID(binaryBucket, 1); - + m_log.DebugFormat( "[AGENT INVENTORY]: ItemId for giving is {0}", itemId); - + m_pendingOffers[imSessionID] = itemId; - + user.ControllingClient.SendInstantMessage( - fromAgentID, fromAgentSession, message, toAgentID, imSessionID, fromAgentName, + fromAgentID, fromAgentSession, message, toAgentID, imSessionID, fromAgentName, dialog, timestamp, binaryBucket); - + return; } else { m_log.WarnFormat( - "[AGENT INVENTORY]: Agent {0} targeted for inventory give by {1}, {2} of {3} was a child agent!", + "[AGENT INVENTORY]: Agent {0} targeted for inventory give by {1}, {2} of {3} was a child agent!", toAgentID, client.AgentId, client.Name, message); } - } + } else { m_log.WarnFormat( @@ -133,84 +137,84 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Inventory toAgentID, client.AgentId, client.Name, message); } } - else if (dialog == (byte)InstantMessageDialog.InventoryAccepted) + else if (dialog == (byte) InstantMessageDialog.InventoryAccepted) { m_log.DebugFormat( - "[AGENT INVENTORY]: Routing inventory accepted message from {0}, {1} to {2}", + "[AGENT INVENTORY]: Routing inventory accepted message from {0}, {1} to {2}", client.AgentId, client.Name, toAgentID); - + if (m_scene.Entities.ContainsKey(toAgentID) && m_scene.Entities[toAgentID] is ScenePresence) { - ScenePresence user = (ScenePresence)m_scene.Entities[toAgentID]; - + ScenePresence user = (ScenePresence) m_scene.Entities[toAgentID]; + if (!user.IsChildAgent) { user.ControllingClient.SendInstantMessage( - fromAgentID, fromAgentSession, message, toAgentID, imSessionID, fromAgentName, + fromAgentID, fromAgentSession, message, toAgentID, imSessionID, fromAgentName, dialog, timestamp, binaryBucket); - + if (m_pendingOffers.ContainsKey(imSessionID)) - { + { m_log.DebugFormat( "[AGENT INVENTORY]: Accepted item id {0}", m_pendingOffers[imSessionID]); - + // Since the message originates from the accepting client, the toAgentID is // the agent giving the item. m_scene.GiveInventoryItem(client, toAgentID, m_pendingOffers[imSessionID]); - + m_pendingOffers.Remove(imSessionID); } else { m_log.ErrorFormat( - "[AGENT INVENTORY]: Could not find an item associated with session id {0} to accept", + "[AGENT INVENTORY]: Could not find an item associated with session id {0} to accept", imSessionID); } - + return; } else { m_log.WarnFormat( - "[AGENT INVENTORY]: Agent {0} targeted for inventory give by {1}, {2} of {3} was a child agent!", + "[AGENT INVENTORY]: Agent {0} targeted for inventory give by {1}, {2} of {3} was a child agent!", toAgentID, client.AgentId, client.Name, message); } - } + } else { m_log.WarnFormat( "[AGENT INVENTORY]: Could not find agent {0} for user {1}, {2} to give {3}", toAgentID, client.AgentId, client.Name, message); - } + } } - else if (dialog == (byte)InstantMessageDialog.InventoryDeclined) + else if (dialog == (byte) InstantMessageDialog.InventoryDeclined) { if (m_scene.Entities.ContainsKey(toAgentID) && m_scene.Entities[toAgentID] is ScenePresence) { - ScenePresence user = (ScenePresence)m_scene.Entities[toAgentID]; - + ScenePresence user = (ScenePresence) m_scene.Entities[toAgentID]; + if (!user.IsChildAgent) { user.ControllingClient.SendInstantMessage( - fromAgentID, fromAgentSession, message, toAgentID, imSessionID, fromAgentName, + fromAgentID, fromAgentSession, message, toAgentID, imSessionID, fromAgentName, dialog, timestamp, binaryBucket); - + if (m_pendingOffers.ContainsKey(imSessionID)) - { + { m_log.DebugFormat( "[AGENT INVENTORY]: Declined item id {0}", m_pendingOffers[imSessionID]); - + m_pendingOffers.Remove(imSessionID); } else { m_log.ErrorFormat( - "[AGENT INVENTORY]: Could not find an item associated with session id {0} to decline", + "[AGENT INVENTORY]: Could not find an item associated with session id {0} to decline", imSessionID); - } + } } } - } + } } } } \ No newline at end of file diff --git a/OpenSim/Region/Environment/Modules/Avatar/Profiles/AvatarProfilesModule.cs b/OpenSim/Region/Environment/Modules/Avatar/Profiles/AvatarProfilesModule.cs index f8b14d3..1955d2a 100644 --- a/OpenSim/Region/Environment/Modules/Avatar/Profiles/AvatarProfilesModule.cs +++ b/OpenSim/Region/Environment/Modules/Avatar/Profiles/AvatarProfilesModule.cs @@ -45,6 +45,8 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Profiles { } + #region IRegionModule Members + public void Initialise(Scene scene, IConfigSource config) { m_scene = scene; @@ -69,6 +71,8 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Profiles get { return false; } } + #endregion + public void NewClient(IClientAPI client) { client.OnRequestAvatarProperties += RequestAvatarProperty; @@ -107,7 +111,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Profiles public void UpdateAvatarProperties(IClientAPI remoteClient, UserProfileData newProfile) { UserProfileData Profile = m_scene.CommsManager.UserService.GetUserProfile(newProfile.ID); - + // if it's the profile of the user requesting the update, then we change only a few things. if (remoteClient.AgentId.CompareTo(Profile.ID) == 0) { diff --git a/OpenSim/Region/Environment/Modules/Avatar/Voice/AsterixVoice/AsteriskVoiceModule.cs b/OpenSim/Region/Environment/Modules/Avatar/Voice/AsterixVoice/AsteriskVoiceModule.cs index 0d7de78..44d67e6 100644 --- a/OpenSim/Region/Environment/Modules/Avatar/Voice/AsterixVoice/AsteriskVoiceModule.cs +++ b/OpenSim/Region/Environment/Modules/Avatar/Voice/AsterixVoice/AsteriskVoiceModule.cs @@ -44,40 +44,43 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.AsterixVoice { public class AsteriskVoiceModule : IRegionModule { - private static readonly ILog m_log = + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - private Scene m_scene; - private IConfig m_config; + private static readonly string m_parcelVoiceInfoRequestPath = "0007/"; + private static readonly string m_provisionVoiceAccountRequestPath = "0008/"; + private string m_asterisk; private string m_asterisk_password; private string m_asterisk_salt; private int m_asterisk_timeout; - private string m_sipDomain; private string m_confDomain; + private IConfig m_config; + private Scene m_scene; + private string m_sipDomain; - private static readonly string m_parcelVoiceInfoRequestPath = "0007/"; - private static readonly string m_provisionVoiceAccountRequestPath = "0008/"; + #region IRegionModule Members public void Initialise(Scene scene, IConfigSource config) { m_scene = scene; m_config = config.Configs["AsteriskVoice"]; - if (null == m_config) + if (null == m_config) { m_log.Info("[ASTERISKVOICE] no config found, plugin disabled"); return; } - if (!m_config.GetBoolean("enabled", false)) + if (!m_config.GetBoolean("enabled", false)) { m_log.Info("[ASTERISKVOICE] plugin disabled by configuration"); return; } m_log.Info("[ASTERISKVOICE] plugin enabled"); - try { + try + { m_sipDomain = m_config.GetString("sip_domain", String.Empty); m_log.InfoFormat("[ASTERISKVOICE] using SIP domain {0}", m_sipDomain); @@ -91,17 +94,17 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.AsterixVoice if (String.IsNullOrEmpty(m_asterisk)) throw new Exception("missing asterisk_frontend config parameter"); if (String.IsNullOrEmpty(m_asterisk_password)) throw new Exception("missing asterisk_password config parameter"); m_log.InfoFormat("[ASTERISKVOICE] using asterisk front end {0}", m_asterisk); - + scene.EventManager.OnRegisterCaps += OnRegisterCaps; } - catch (Exception e) + catch (Exception e) { m_log.ErrorFormat("[ASTERISKVOICE] plugin initialization failed: {0}", e.Message); m_log.DebugFormat("[ASTERISKVOICE] plugin initialization failed: {0}", e.ToString()); return; } } - + public void PostInitialise() { } @@ -120,15 +123,17 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.AsterixVoice get { return false; } } - public void OnRegisterCaps(LLUUID agentID, Caps caps) + #endregion + + public void OnRegisterCaps(LLUUID agentID, Caps caps) { m_log.DebugFormat("[ASTERISKVOICE] OnRegisterCaps: agentID {0} caps {1}", agentID, caps); - string capsBase = "/CAPS/" + caps.CapsObjectPath; + string capsBase = "/CAPS/" + caps.CapsObjectPath; caps.RegisterHandler("ParcelVoiceInfoRequest", - new RestStreamHandler("POST", capsBase + m_parcelVoiceInfoRequestPath, - delegate(string request, string path, string param) + new RestStreamHandler("POST", capsBase + m_parcelVoiceInfoRequestPath, + delegate(string request, string path, string param) { - return ParcelVoiceInfoRequest(request, path, param, + return ParcelVoiceInfoRequest(request, path, param, agentID, caps); })); caps.RegisterHandler("ProvisionVoiceAccountRequest", @@ -139,7 +144,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.AsterixVoice agentID, caps); })); } - + /// /// Callback for a client request for ParcelVoiceInfo /// @@ -149,30 +154,30 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.AsterixVoice /// /// /// - public string ParcelVoiceInfoRequest(string request, string path, string param, - LLUUID agentID, Caps caps) + public string ParcelVoiceInfoRequest(string request, string path, string param, + LLUUID agentID, Caps caps) { // we need to do: // - send channel_uri: as "sip:regionID@m_sipDomain" try { - m_log.DebugFormat("[ASTERISKVOICE][PARCELVOICE]: request: {0}, path: {1}, param: {2}", + m_log.DebugFormat("[ASTERISKVOICE][PARCELVOICE]: request: {0}, path: {1}, param: {2}", request, path, param); // setup response to client Hashtable creds = new Hashtable(); - creds["channel_uri"] = String.Format("sip:{0}@{1}", + creds["channel_uri"] = String.Format("sip:{0}@{1}", m_scene.RegionInfo.RegionID, m_sipDomain); - + string regionName = m_scene.RegionInfo.RegionName; ScenePresence avatar = m_scene.GetScenePresence(agentID); if (null == m_scene.LandChannel) throw new Exception("land data not yet available"); LandData land = m_scene.GetLandData(avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y); - - LLSDParcelVoiceInfoResponse parcelVoiceInfo = + + LLSDParcelVoiceInfoResponse parcelVoiceInfo = new LLSDParcelVoiceInfoResponse(regionName, land.localID, creds); - + string r = LLSDHelpers.SerialiseLLSDReply(parcelVoiceInfo); @@ -183,17 +188,17 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.AsterixVoice if (!String.IsNullOrEmpty(m_confDomain)) { requestData["region"] += String.Format("@{0}", m_confDomain); - } + } ArrayList SendParams = new ArrayList(); SendParams.Add(requestData); XmlRpcRequest updateAccountRequest = new XmlRpcRequest("region_update", SendParams); XmlRpcResponse updateAccountResponse = updateAccountRequest.Send(m_asterisk, m_asterisk_timeout); - Hashtable responseData = (Hashtable)updateAccountResponse.Value; - + Hashtable responseData = (Hashtable) updateAccountResponse.Value; + if (!responseData.ContainsKey("success")) throw new Exception("region_update call failed"); - bool success = Convert.ToBoolean((string)responseData["success"]); + bool success = Convert.ToBoolean((string) responseData["success"]); if (!success) throw new Exception("region_update failed"); @@ -218,8 +223,8 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.AsterixVoice /// /// /// - public string ProvisionVoiceAccountRequest(string request, string path, string param, - LLUUID agentID, Caps caps) + public string ProvisionVoiceAccountRequest(string request, string path, string param, + LLUUID agentID, Caps caps) { // we need to // - get user data from UserProfileCacheService @@ -232,7 +237,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.AsterixVoice // send account details back to client try { - m_log.DebugFormat("[ASTERISKVOICE][PROVISIONVOICE]: request: {0}, path: {1}, param: {2}", + m_log.DebugFormat("[ASTERISKVOICE][PROVISIONVOICE]: request: {0}, path: {1}, param: {2}", request, path, param); // get user data & prepare voice account response @@ -244,7 +249,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.AsterixVoice // we generate a nonce everytime string voicePassword = "$1$" + Util.Md5Hash(DateTime.UtcNow.ToLongTimeString() + m_asterisk_salt); - LLSDVoiceAccountResponse voiceAccountResponse = + LLSDVoiceAccountResponse voiceAccountResponse = new LLSDVoiceAccountResponse(voiceUser, voicePassword); string r = LLSDHelpers.SerialiseLLSDReply(voiceAccountResponse); m_log.DebugFormat("[CAPS][PROVISIONVOICE]: {0}", r); @@ -257,18 +262,18 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.AsterixVoice if (!String.IsNullOrEmpty(m_sipDomain)) { requestData["username"] += String.Format("@{0}", m_sipDomain); - } + } requestData["password"] = voicePassword; ArrayList SendParams = new ArrayList(); SendParams.Add(requestData); XmlRpcRequest updateAccountRequest = new XmlRpcRequest("account_update", SendParams); XmlRpcResponse updateAccountResponse = updateAccountRequest.Send(m_asterisk, m_asterisk_timeout); - Hashtable responseData = (Hashtable)updateAccountResponse.Value; - + Hashtable responseData = (Hashtable) updateAccountResponse.Value; + if (!responseData.ContainsKey("success")) throw new Exception("account_update call failed"); - bool success = Convert.ToBoolean((string)responseData["success"]); + bool success = Convert.ToBoolean((string) responseData["success"]); if (!success) throw new Exception("account_update failed"); return r; diff --git a/OpenSim/Region/Environment/Modules/Avatar/Voice/SIPVoice/SIPVoiceModule.cs b/OpenSim/Region/Environment/Modules/Avatar/Voice/SIPVoice/SIPVoiceModule.cs index 8b7c3d0..8d9ba6f 100644 --- a/OpenSim/Region/Environment/Modules/Avatar/Voice/SIPVoice/SIPVoiceModule.cs +++ b/OpenSim/Region/Environment/Modules/Avatar/Voice/SIPVoice/SIPVoiceModule.cs @@ -43,22 +43,23 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.SIPVoice { public class SIPVoiceModule : IRegionModule { - private static readonly ILog m_log = + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - private Scene m_scene; + private static readonly string m_parcelVoiceInfoRequestPath = "0007/"; + private static readonly string m_provisionVoiceAccountRequestPath = "0008/"; private IConfig m_config; + private Scene m_scene; private string m_sipDomain; - private static readonly string m_parcelVoiceInfoRequestPath = "0007/"; - private static readonly string m_provisionVoiceAccountRequestPath = "0008/"; + #region IRegionModule Members public void Initialise(Scene scene, IConfigSource config) { m_scene = scene; m_config = config.Configs["Voice"]; - if (null == m_config || !m_config.GetBoolean("enabled", false)) + if (null == m_config || !m_config.GetBoolean("enabled", false)) { m_log.Info("[VOICE] plugin disabled"); return; @@ -95,15 +96,17 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.SIPVoice get { return false; } } - public void OnRegisterCaps(LLUUID agentID, Caps caps) + #endregion + + public void OnRegisterCaps(LLUUID agentID, Caps caps) { m_log.DebugFormat("[VOICE] OnRegisterCaps: agentID {0} caps {1}", agentID, caps); - string capsBase = "/CAPS/" + caps.CapsObjectPath; + string capsBase = "/CAPS/" + caps.CapsObjectPath; caps.RegisterHandler("ParcelVoiceInfoRequest", - new RestStreamHandler("POST", capsBase + m_parcelVoiceInfoRequestPath, - delegate(string request, string path, string param) + new RestStreamHandler("POST", capsBase + m_parcelVoiceInfoRequestPath, + delegate(string request, string path, string param) { - return ParcelVoiceInfoRequest(request, path, param, + return ParcelVoiceInfoRequest(request, path, param, agentID, caps); })); caps.RegisterHandler("ProvisionVoiceAccountRequest", @@ -114,7 +117,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.SIPVoice agentID, caps); })); } - + /// /// Callback for a client request for ParcelVoiceInfo /// @@ -124,8 +127,8 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.SIPVoice /// /// /// - public string ParcelVoiceInfoRequest(string request, string path, string param, - LLUUID agentID, Caps caps) + public string ParcelVoiceInfoRequest(string request, string path, string param, + LLUUID agentID, Caps caps) { try { @@ -135,15 +138,15 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.SIPVoice Hashtable creds = new Hashtable(); creds["channel_uri"] = String.Format("sip:{0}@{1}", agentID, m_sipDomain); - + string regionName = m_scene.RegionInfo.RegionName; ScenePresence avatar = m_scene.GetScenePresence(agentID); if (null == m_scene.LandChannel) throw new Exception("land data not yet available"); LandData land = m_scene.GetLandData(avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y); - - LLSDParcelVoiceInfoResponse parcelVoiceInfo = + + LLSDParcelVoiceInfoResponse parcelVoiceInfo = new LLSDParcelVoiceInfoResponse(regionName, land.localID, creds); - + string r = LLSDHelpers.SerialiseLLSDReply(parcelVoiceInfo); m_log.DebugFormat("[VOICE][PARCELVOICE]: {0}", r); @@ -153,7 +156,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.SIPVoice { m_log.ErrorFormat("[CAPS]: {0}, try again later", e.ToString()); } - + return null; } @@ -166,12 +169,12 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.SIPVoice /// /// /// - public string ProvisionVoiceAccountRequest(string request, string path, string param, - LLUUID agentID, Caps caps) + public string ProvisionVoiceAccountRequest(string request, string path, string param, + LLUUID agentID, Caps caps) { try { - m_log.DebugFormat("[VOICE][PROVISIONVOICE]: request: {0}, path: {1}, param: {2}", + m_log.DebugFormat("[VOICE][PROVISIONVOICE]: request: {0}, path: {1}, param: {2}", request, path, param); string voiceUser = "x" + Convert.ToBase64String(agentID.GetBytes()); @@ -180,7 +183,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.SIPVoice CachedUserInfo userInfo = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(agentID); if (null == userInfo) throw new Exception("cannot get user details"); - LLSDVoiceAccountResponse voiceAccountResponse = + LLSDVoiceAccountResponse voiceAccountResponse = new LLSDVoiceAccountResponse(voiceUser, "$1$" + userInfo.UserProfile.PasswordHash); string r = LLSDHelpers.SerialiseLLSDReply(voiceAccountResponse); m_log.DebugFormat("[CAPS][PROVISIONVOICE]: {0}", r); -- cgit v1.1