From 180be7de07014aa33bc6066f12a0819b731c1c9d Mon Sep 17 00:00:00 2001 From: Dr Scofield Date: Tue, 10 Feb 2009 13:10:57 +0000 Subject: this is step 2 of 2 of the OpenSim.Region.Environment refactor. NOTHING has been deleted or moved off to forge at this point. what has happened is that OpenSim.Region.Environment.Modules has been split in two: - OpenSim.Region.CoreModules: all those modules that are either directly or indirectly referenced from other OpenSim packages, or that provide functionality that the OpenSim developer community considers core functionality: CoreModules/Agent/AssetTransaction CoreModules/Agent/Capabilities CoreModules/Agent/TextureDownload CoreModules/Agent/TextureSender CoreModules/Agent/TextureSender/Tests CoreModules/Agent/Xfer CoreModules/Avatar/AvatarFactory CoreModules/Avatar/Chat/ChatModule CoreModules/Avatar/Combat CoreModules/Avatar/Currency/SampleMoney CoreModules/Avatar/Dialog CoreModules/Avatar/Friends CoreModules/Avatar/Gestures CoreModules/Avatar/Groups CoreModules/Avatar/InstantMessage CoreModules/Avatar/Inventory CoreModules/Avatar/Inventory/Archiver CoreModules/Avatar/Inventory/Transfer CoreModules/Avatar/Lure CoreModules/Avatar/ObjectCaps CoreModules/Avatar/Profiles CoreModules/Communications/Local CoreModules/Communications/REST CoreModules/Framework/EventQueue CoreModules/Framework/InterfaceCommander CoreModules/Hypergrid CoreModules/InterGrid CoreModules/Scripting/DynamicTexture CoreModules/Scripting/EMailModules CoreModules/Scripting/HttpRequest CoreModules/Scripting/LoadImageURL CoreModules/Scripting/VectorRender CoreModules/Scripting/WorldComm CoreModules/Scripting/XMLRPC CoreModules/World/Archiver CoreModules/World/Archiver/Tests CoreModules/World/Estate CoreModules/World/Land CoreModules/World/Permissions CoreModules/World/Serialiser CoreModules/World/Sound CoreModules/World/Sun CoreModules/World/Terrain CoreModules/World/Terrain/DefaultEffects CoreModules/World/Terrain/DefaultEffects/bin CoreModules/World/Terrain/DefaultEffects/bin/Debug CoreModules/World/Terrain/Effects CoreModules/World/Terrain/FileLoaders CoreModules/World/Terrain/FloodBrushes CoreModules/World/Terrain/PaintBrushes CoreModules/World/Terrain/Tests CoreModules/World/Vegetation CoreModules/World/Wind CoreModules/World/WorldMap - OpenSim.Region.OptionalModules: all those modules that are not core modules: OptionalModules/Avatar/Chat/IRC-stuff OptionalModules/Avatar/Concierge OptionalModules/Avatar/Voice/AsterixVoice OptionalModules/Avatar/Voice/SIPVoice OptionalModules/ContentManagementSystem OptionalModules/Grid/Interregion OptionalModules/Python OptionalModules/SvnSerialiser OptionalModules/World/NPC OptionalModules/World/TreePopulator --- .../Avatar/AvatarFactory/AvatarFactoryModule.cs | 232 --- .../Modules/Avatar/Chat/ChannelState.cs | 628 -------- .../Environment/Modules/Avatar/Chat/ChatModule.cs | 287 ---- .../Modules/Avatar/Chat/IRCBridgeModule.cs | 219 --- .../Modules/Avatar/Chat/IRCConnector.cs | 887 ----------- .../Environment/Modules/Avatar/Chat/RegionState.cs | 424 ------ .../Modules/Avatar/Combat/CombatModule.cs | 154 -- .../Modules/Avatar/Concierge/ConciergeModule.cs | 604 -------- .../Modules/Avatar/Concierge/ConciergeServer.py | 130 -- .../Currency/SampleMoney/SampleMoneyModule.cs | 1605 -------------------- .../Modules/Avatar/Dialog/DialogModule.cs | 143 -- .../Modules/Avatar/Friends/FriendsModule.cs | 1003 ------------ .../Modules/Avatar/Gestures/GesturesModule.cs | 104 -- .../Modules/Avatar/Groups/GroupsModule.cs | 223 --- .../Avatar/InstantMessage/InstantMessageModule.cs | 170 --- .../Avatar/InstantMessage/MessageTransferModule.cs | 655 -------- .../Avatar/InstantMessage/PresenceModule.cs | 426 ------ .../Archiver/InventoryArchiveReadRequest.cs | 279 ---- .../Archiver/InventoryArchiveWriteRequest.cs | 247 --- .../Inventory/Transfer/InventoryTransferModule.cs | 389 ----- .../Environment/Modules/Avatar/Lure/LureModule.cs | 176 --- .../Modules/Avatar/ObjectCaps/ObjectAdd.cs | 368 ----- .../Avatar/Profiles/AvatarProfilesModule.cs | 145 -- .../Voice/AsterixVoice/AsteriskVoiceModule.cs | 292 ---- .../Avatar/Voice/SIPVoice/SIPVoiceModule.cs | 202 --- 25 files changed, 9992 deletions(-) delete mode 100644 OpenSim/Region/Environment/Modules/Avatar/AvatarFactory/AvatarFactoryModule.cs delete mode 100644 OpenSim/Region/Environment/Modules/Avatar/Chat/ChannelState.cs delete mode 100644 OpenSim/Region/Environment/Modules/Avatar/Chat/ChatModule.cs delete mode 100644 OpenSim/Region/Environment/Modules/Avatar/Chat/IRCBridgeModule.cs delete mode 100644 OpenSim/Region/Environment/Modules/Avatar/Chat/IRCConnector.cs delete mode 100644 OpenSim/Region/Environment/Modules/Avatar/Chat/RegionState.cs delete mode 100644 OpenSim/Region/Environment/Modules/Avatar/Combat/CombatModule.cs delete mode 100644 OpenSim/Region/Environment/Modules/Avatar/Concierge/ConciergeModule.cs delete mode 100755 OpenSim/Region/Environment/Modules/Avatar/Concierge/ConciergeServer.py delete mode 100644 OpenSim/Region/Environment/Modules/Avatar/Currency/SampleMoney/SampleMoneyModule.cs delete mode 100644 OpenSim/Region/Environment/Modules/Avatar/Dialog/DialogModule.cs delete mode 100644 OpenSim/Region/Environment/Modules/Avatar/Friends/FriendsModule.cs delete mode 100644 OpenSim/Region/Environment/Modules/Avatar/Gestures/GesturesModule.cs delete mode 100644 OpenSim/Region/Environment/Modules/Avatar/Groups/GroupsModule.cs delete mode 100644 OpenSim/Region/Environment/Modules/Avatar/InstantMessage/InstantMessageModule.cs delete mode 100644 OpenSim/Region/Environment/Modules/Avatar/InstantMessage/MessageTransferModule.cs delete mode 100644 OpenSim/Region/Environment/Modules/Avatar/InstantMessage/PresenceModule.cs delete mode 100644 OpenSim/Region/Environment/Modules/Avatar/Inventory/Archiver/InventoryArchiveReadRequest.cs delete mode 100644 OpenSim/Region/Environment/Modules/Avatar/Inventory/Archiver/InventoryArchiveWriteRequest.cs delete mode 100644 OpenSim/Region/Environment/Modules/Avatar/Inventory/Transfer/InventoryTransferModule.cs delete mode 100644 OpenSim/Region/Environment/Modules/Avatar/Lure/LureModule.cs delete mode 100644 OpenSim/Region/Environment/Modules/Avatar/ObjectCaps/ObjectAdd.cs delete mode 100644 OpenSim/Region/Environment/Modules/Avatar/Profiles/AvatarProfilesModule.cs delete mode 100644 OpenSim/Region/Environment/Modules/Avatar/Voice/AsterixVoice/AsteriskVoiceModule.cs delete mode 100644 OpenSim/Region/Environment/Modules/Avatar/Voice/SIPVoice/SIPVoiceModule.cs (limited to 'OpenSim/Region/Environment/Modules/Avatar') diff --git a/OpenSim/Region/Environment/Modules/Avatar/AvatarFactory/AvatarFactoryModule.cs b/OpenSim/Region/Environment/Modules/Avatar/AvatarFactory/AvatarFactoryModule.cs deleted file mode 100644 index 1ac0807..0000000 --- a/OpenSim/Region/Environment/Modules/Avatar/AvatarFactory/AvatarFactoryModule.cs +++ /dev/null @@ -1,232 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using System.Reflection; - -using System.Threading; -using OpenMetaverse; -using log4net; -using Nini.Config; -using OpenSim.Framework; -using OpenSim.Framework.Communications.Cache; -using OpenSim.Region.Framework.Interfaces; -using OpenSim.Region.Framework.Scenes; - -namespace OpenSim.Region.Environment.Modules.Avatar.AvatarFactory -{ - public class AvatarFactoryModule : IAvatarFactory, IRegionModule - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - private Scene m_scene = null; - private static readonly AvatarAppearance def = new AvatarAppearance(); - - public bool TryGetAvatarAppearance(UUID avatarId, out AvatarAppearance appearance) - { - CachedUserInfo profile = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(avatarId); - //if ((profile != null) && (profile.RootFolder != null)) - if (profile != null) - { - appearance = m_scene.CommsManager.AvatarService.GetUserAppearance(avatarId); - if (appearance != null) - { - //SetAppearanceAssets(profile, ref appearance); - //m_log.DebugFormat("[APPEARANCE]: Found : {0}", appearance.ToString()); - return true; - } - } - - appearance = CreateDefault(avatarId); - m_log.ErrorFormat("[APPEARANCE]: Appearance not found for {0}, creating default", avatarId); - return false; - } - - private AvatarAppearance CreateDefault(UUID avatarId) - { - AvatarAppearance appearance = null; - AvatarWearable[] wearables; - byte[] visualParams; - GetDefaultAvatarAppearance(out wearables, out visualParams); - appearance = new AvatarAppearance(avatarId, wearables, visualParams); - - return appearance; - } - - public void Initialise(Scene scene, IConfigSource source) - { - scene.RegisterModuleInterface(this); - scene.EventManager.OnNewClient += NewClient; - - if (m_scene == null) - { - m_scene = scene; - } - - } - - public void PostInitialise() - { - } - - public void Close() - { - } - - public string Name - { - get { return "Default Avatar Factory"; } - } - - public bool IsSharedModule - { - get { return false; } - } - - public void NewClient(IClientAPI client) - { - client.OnAvatarNowWearing += AvatarIsWearing; - } - - public void RemoveClient(IClientAPI client) - { - // client.OnAvatarNowWearing -= AvatarIsWearing; - } - - - public void SetAppearanceAssets(CachedUserInfo profile, ref AvatarAppearance appearance) - { - if (profile.RootFolder != null) - { - for (int i = 0; i < 13; i++) - { - if (appearance.Wearables[i].ItemID == UUID.Zero) - { - appearance.Wearables[i].AssetID = UUID.Zero; - } - else - { - InventoryItemBase baseItem = profile.RootFolder.FindItem(appearance.Wearables[i].ItemID); - - if (baseItem != null) - { - appearance.Wearables[i].AssetID = baseItem.AssetID; - } - else - { - m_log.ErrorFormat("[APPEARANCE]: Can't find inventory item {0}, setting to default", appearance.Wearables[i].ItemID); - appearance.Wearables[i].AssetID = def.Wearables[i].AssetID; - } - } - } - } - else - { - m_log.Error("[APPEARANCE]: you have no inventory, appearance stuff isn't going to work"); - } - } - - /// - /// Update what the avatar is wearing using an item from their inventory. - /// - /// - /// - public void AvatarIsWearing(Object sender, AvatarWearingArgs e) - { - IClientAPI clientView = (IClientAPI)sender; - ScenePresence avatar = m_scene.GetScenePresence(clientView.AgentId); - - if (avatar == null) - { - m_log.Error("[APPEARANCE]: Avatar is child agent, ignoring AvatarIsWearing event"); - return; - } - - CachedUserInfo profile = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(clientView.AgentId); - - AvatarAppearance avatAppearance = null; - if (!TryGetAvatarAppearance(clientView.AgentId, out avatAppearance)) - { - m_log.Warn("[APPEARANCE]: We didn't seem to find the appearance, falling back to ScenePresence"); - avatAppearance = avatar.Appearance; - } - - //m_log.DebugFormat("[APPEARANCE]: Received wearables for {0}", clientView.Name); - - if (profile != null) - { - if (profile.RootFolder != null) - { - foreach (AvatarWearingArgs.Wearable wear in e.NowWearing) - { - if (wear.Type < 13) - { - avatAppearance.Wearables[wear.Type].ItemID = wear.ItemID; - } - } - - SetAppearanceAssets(profile, ref avatAppearance); - - m_scene.CommsManager.AvatarService.UpdateUserAppearance(clientView.AgentId, avatAppearance); - avatar.Appearance = avatAppearance; - } - else - { - m_log.WarnFormat( - "[APPEARANCE]: Inventory has not yet been received for {0}, cannot set wearables", - clientView.Name); - } - } - else - { - m_log.WarnFormat("[APPEARANCE]: Cannot set wearables for {0}, no user profile found", clientView.Name); - } - } - - public static void GetDefaultAvatarAppearance(out AvatarWearable[] wearables, out byte[] visualParams) - { - visualParams = GetDefaultVisualParams(); - wearables = AvatarWearable.DefaultWearables; - } - - public void UpdateDatabase(UUID user, AvatarAppearance appearance) - { - m_scene.CommsManager.AvatarService.UpdateUserAppearance(user, appearance); - } - - private static byte[] GetDefaultVisualParams() - { - byte[] visualParams; - visualParams = new byte[218]; - for (int i = 0; i < 218; i++) - { - visualParams[i] = 100; - } - return visualParams; - } - } -} diff --git a/OpenSim/Region/Environment/Modules/Avatar/Chat/ChannelState.cs b/OpenSim/Region/Environment/Modules/Avatar/Chat/ChannelState.cs deleted file mode 100644 index dfa1caa..0000000 --- a/OpenSim/Region/Environment/Modules/Avatar/Chat/ChannelState.cs +++ /dev/null @@ -1,628 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using System.Reflection; -using System.Text.RegularExpressions; -using log4net; -using Nini.Config; -using OpenSim.Framework; -using OpenSim.Region.Framework.Interfaces; -using OpenSim.Region.Framework.Scenes; - -namespace OpenSim.Region.Environment.Modules.Avatar.Chat -{ - - // An instance of this class exists for each unique combination of - // IRC chat interface characteristics, as determined by the supplied - // configuration file. - - internal class ChannelState - { - - private static readonly ILog m_log = - LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private static Regex arg = new Regex(@"\[[^\[\]]*\]"); - private static int _idk_ = 0; - private static int DEBUG_CHANNEL = 2147483647; - - // These are the IRC Connector configurable parameters with hard-wired - // default values (retained for compatability). - - internal string Server = null; - internal string Password = null; - internal string IrcChannel = null; - internal string BaseNickname = "OSimBot"; - internal uint Port = 6667; - internal string User = "USER OpenSimBot 8 * :I'm an OpenSim to IRC bot"; - - internal bool ClientReporting = true; - internal bool RelayChat = true; - internal bool RelayPrivateChannels = false; - internal int RelayChannel = 1; - internal List ValidInWorldChannels = new List(); - - // Connector agnostic parameters. These values are NOT shared with the - // connector and do not differentiate at an IRC level - - internal string PrivateMessageFormat = "PRIVMSG {0} :<{2}> {1} {3}"; - internal string NoticeMessageFormat = "PRIVMSG {0} :<{2}> {3}"; - internal int RelayChannelOut = -1; - internal bool RandomizeNickname = true; - internal bool CommandsEnabled = false; - internal int CommandChannel = -1; - internal int ConnectDelay = 10; - internal int PingDelay = 15; - internal string DefaultZone = "Sim"; - - internal string _accessPassword = String.Empty; - internal Regex AccessPasswordRegex = null; - internal string AccessPassword - { - get { return _accessPassword; } - set - { - _accessPassword = value; - AccessPasswordRegex = new Regex(String.Format(@"^{0},\s*(?[^,]+),\s*(?.+)$", _accessPassword), - RegexOptions.Compiled); - } - } - - - - // IRC connector reference - - internal IRCConnector irc = null; - - internal int idn = _idk_++; - - // List of regions dependent upon this connection - - internal List clientregions = new List(); - - // Needed by OpenChannel - - internal ChannelState() - { - } - - // This constructor is used by the Update* methods. A copy of the - // existing channel state is created, and distinguishing characteristics - // are copied across. - - internal ChannelState(ChannelState model) - { - Server = model.Server; - Password = model.Password; - IrcChannel = model.IrcChannel; - Port = model.Port; - BaseNickname = model.BaseNickname; - RandomizeNickname = model.RandomizeNickname; - User = model.User; - CommandsEnabled = model.CommandsEnabled; - CommandChannel = model.CommandChannel; - RelayChat = model.RelayChat; - RelayPrivateChannels = model.RelayPrivateChannels; - RelayChannelOut = model.RelayChannelOut; - RelayChannel = model.RelayChannel; - ValidInWorldChannels = model.ValidInWorldChannels; - PrivateMessageFormat = model.PrivateMessageFormat; - NoticeMessageFormat = model.NoticeMessageFormat; - ClientReporting = model.ClientReporting; - AccessPassword = model.AccessPassword; - DefaultZone = model.DefaultZone; - ConnectDelay = model.ConnectDelay; - PingDelay = model.PingDelay; - } - - // Read the configuration file, performing variable substitution and any - // necessary aliasing. See accompanying documentation for how this works. - // If you don't need variables, then this works exactly as before. - // If either channel or server are not specified, the request fails. - - internal static void OpenChannel(RegionState rs, IConfig config) - { - - // Create a new instance of a channel. This may not actually - // get used if an equivalent channel already exists. - - ChannelState cs = new ChannelState(); - - // Read in the configuration file and filter everything for variable - // subsititution. - - m_log.DebugFormat("[IRC-Channel-{0}] Initial request by Region {1} to connect to IRC", cs.idn, rs.Region); - - cs.Server = Substitute(rs, config.GetString("server", null)); - m_log.DebugFormat("[IRC-Channel-{0}] Server : <{1}>", cs.idn, cs.Server); - cs.Password = Substitute(rs, config.GetString("password", null)); - // probably not a good idea to put a password in the log file - cs.IrcChannel = Substitute(rs, config.GetString("channel", null)); - m_log.DebugFormat("[IRC-Channel-{0}] IrcChannel : <{1}>", cs.idn, cs.IrcChannel); - cs.Port = Convert.ToUInt32(Substitute(rs, config.GetString("port", Convert.ToString(cs.Port)))); - m_log.DebugFormat("[IRC-Channel-{0}] Port : <{1}>", cs.idn, cs.Port); - cs.BaseNickname = Substitute(rs, config.GetString("nick", cs.BaseNickname)); - m_log.DebugFormat("[IRC-Channel-{0}] BaseNickname : <{1}>", cs.idn, cs.BaseNickname); - cs.RandomizeNickname = Convert.ToBoolean(Substitute(rs, config.GetString("randomize_nick", Convert.ToString(cs.RandomizeNickname)))); - m_log.DebugFormat("[IRC-Channel-{0}] RandomizeNickname : <{1}>", cs.idn, cs.RandomizeNickname); - cs.RandomizeNickname = Convert.ToBoolean(Substitute(rs, config.GetString("nicknum", Convert.ToString(cs.RandomizeNickname)))); - m_log.DebugFormat("[IRC-Channel-{0}] RandomizeNickname : <{1}>", cs.idn, cs.RandomizeNickname); - cs.User = Substitute(rs, config.GetString("username", cs.User)); - m_log.DebugFormat("[IRC-Channel-{0}] User : <{1}>", cs.idn, cs.User); - cs.CommandsEnabled = Convert.ToBoolean(Substitute(rs, config.GetString("commands_enabled", Convert.ToString(cs.CommandsEnabled)))); - m_log.DebugFormat("[IRC-Channel-{0}] CommandsEnabled : <{1}>", cs.idn, cs.CommandsEnabled); - cs.CommandChannel = Convert.ToInt32(Substitute(rs, config.GetString("commandchannel", Convert.ToString(cs.CommandChannel)))); - m_log.DebugFormat("[IRC-Channel-{0}] CommandChannel : <{1}>", cs.idn, cs.CommandChannel); - cs.CommandChannel = Convert.ToInt32(Substitute(rs, config.GetString("command_channel", Convert.ToString(cs.CommandChannel)))); - m_log.DebugFormat("[IRC-Channel-{0}] CommandChannel : <{1}>", cs.idn, cs.CommandChannel); - cs.RelayChat = Convert.ToBoolean(Substitute(rs, config.GetString("relay_chat", Convert.ToString(cs.RelayChat)))); - m_log.DebugFormat("[IRC-Channel-{0}] RelayChat : <{1}>", cs.idn, cs.RelayChat); - cs.RelayPrivateChannels = Convert.ToBoolean(Substitute(rs, config.GetString("relay_private_channels", Convert.ToString(cs.RelayPrivateChannels)))); - m_log.DebugFormat("[IRC-Channel-{0}] RelayPrivateChannels : <{1}>", cs.idn, cs.RelayPrivateChannels); - cs.RelayPrivateChannels = Convert.ToBoolean(Substitute(rs, config.GetString("useworldcomm", Convert.ToString(cs.RelayPrivateChannels)))); - m_log.DebugFormat("[IRC-Channel-{0}] RelayPrivateChannels : <{1}>", cs.idn, cs.RelayPrivateChannels); - cs.RelayChannelOut = Convert.ToInt32(Substitute(rs, config.GetString("relay_private_channel_out", Convert.ToString(cs.RelayChannelOut)))); - m_log.DebugFormat("[IRC-Channel-{0}] RelayChannelOut : <{1}>", cs.idn, cs.RelayChannelOut); - cs.RelayChannel = Convert.ToInt32(Substitute(rs, config.GetString("relay_private_channel_in", Convert.ToString(cs.RelayChannel)))); - m_log.DebugFormat("[IRC-Channel-{0}] RelayChannel : <{1}>", cs.idn, cs.RelayChannel); - cs.RelayChannel = Convert.ToInt32(Substitute(rs, config.GetString("inchannel", Convert.ToString(cs.RelayChannel)))); - m_log.DebugFormat("[IRC-Channel-{0}] RelayChannel : <{1}>", cs.idn, cs.RelayChannel); - cs.PrivateMessageFormat = Substitute(rs, config.GetString("msgformat", cs.PrivateMessageFormat)); - m_log.DebugFormat("[IRC-Channel-{0}] PrivateMessageFormat : <{1}>", cs.idn, cs.PrivateMessageFormat); - cs.NoticeMessageFormat = Substitute(rs, config.GetString("noticeformat", cs.NoticeMessageFormat)); - m_log.DebugFormat("[IRC-Channel-{0}] NoticeMessageFormat : <{1}>", cs.idn, cs.NoticeMessageFormat); - cs.ClientReporting = Convert.ToInt32(Substitute(rs, config.GetString("verbosity", cs.ClientReporting?"1":"0"))) > 0; - m_log.DebugFormat("[IRC-Channel-{0}] ClientReporting : <{1}>", cs.idn, cs.ClientReporting); - cs.ClientReporting = Convert.ToBoolean(Substitute(rs, config.GetString("report_clients", Convert.ToString(cs.ClientReporting)))); - m_log.DebugFormat("[IRC-Channel-{0}] ClientReporting : <{1}>", cs.idn, cs.ClientReporting); - cs.DefaultZone = Substitute(rs, config.GetString("fallback_region", cs.DefaultZone)); - m_log.DebugFormat("[IRC-Channel-{0}] DefaultZone : <{1}>", cs.idn, cs.DefaultZone); - cs.ConnectDelay = Convert.ToInt32(Substitute(rs, config.GetString("connect_delay", Convert.ToString(cs.ConnectDelay)))); - m_log.DebugFormat("[IRC-Channel-{0}] ConnectDelay : <{1}>", cs.idn, cs.ConnectDelay); - cs.PingDelay = Convert.ToInt32(Substitute(rs, config.GetString("ping_delay", Convert.ToString(cs.PingDelay)))); - m_log.DebugFormat("[IRC-Channel-{0}] PingDelay : <{1}>", cs.idn, cs.PingDelay); - cs.AccessPassword = Substitute(rs, config.GetString("access_password", cs.AccessPassword)); - m_log.DebugFormat("[IRC-Channel-{0}] AccessPassword : <{1}>", cs.idn, cs.AccessPassword); - - - // Fail if fundamental information is still missing - - if (cs.Server == null || cs.IrcChannel == null || cs.BaseNickname == null || cs.User == null) - throw new Exception(String.Format("[IRC-Channel-{0}] Invalid configuration for region {1}", cs.idn, rs.Region)); - - m_log.InfoFormat("[IRC-Channel-{0}] Configuration for Region {1} is valid", cs.idn, rs.Region); - m_log.InfoFormat("[IRC-Channel-{0}] Server = {1}", cs.idn, cs.Server); - m_log.InfoFormat("[IRC-Channel-{0}] Channel = {1}", cs.idn, cs.IrcChannel); - m_log.InfoFormat("[IRC-Channel-{0}] Port = {1}", cs.idn, cs.Port); - m_log.InfoFormat("[IRC-Channel-{0}] Nickname = {1}", cs.idn, cs.BaseNickname); - m_log.InfoFormat("[IRC-Channel-{0}] User = {1}", cs.idn, cs.User); - - // Set the channel state for this region - - if (cs.RelayChat) - { - cs.ValidInWorldChannels.Add(0); - cs.ValidInWorldChannels.Add(DEBUG_CHANNEL); - } - - if (cs.RelayPrivateChannels) - cs.ValidInWorldChannels.Add(cs.RelayChannelOut); - - rs.cs = Integrate(rs, cs); - - } - - // An initialized channel state instance is passed in. If an identical - // channel state instance already exists, then the existing instance - // is used to replace the supplied value. - // If the instance matches with respect to IRC, then the underlying - // IRCConnector is assigned to the supplied channel state and the - // updated value is returned. - // If there is no match, then the supplied instance is completed by - // creating and assigning an instance of an IRC connector. - - private static ChannelState Integrate(RegionState rs, ChannelState p_cs) - { - - ChannelState cs = p_cs; - - // Check to see if we have an existing server/channel setup that can be used - // In the absence of variable substitution this will always resolve to the - // same ChannelState instance, and the table will only contains a single - // entry, so the performance considerations for the existing behavior are - // zero. Only the IRC connector is shared, the ChannelState still contains - // values that, while independent of the IRC connetion, do still distinguish - // this region's behavior. - - lock (IRCBridgeModule.m_channels) - { - - foreach (ChannelState xcs in IRCBridgeModule.m_channels) - { - if (cs.IsAPerfectMatchFor(xcs)) - { - m_log.DebugFormat("[IRC-Channel-{0}] Channel state matched", cs.idn); - cs = xcs; - break; - } - if (cs.IsAConnectionMatchFor(xcs)) - { - m_log.DebugFormat("[IRC-Channel-{0}] Channel matched", cs.idn); - cs.irc = xcs.irc; - break; - } - } - - } - - // No entry was found, so this is going to be a new entry. - - if (cs.irc == null) - { - - m_log.DebugFormat("[IRC-Channel-{0}] New channel required", cs.idn); - - if ((cs.irc = new IRCConnector(cs)) != null) - { - - IRCBridgeModule.m_channels.Add(cs); - - m_log.InfoFormat("[IRC-Channel-{0}] New channel initialized for {1}, nick: {2}, commands {3}, private channels {4}", - cs.idn, rs.Region, cs.DefaultZone, - cs.CommandsEnabled ? "enabled" : "not enabled", - cs.RelayPrivateChannels ? "relayed" : "not relayed"); - } - else - { - string txt = String.Format("[IRC-Channel-{0}] Region {1} failed to connect to channel {2} on server {3}:{4}", - cs.idn, rs.Region, cs.IrcChannel, cs.Server, cs.Port); - m_log.Error(txt); - throw new Exception(txt); - } - } - else - { - m_log.InfoFormat("[IRC-Channel-{0}] Region {1} reusing existing connection to channel {2} on server {3}:{4}", - cs.idn, rs.Region, cs.IrcChannel, cs.Server, cs.Port); - } - - m_log.InfoFormat("[IRC-Channel-{0}] Region {1} associated with channel {2} on server {3}:{4}", - cs.idn, rs.Region, cs.IrcChannel, cs.Server, cs.Port); - - // We're finally ready to commit ourselves - - - return cs; - - } - - // These routines allow differentiating changes to - // the underlying channel state. If necessary, a - // new channel state will be created. - - internal ChannelState UpdateServer(RegionState rs, string server) - { - RemoveRegion(rs); - ChannelState cs = new ChannelState(this); - cs.Server = server; - cs = Integrate(rs, cs); - cs.AddRegion(rs); - return cs; - } - - internal ChannelState UpdatePort(RegionState rs, string port) - { - RemoveRegion(rs); - ChannelState cs = new ChannelState(this); - cs.Port = Convert.ToUInt32(port); - cs = Integrate(rs, cs); - cs.AddRegion(rs); - return cs; - } - - internal ChannelState UpdateChannel(RegionState rs, string channel) - { - RemoveRegion(rs); - ChannelState cs = new ChannelState(this); - cs.IrcChannel = channel; - cs = Integrate(rs, cs); - cs.AddRegion(rs); - return cs; - } - - internal ChannelState UpdateNickname(RegionState rs, string nickname) - { - RemoveRegion(rs); - ChannelState cs = new ChannelState(this); - cs.BaseNickname = nickname; - cs = Integrate(rs, cs); - cs.AddRegion(rs); - return cs; - } - - internal ChannelState UpdateClientReporting(RegionState rs, string cr) - { - RemoveRegion(rs); - ChannelState cs = new ChannelState(this); - cs.ClientReporting = Convert.ToBoolean(cr); - cs = Integrate(rs, cs); - cs.AddRegion(rs); - return cs; - } - - internal ChannelState UpdateRelayIn(RegionState rs, string channel) - { - RemoveRegion(rs); - ChannelState cs = new ChannelState(this); - cs.RelayChannel = Convert.ToInt32(channel); - cs = Integrate(rs, cs); - cs.AddRegion(rs); - return cs; - } - - internal ChannelState UpdateRelayOut(RegionState rs, string channel) - { - RemoveRegion(rs); - ChannelState cs = new ChannelState(this); - cs.RelayChannelOut = Convert.ToInt32(channel); - cs = Integrate(rs, cs); - cs.AddRegion(rs); - return cs; - } - - // Determine whether or not this is a 'new' channel. Only those - // attributes that uniquely distinguish an IRC connection should - // be included here (and only those attributes should really be - // in the ChannelState structure) - - private bool IsAConnectionMatchFor(ChannelState cs) - { - return ( - Server == cs.Server && - IrcChannel == cs.IrcChannel && - Port == cs.Port && - BaseNickname == cs.BaseNickname && - User == cs.User - ); - } - - // This level of obsessive matching allows us to produce - // a minimal overhead int he case of a server which does - // need to differentiate IRC at a region level. - - private bool IsAPerfectMatchFor(ChannelState cs) - { - return ( IsAConnectionMatchFor(cs) && - RelayChannelOut == cs.RelayChannelOut && - PrivateMessageFormat == cs.PrivateMessageFormat && - NoticeMessageFormat == cs.NoticeMessageFormat && - RandomizeNickname == cs.RandomizeNickname && - AccessPassword == cs.AccessPassword && - CommandsEnabled == cs.CommandsEnabled && - CommandChannel == cs.CommandChannel && - DefaultZone == cs.DefaultZone && - RelayPrivateChannels == cs.RelayPrivateChannels && - RelayChannel == cs.RelayChannel && - RelayChat == cs.RelayChat && - ClientReporting == cs.ClientReporting - ); - } - - // This function implements the variable substitution mechanism - // for the configuration values. Each string read from the - // configuration file is scanned for '[...]' enclosures. Each - // one that is found is replaced by either a runtime variable - // (%xxx) or an existing configuration key. When no further - // substitution is possible, the remaining string is returned - // to the caller. This allows for arbitrarily nested - // enclosures. - - private static string Substitute(RegionState rs, string instr) - { - - string result = instr; - - if (result == null || result.Length == 0) - return result; - - // Repeatedly scan the string until all possible - // substitutions have been performed. - - // m_log.DebugFormat("[IRC-Channel] Parse[1]: {0}", result); - - while (arg.IsMatch(result)) - { - - string vvar = arg.Match(result).ToString(); - string var = vvar.Substring(1,vvar.Length-2).Trim(); - - switch (var.ToLower()) - { - case "%region" : - result = result.Replace(vvar, rs.Region); - break; - case "%host" : - result = result.Replace(vvar, rs.Host); - break; - case "%master1" : - result = result.Replace(vvar, rs.MA1); - break; - case "%master2" : - result = result.Replace(vvar, rs.MA2); - break; - case "%locx" : - result = result.Replace(vvar, rs.LocX); - break; - case "%locy" : - result = result.Replace(vvar, rs.LocY); - break; - case "%k" : - result = result.Replace(vvar, rs.IDK); - break; - default : - result = result.Replace(vvar, rs.config.GetString(var,var)); - break; - } - // m_log.DebugFormat("[IRC-Channel] Parse[2]: {0}", result); - } - - // m_log.DebugFormat("[IRC-Channel] Parse[3]: {0}", result); - return result; - - } - - public void Close() - { - m_log.InfoFormat("[IRC-Channel-{0}] Closing channel <{1}> to server <{2}:{3}>", - idn, IrcChannel, Server, Port); - m_log.InfoFormat("[IRC-Channel-{0}] There are {1} active clients", - idn, clientregions.Count); - irc.Close(); - } - - public void Open() - { - m_log.InfoFormat("[IRC-Channel-{0}] Opening channel <{1}> to server <{2}:{3}>", - idn, IrcChannel, Server, Port); - - irc.Open(); - - } - - // These are called by each region that attaches to this channel. The call affects - // only the relationship of the region with the channel. Not the channel to IRC - // relationship (unless it is closed and we want it open). - - public void Open(RegionState rs) - { - AddRegion(rs); - Open(); - } - - // Close is called to ensure that the IRC session is terminated if this is the - // only client. - - public void Close(RegionState rs) - { - RemoveRegion(rs); - lock (IRCBridgeModule.m_channels) - { - if (clientregions.Count == 0) - { - Close(); - IRCBridgeModule.m_channels.Remove(this); - m_log.InfoFormat("[IRC-Channel-{0}] Region {1} is last user of channel <{2}> to server <{3}:{4}>", - idn, rs.Region, IrcChannel, Server, Port); - m_log.InfoFormat("[IRC-Channel-{0}] Removed", idn); - } - } - } - - // Add a client region to this channel if it is not already known - - public void AddRegion(RegionState rs) - { - m_log.InfoFormat("[IRC-Channel-{0}] Adding region {1} to channel <{2}> to server <{3}:{4}>", - idn, rs.Region, IrcChannel, Server, Port); - if (!clientregions.Contains(rs)) - { - clientregions.Add(rs); - lock (irc) irc.depends++; - } - } - - // Remove a client region from the channel. If this is the last - // region, then clean up the channel. The connector will clean itself - // up if it finds itself about to be GC'd. - - public void RemoveRegion(RegionState rs) - { - - m_log.InfoFormat("[IRC-Channel-{0}] Removing region {1} from channel <{2} to server <{3}:{4}>", - idn, rs.Region, IrcChannel, Server, Port); - - if (clientregions.Contains(rs)) - { - clientregions.Remove(rs); - lock (irc) irc.depends--; - } - - } - - // This function is lifted from the IRCConnector because it - // contains information that is not differentiating from an - // IRC point-of-view. - - public static void OSChat(IRCConnector p_irc, OSChatMessage c, bool cmsg) - { - - // m_log.DebugFormat("[IRC-OSCHAT] from {0}:{1}", p_irc.Server, p_irc.IrcChannel); - - try - { - - // Scan through the set of unique channel configuration for those - // that belong to this connector. And then forward the message to - // all regions known to those channels. - // Note that this code is responsible for completing some of the - // settings for the inbound OSChatMessage - - lock (IRCBridgeModule.m_channels) - { - foreach (ChannelState cs in IRCBridgeModule.m_channels) - { - if ( p_irc == cs.irc) - { - - // This non-IRC differentiator moved to here - - if (cmsg && !cs.ClientReporting) - continue; - - // This non-IRC differentiator moved to here - - c.Channel = (cs.RelayPrivateChannels ? cs.RelayChannel : 0); - - foreach (RegionState region in cs.clientregions) - { - region.OSChat(cs.irc, c); - } - - } - } - } - } - catch (Exception ex) - { - m_log.ErrorFormat("[IRC-OSCHAT]: BroadcastSim Exception: {0}", ex.Message); - m_log.Debug(ex); - } - } - } -} diff --git a/OpenSim/Region/Environment/Modules/Avatar/Chat/ChatModule.cs b/OpenSim/Region/Environment/Modules/Avatar/Chat/ChatModule.cs deleted file mode 100644 index f234b75..0000000 --- a/OpenSim/Region/Environment/Modules/Avatar/Chat/ChatModule.cs +++ /dev/null @@ -1,287 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using System.IO; -using System.Net.Sockets; -using System.Reflection; -using System.Text.RegularExpressions; -using System.Threading; -using OpenMetaverse; -using log4net; -using Nini.Config; -using OpenSim.Framework; -using OpenSim.Region.Framework.Interfaces; -using OpenSim.Region.Framework.Scenes; - -namespace OpenSim.Region.Environment.Modules.Avatar.Chat -{ - public class ChatModule : IRegionModule - { - private static readonly ILog m_log = - LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private const int DEBUG_CHANNEL = 2147483647; - - private bool m_enabled = true; - private int m_saydistance = 30; - private int m_shoutdistance = 100; - private int m_whisperdistance = 10; - private List m_scenes = new List(); - - internal object m_syncInit = new object(); - - #region IRegionModule Members - public virtual void Initialise(Scene scene, IConfigSource config) - { - // wrap this in a try block so that defaults will work if - // the config file doesn't specify otherwise. - try - { - m_enabled = config.Configs["Chat"].GetBoolean("enabled", m_enabled); - if (!m_enabled) return; - - m_whisperdistance = config.Configs["Chat"].GetInt("whisper_distance", m_whisperdistance); - m_saydistance = config.Configs["Chat"].GetInt("say_distance", m_saydistance); - m_shoutdistance = config.Configs["Chat"].GetInt("shout_distance", m_shoutdistance); - } - catch (Exception) - { - } - - lock (m_syncInit) - { - if (!m_scenes.Contains(scene)) - { - m_scenes.Add(scene); - scene.EventManager.OnNewClient += OnNewClient; - scene.EventManager.OnChatFromWorld += OnChatFromWorld; - scene.EventManager.OnChatBroadcast += OnChatBroadcast; - } - } - - m_log.InfoFormat("[CHAT] initialized for {0} w:{1} s:{2} S:{3}", scene.RegionInfo.RegionName, - m_whisperdistance, m_saydistance, m_shoutdistance); - } - public virtual void PostInitialise() - { - } - - public virtual void Close() - { - } - - public virtual string Name - { - get { return "ChatModule"; } - } - - public virtual bool IsSharedModule - { - get { return true; } - } - - #endregion - - - public virtual void OnNewClient(IClientAPI client) - { - client.OnChatFromClient += OnChatFromClient; - } - - protected OSChatMessage FixPositionOfChatMessage(OSChatMessage c) - { - ScenePresence avatar; - Scene scene = (Scene)c.Scene; - if ((avatar = scene.GetScenePresence(c.Sender.AgentId)) != null) - c.Position = avatar.AbsolutePosition; - - return c; - } - - public virtual void OnChatFromClient(Object sender, OSChatMessage c) - { - c = FixPositionOfChatMessage(c); - - // redistribute to interested subscribers - Scene scene = (Scene)c.Scene; - scene.EventManager.TriggerOnChatFromClient(sender, c); - - // early return if not on public or debug channel - if (c.Channel != 0 && c.Channel != DEBUG_CHANNEL) return; - - // sanity check: - if (c.Sender == null) - { - m_log.ErrorFormat("[CHAT] OnChatFromClient from {0} has empty Sender field!", sender); - return; - } - - DeliverChatToAvatars(ChatSourceType.Agent, c); - } - - public virtual void OnChatFromWorld(Object sender, OSChatMessage c) - { - // early return if not on public or debug channel - if (c.Channel != 0 && c.Channel != DEBUG_CHANNEL) return; - - DeliverChatToAvatars(ChatSourceType.Object, c); - } - - protected virtual void DeliverChatToAvatars(ChatSourceType sourceType, OSChatMessage c) - { - string fromName = c.From; - UUID fromID = UUID.Zero; - string message = c.Message; - IScene scene = c.Scene; - Vector3 fromPos = c.Position; - Vector3 regionPos = new Vector3(scene.RegionInfo.RegionLocX * Constants.RegionSize, - scene.RegionInfo.RegionLocY * Constants.RegionSize, 0); - - if (c.Channel == DEBUG_CHANNEL) c.Type = ChatTypeEnum.DebugChannel; - - switch (sourceType) - { - case ChatSourceType.Agent: - if (!(scene is Scene)) - { - m_log.WarnFormat("[CHAT]: scene {0} is not a Scene object, cannot obtain scene presence for {1}", - scene.RegionInfo.RegionName, c.Sender.AgentId); - return; - } - ScenePresence avatar = (scene as Scene).GetScenePresence(c.Sender.AgentId); - fromPos = avatar.AbsolutePosition; - fromName = avatar.Name; - fromID = c.Sender.AgentId; - - break; - - case ChatSourceType.Object: - fromID = c.SenderUUID; - - break; - } - - // TODO: iterate over message - if (message.Length >= 1000) // libomv limit - message = message.Substring(0, 1000); - - // m_log.DebugFormat("[CHAT]: DCTA: fromID {0} fromName {1}, cType {2}, sType {3}", fromID, fromName, c.Type, sourceType); - - foreach (Scene s in m_scenes) - { - s.ForEachScenePresence(delegate(ScenePresence presence) - { - TrySendChatMessage(presence, fromPos, regionPos, fromID, fromName, - c.Type, message, sourceType); - }); - } - } - - - static private Vector3 CenterOfRegion = new Vector3(128, 128, 30); - public virtual void OnChatBroadcast(Object sender, OSChatMessage c) - { - // unless the chat to be broadcast is of type Region, we - // drop it if its channel is neither 0 nor DEBUG_CHANNEL - if (c.Channel != 0 && c.Channel != DEBUG_CHANNEL && c.Type != ChatTypeEnum.Region) return; - - ChatTypeEnum cType = c.Type; - if (c.Channel == DEBUG_CHANNEL) - cType = ChatTypeEnum.DebugChannel; - - if (cType == ChatTypeEnum.Region) - cType = ChatTypeEnum.Say; - - if (c.Message.Length > 1100) - c.Message = c.Message.Substring(0, 1000); - - // broadcast chat works by redistributing every incoming chat - // message to each avatar in the scene. - string fromName = c.From; - - UUID fromID = UUID.Zero; - ChatSourceType sourceType = ChatSourceType.Object; - if (null != c.Sender) - { - ScenePresence avatar = (c.Scene as Scene).GetScenePresence(c.Sender.AgentId); - fromID = c.Sender.AgentId; - fromName = avatar.Name; - sourceType = ChatSourceType.Agent; - } - - // m_log.DebugFormat("[CHAT] Broadcast: fromID {0} fromName {1}, cType {2}, sType {3}", fromID, fromName, cType, sourceType); - - ((Scene)c.Scene).ForEachScenePresence( - delegate(ScenePresence presence) - { - // ignore chat from child agents - if (presence.IsChildAgent) return; - - IClientAPI client = presence.ControllingClient; - - // don't forward SayOwner chat from objects to - // non-owner agents - if ((c.Type == ChatTypeEnum.Owner) && - (null != c.SenderObject) && - (((SceneObjectPart)c.SenderObject).OwnerID != client.AgentId)) - return; - - client.SendChatMessage(c.Message, (byte)cType, CenterOfRegion, fromName, fromID, - (byte)sourceType, (byte)ChatAudibleLevel.Fully); - }); - } - - - protected virtual void TrySendChatMessage(ScenePresence presence, Vector3 fromPos, Vector3 regionPos, - UUID fromAgentID, string fromName, ChatTypeEnum type, - string message, ChatSourceType src) - { - // don't send stuff to child agents - if (presence.IsChildAgent) return; - - Vector3 fromRegionPos = fromPos + regionPos; - Vector3 toRegionPos = presence.AbsolutePosition + - new Vector3(presence.Scene.RegionInfo.RegionLocX * Constants.RegionSize, - presence.Scene.RegionInfo.RegionLocY * Constants.RegionSize, 0); - - 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,(byte)src,(byte)ChatAudibleLevel.Fully); - } - } -} diff --git a/OpenSim/Region/Environment/Modules/Avatar/Chat/IRCBridgeModule.cs b/OpenSim/Region/Environment/Modules/Avatar/Chat/IRCBridgeModule.cs deleted file mode 100644 index ccd81c7..0000000 --- a/OpenSim/Region/Environment/Modules/Avatar/Chat/IRCBridgeModule.cs +++ /dev/null @@ -1,219 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using log4net; -using Nini.Config; -using Nwc.XmlRpc; -using OpenSim.Framework; -using OpenSim.Region.Framework.Interfaces; -using OpenSim.Region.Framework.Scenes; - -namespace OpenSim.Region.Environment.Modules.Avatar.Chat -{ - public class IRCBridgeModule : IRegionModule - { - private static readonly ILog m_log = - LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - internal static bool configured = false; - internal static bool enabled = false; - internal static IConfig m_config = null; - - internal static List m_channels = new List(); - internal static List m_regions = new List(); - - internal static string password = String.Empty; - - internal RegionState region = null; - - #region IRegionModule Members - - public string Name - { - get { return "IRCBridgeModule"; } - } - - public bool IsSharedModule - { - get { return false; } - } - - public void Initialise(Scene scene, IConfigSource config) - { - // Do a once-only scan of the configuration file to make - // sure it's basically intact. - - if (!configured) - { - configured = true; - - try - { - if ((m_config = config.Configs["IRC"]) == null) - { - m_log.InfoFormat("[IRC-Bridge] module not configured"); - return; - } - - if (!m_config.GetBoolean("enabled", false)) - { - m_log.InfoFormat("[IRC-Bridge] module disabled in configuration"); - return; - } - } - catch (Exception e) - { - m_log.ErrorFormat("[IRC-Bridge] configuration failed : {0}", e.Message); - return; - } - - enabled = true; - - if (config.Configs["RemoteAdmin"] != null) - { - password = config.Configs["RemoteAdmin"].GetString("access_password", password); - scene.CommsManager.HttpServer.AddXmlRPCHandler("irc_admin", XmlRpcAdminMethod, false); - } - } - - // Iff the IRC bridge is enabled, then each new region may be - // connected to IRC. But it should NOT be obligatory (and it - // is not). - // We have to do ALL of the startup here because PostInitialize - // is not called when a region gets created in-flight from the - // command line. - - if (enabled) - { - try - { - m_log.InfoFormat("[IRC-Bridge] Connecting region {0}", scene.RegionInfo.RegionName); - region = new RegionState(scene, m_config); - lock (m_regions) m_regions.Add(region); - region.Open(); - } - catch (Exception e) - { - m_log.WarnFormat("[IRC-Bridge] Region {0} not connected to IRC : {1}", scene.RegionInfo.RegionName, e.Message); - m_log.Debug(e); - } - } - else - { - m_log.WarnFormat("[IRC-Bridge] Not enabled. Connect for region {0} ignored", scene.RegionInfo.RegionName); - } - } - - // This module can be called in-flight in which case PostInitialize - // is not called following Initialize. So no use is made of this - // call. - - public void PostInitialise() - { - } - - // Called immediately before the region module is unloaded. Cleanup - // the region. - - public void Close() - { - if (!enabled) - return; - - region.Close(); - lock (m_regions) m_regions.Remove(region); - } - - #endregion - - public static XmlRpcResponse XmlRpcAdminMethod(XmlRpcRequest request) - { - m_log.Info("[IRC-Bridge]: XML RPC Admin Entry"); - - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable responseData = new Hashtable(); - - try - { - Hashtable requestData = (Hashtable)request.Params[0]; - bool found = false; - string region = String.Empty; - - if (password != String.Empty) - { - if (!requestData.ContainsKey("password")) - throw new Exception("Invalid request"); - if ((string)requestData["password"] != password) - throw new Exception("Invalid request"); - } - - if (!requestData.ContainsKey("region")) - throw new Exception("No region name specified"); - region = (string)requestData["region"]; - - foreach (RegionState rs in m_regions) - { - if (rs.Region == region) - { - responseData["server"] = rs.cs.Server; - responseData["port"] = (int)rs.cs.Port; - responseData["user"] = rs.cs.User; - responseData["channel"] = rs.cs.IrcChannel; - responseData["enabled"] = rs.cs.irc.Enabled; - responseData["connected"] = rs.cs.irc.Connected; - responseData["nickname"] = rs.cs.irc.Nick; - found = true; - break; - } - } - - if (!found) throw new Exception(String.Format("Region <{0}> not found", region)); - - responseData["success"] = true; - } - catch (Exception e) - { - m_log.InfoFormat("[IRC-Bridge] XML RPC Admin request failed : {0}", e.Message); - - responseData["success"] = "false"; - responseData["error"] = e.Message; - } - finally - { - response.Value = responseData; - } - - m_log.Debug("[IRC-Bridge]: XML RPC Admin Exit"); - - return response; - } - } -} diff --git a/OpenSim/Region/Environment/Modules/Avatar/Chat/IRCConnector.cs b/OpenSim/Region/Environment/Modules/Avatar/Chat/IRCConnector.cs deleted file mode 100644 index c3cafb0..0000000 --- a/OpenSim/Region/Environment/Modules/Avatar/Chat/IRCConnector.cs +++ /dev/null @@ -1,887 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Timers; -using System.Collections.Generic; -using System.IO; -using System.Net.Sockets; -using System.Reflection; -using System.Text.RegularExpressions; -using System.Threading; -using OpenMetaverse; -using log4net; -using Nini.Config; -using OpenSim.Framework; -using OpenSim.Region.Framework.Interfaces; -using OpenSim.Region.Framework.Scenes; - -namespace OpenSim.Region.Environment.Modules.Avatar.Chat -{ - public class IRCConnector - { - - #region Global (static) state - - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - // Local constants - - private static readonly Vector3 CenterOfRegion = new Vector3(128, 128, 20); - private static readonly char[] CS_SPACE = { ' ' }; - - private const int WD_INTERVAL = 1000; // base watchdog interval - private static int PING_PERIOD = 15; // WD intervals per PING - private static int ICCD_PERIOD = 10; // WD intervals between Connects - private static int L_TIMEOUT = 25; // Login time out interval - - private static int _idk_ = 0; // core connector identifier - private static int _pdk_ = 0; // ping interval counter - private static int _icc_ = 0; // IRC connect counter - - // List of configured connectors - - private static List m_connectors = new List(); - - // Watchdog state - - private static System.Timers.Timer m_watchdog = null; - - static IRCConnector() - { - m_log.DebugFormat("[IRC-Connector]: Static initialization started"); - m_watchdog = new System.Timers.Timer(WD_INTERVAL); - m_watchdog.Elapsed += new ElapsedEventHandler(WatchdogHandler); - m_watchdog.AutoReset = true; - m_watchdog.Start(); - m_log.DebugFormat("[IRC-Connector]: Static initialization complete"); - } - - #endregion - - #region Instance state - - // Connector identity - - internal int idn = _idk_++; - - // How many regions depend upon this connection - // This count is updated by the ChannelState object and reflects the sum - // of the region clients associated with the set of associated channel - // state instances. That's why it cannot be managed here. - - internal int depends = 0; - - // Working threads - - private Thread m_listener = null; - - private Object msyncConnect = new Object(); - - internal bool m_randomizeNick = true; // add random suffix - internal string m_baseNick = null; // base name for randomizing - internal string m_nick = null; // effective nickname - - public string Nick // Public property - { - get { return m_nick; } - set { m_nick = value; } - } - - private bool m_enabled = false; // connector enablement - public bool Enabled - { - get { return m_enabled; } - } - - private bool m_connected = false; // connection status - private bool m_pending = false; // login disposition - private int m_timeout = L_TIMEOUT; // login timeout counter - public bool Connected - { - get { return m_connected; } - } - - private string m_ircChannel; // associated channel id - public string IrcChannel - { - get { return m_ircChannel; } - set { m_ircChannel = value; } - } - - private uint m_port = 6667; // session port - public uint Port - { - get { return m_port; } - set { m_port = value; } - } - - private string m_server = null; // IRC server name - public string Server - { - get { return m_server; } - set { m_server = value; } - } - private string m_password = null; - public string Password - { - get { return m_password; } - set { m_password = value; } - } - - private string m_user = "USER OpenSimBot 8 * :I'm an OpenSim to IRC bot"; - public string User - { - get { return m_user; } - } - - // Network interface - - private TcpClient m_tcp; - private NetworkStream m_stream = null; - private StreamReader m_reader; - private StreamWriter m_writer; - - // Channel characteristic info (if available) - - internal string usermod = String.Empty; - internal string chanmod = String.Empty; - internal string version = String.Empty; - internal bool motd = false; - - #endregion - - #region connector instance management - - internal IRCConnector(ChannelState cs) - { - - // Prepare network interface - - m_tcp = null; - m_writer = null; - m_reader = null; - - // Setup IRC session parameters - - m_server = cs.Server; - m_password = cs.Password; - m_baseNick = cs.BaseNickname; - m_randomizeNick = cs.RandomizeNickname; - m_ircChannel = cs.IrcChannel; - m_port = cs.Port; - m_user = cs.User; - - if (m_watchdog == null) - { - // Non-differentiating - - ICCD_PERIOD = cs.ConnectDelay; - PING_PERIOD = cs.PingDelay; - - // Smaller values are not reasonable - - if (ICCD_PERIOD < 5) - ICCD_PERIOD = 5; - - if (PING_PERIOD < 5) - PING_PERIOD = 5; - - _icc_ = ICCD_PERIOD; // get started right away! - - } - - // The last line of defense - - if (m_server == null || m_baseNick == null || m_ircChannel == null || m_user == null) - throw new Exception("Invalid connector configuration"); - - // Generate an initial nickname if randomizing is enabled - - if (m_randomizeNick) - { - m_nick = m_baseNick + Util.RandomClass.Next(1, 99); - } - - // Add the newly created connector to the known connectors list - - m_connectors.Add(this); - - m_log.InfoFormat("[IRC-Connector-{0}]: Initialization complete", idn); - - } - - ~IRCConnector() - { - m_watchdog.Stop(); - Close(); - } - - // Mark the connector as connectable. Harmless if already enabled. - - public void Open() - { - if (!m_enabled) - { - - m_connectors.Add(this); - m_enabled = true; - - if (!Connected) - { - Connect(); - } - - } - } - - // Only close the connector if the dependency count is zero. - - public void Close() - { - - m_log.InfoFormat("[IRC-Connector-{0}] Closing", idn); - - lock (msyncConnect) - { - - if ((depends == 0) && Enabled) - { - - m_enabled = false; - - if (Connected) - { - m_log.DebugFormat("[IRC-Connector-{0}] Closing interface", idn); - - // Cleanup the IRC session - - try - { - m_writer.WriteLine(String.Format("QUIT :{0} to {1} wormhole to {2} closing", - m_nick, m_ircChannel, m_server)); - m_writer.Flush(); - } - catch (Exception) {} - - - m_connected = false; - - try { m_writer.Close(); } catch (Exception) {} - try { m_reader.Close(); } catch (Exception) {} - try { m_stream.Close(); } catch (Exception) {} - try { m_tcp.Close(); } catch (Exception) {} - - } - - m_connectors.Remove(this); - - } - } - - m_log.InfoFormat("[IRC-Connector-{0}] Closed", idn); - - } - - #endregion - - #region session management - - // Connect to the IRC server. A connector should always be connected, once enabled - - public void Connect() - { - - if (!m_enabled) - return; - - // Delay until next WD cycle if this is too close to the last start attempt - - while (_icc_ < ICCD_PERIOD) - return; - - m_log.DebugFormat("[IRC-Connector-{0}]: Connection request for {1} on {2}:{3}", idn, m_nick, m_server, m_ircChannel); - - lock (msyncConnect) - { - - _icc_ = 0; - - try - { - if (m_connected) return; - - m_connected = true; - m_pending = true; - m_timeout = L_TIMEOUT; - - m_tcp = new TcpClient(m_server, (int)m_port); - m_stream = m_tcp.GetStream(); - m_reader = new StreamReader(m_stream); - m_writer = new StreamWriter(m_stream); - - m_log.InfoFormat("[IRC-Connector-{0}]: Connected to {1}:{2}", idn, m_server, m_port); - - m_listener = new Thread(new ThreadStart(ListenerRun)); - m_listener.Name = "IRCConnectorListenerThread"; - m_listener.IsBackground = true; - m_listener.Start(); - ThreadTracker.Add(m_listener); - - // This is the message order recommended by RFC 2812 - if (m_password != null) - m_writer.WriteLine(String.Format("PASS {0}", m_password)); - m_writer.WriteLine(String.Format("NICK {0}", m_nick)); - m_writer.Flush(); - m_writer.WriteLine(m_user); - m_writer.Flush(); - m_writer.WriteLine(String.Format("JOIN {0}", m_ircChannel)); - m_writer.Flush(); - - m_log.InfoFormat("[IRC-Connector-{0}]: {1} has asked to join {2}", idn, m_nick, m_ircChannel); - - } - catch (Exception e) - { - m_log.ErrorFormat("[IRC-Connector-{0}] cannot connect {1} to {2}:{3}: {4}", - idn, m_nick, m_server, m_port, e.Message); - m_connected = false; - m_pending = false; - } - - } - - return; - - } - - // Reconnect is used to force a re-cycle of the IRC connection. Should generally - // be a transparent event - - public void Reconnect() - { - m_log.DebugFormat("[IRC-Connector-{0}]: Reconnect request for {1} on {2}:{3}", idn, m_nick, m_server, m_ircChannel); - - // Don't do this if a Connect is in progress... - - lock (msyncConnect) - { - - if (m_connected) - { - m_log.InfoFormat("[IRC-Connector-{0}] Resetting connector", idn); - - // Mark as disconnected. This will allow the listener thread - // to exit if still in-flight. - - - // The listener thread is not aborted - it *might* actually be - // the thread that is running the Reconnect! Instead just close - // the socket and it will disappear of its own accord, once this - // processing is completed. - - try { m_writer.Close(); } catch (Exception) {} - try { m_reader.Close(); } catch (Exception) {} - try { m_tcp.Close(); } catch (Exception) {} - - m_connected = false; - m_pending = false; - - } - - } - - Connect(); - - } - - #endregion - - #region Outbound (to-IRC) message handlers - - public void PrivMsg(string pattern, string from, string region, string msg) - { - - m_log.DebugFormat("[IRC-Connector-{0}] PrivMsg to IRC from {1}: <{2}>", idn, from, - String.Format(pattern, m_ircChannel, from, region, msg)); - - // One message to the IRC server - - try - { - m_writer.WriteLine(pattern, m_ircChannel, from, region, msg); - m_writer.Flush(); - m_log.DebugFormat("[IRC-Connector-{0}]: PrivMsg from {1} in {2}: {3}", idn, from, region, msg); - } - catch (IOException) - { - m_log.ErrorFormat("[IRC-Connector-{0}]: PrivMsg I/O Error: disconnected from IRC server", idn); - Reconnect(); - } - catch (Exception ex) - { - m_log.ErrorFormat("[IRC-Connector-{0}]: PrivMsg exception : {1}", idn, ex.Message); - m_log.Debug(ex); - } - - } - - public void Send(string msg) - { - - m_log.DebugFormat("[IRC-Connector-{0}] Send to IRC : <{1}>", idn, msg); - - try - { - m_writer.WriteLine(msg); - m_writer.Flush(); - m_log.DebugFormat("[IRC-Connector-{0}] Sent command string: {1}", idn, msg); - } - catch (IOException) - { - m_log.ErrorFormat("[IRC-Connector-{0}] Disconnected from IRC server.(Send)", idn); - Reconnect(); - } - catch (Exception ex) - { - m_log.ErrorFormat("[IRC-Connector-{0}] Send exception trap: {0}", idn, ex.Message); - m_log.Debug(ex); - } - - } - - #endregion - - public void ListenerRun() - { - string inputLine; - - try - { - while (m_enabled && m_connected) - { - - if ((inputLine = m_reader.ReadLine()) == null) - throw new Exception("Listener input socket closed"); - - // m_log.Info("[IRCConnector]: " + inputLine); - - if (inputLine.Contains("PRIVMSG")) - { - - Dictionary data = ExtractMsg(inputLine); - - // Any chat ??? - if (data != null) - { - - OSChatMessage c = new OSChatMessage(); - c.Message = data["msg"]; - c.Type = ChatTypeEnum.Region; - c.Position = CenterOfRegion; - c.From = data["nick"]; - c.Sender = null; - c.SenderUUID = UUID.Zero; - - // Is message "\001ACTION foo bar\001"? - // Then change to: "/me foo bar" - - if ((1 == c.Message[0]) && c.Message.Substring(1).StartsWith("ACTION")) - c.Message = String.Format("/me {0}", c.Message.Substring(8, c.Message.Length - 9)); - - ChannelState.OSChat(this, c, false); - - } - - } - else - { - ProcessIRCCommand(inputLine); - } - } - } - catch (Exception /*e*/) - { - // m_log.ErrorFormat("[IRC-Connector-{0}]: ListenerRun exception trap: {1}", idn, e.Message); - // m_log.Debug(e); - } - - // This is potentially circular, but harmless if so. - // The connection is marked as not connected the first time - // through reconnect. - - if (m_enabled) Reconnect(); - - } - - private Regex RE = new Regex(@":(?[\w-]*)!(?\S*) PRIVMSG (?\S+) :(?.*)", - RegexOptions.Multiline); - - private Dictionary ExtractMsg(string input) - { - //examines IRC commands and extracts any private messages - // which will then be reboadcast in the Sim - - // m_log.InfoFormat("[IRC-Connector-{0}]: ExtractMsg: {1}", idn, input); - - Dictionary result = null; - MatchCollection matches = RE.Matches(input); - - // Get some direct matches $1 $4 is a - if ((matches.Count == 0) || (matches.Count != 1) || (matches[0].Groups.Count != 5)) - { - // m_log.Info("[IRCConnector]: Number of matches: " + matches.Count); - // if (matches.Count > 0) - // { - // m_log.Info("[IRCConnector]: Number of groups: " + matches[0].Groups.Count); - // } - return null; - } - - result = new Dictionary(); - result.Add("nick", matches[0].Groups[1].Value); - result.Add("user", matches[0].Groups[2].Value); - result.Add("channel", matches[0].Groups[3].Value); - result.Add("msg", matches[0].Groups[4].Value); - - return result; - } - - public void BroadcastSim(string sender, string format, params string[] args) - { - try - { - OSChatMessage c = new OSChatMessage(); - c.From = sender; - c.Message = String.Format(format, args); - c.Type = ChatTypeEnum.Region; // ChatTypeEnum.Say; - c.Position = CenterOfRegion; - c.Sender = null; - c.SenderUUID = UUID.Zero; - - ChannelState.OSChat(this, c, true); - - } - catch (Exception ex) // IRC gate should not crash Sim - { - m_log.ErrorFormat("[IRC-Connector-{0}]: BroadcastSim Exception Trap: {1}\n{2}", idn, ex.Message, ex.StackTrace); - } - } - - #region IRC Command Handlers - - public void ProcessIRCCommand(string command) - { - - string[] commArgs; - string c_server = m_server; - - string pfx = String.Empty; - string cmd = String.Empty; - string parms = String.Empty; - - // ":" indicates that a prefix is present - // There are NEVER more than 17 real - // fields. A parameter that starts with - // ":" indicates that the remainder of the - // line is a single parameter value. - - commArgs = command.Split(CS_SPACE,2); - - if (commArgs[0].StartsWith(":")) - { - pfx = commArgs[0].Substring(1); - commArgs = commArgs[1].Split(CS_SPACE,2); - } - - cmd = commArgs[0]; - parms = commArgs[1]; - - // m_log.DebugFormat("[IRC-Connector-{0}] prefix = <{1}> cmd = <{2}>", idn, pfx, cmd); - - switch (cmd) - { - - // Messages 001-004 are always sent - // following signon. - - case "001" : // Welcome ... - case "002" : // Server information - case "003" : // Welcome ... - break; - case "004" : // Server information - m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms); - commArgs = parms.Split(CS_SPACE); - c_server = commArgs[1]; - m_server = c_server; - version = commArgs[2]; - usermod = commArgs[3]; - chanmod = commArgs[4]; - break; - case "005" : // Server information - break; - case "042" : - case "250" : - case "251" : - case "252" : - case "254" : - case "255" : - case "265" : - case "266" : - case "332" : // Subject - case "333" : // Subject owner (?) - case "353" : // Name list - case "366" : // End-of-Name list marker - case "372" : // MOTD body - case "375" : // MOTD start - m_log.InfoFormat("[IRC-Connector-{0}] [{1}] {2}", idn, cmd, parms.Split(CS_SPACE,2)[1]); - break; - case "376" : // MOTD end - m_log.InfoFormat("[IRC-Connector-{0}] [{1}] {2}", idn, cmd, parms.Split(CS_SPACE,2)[1]); - motd = true; - break; - case "451" : // Not registered - break; - case "433" : // Nickname in use - // Gen a new name - m_nick = m_baseNick + Util.RandomClass.Next(1, 99); - m_log.ErrorFormat("[IRC-Connector-{0}]: [{1}] IRC SERVER reports NicknameInUse, trying {2}", idn, cmd, m_nick); - // Retry - m_writer.WriteLine(String.Format("NICK {0}", m_nick)); - m_writer.Flush(); - m_writer.WriteLine(m_user); - m_writer.Flush(); - m_writer.WriteLine(String.Format("JOIN {0}", m_ircChannel)); - m_writer.Flush(); - break; - case "479" : // Bad channel name, etc. This will never work, so disable the connection - m_log.ErrorFormat("[IRC-Connector-{0}] [{1}] {2}", idn, cmd, parms.Split(CS_SPACE,2)[1]); - m_log.ErrorFormat("[IRC-Connector-{0}] [{1}] Connector disabled", idn, cmd); - m_enabled = false; - m_connected = false; - m_pending = false; - break; - case "NOTICE" : - m_log.WarnFormat("[IRC-Connector-{0}] [{1}] {2}", idn, cmd, parms.Split(CS_SPACE,2)[1]); - break; - case "ERROR" : - m_log.ErrorFormat("[IRC-Connector-{0}] [{1}] {2}", idn, cmd, parms.Split(CS_SPACE,2)[1]); - if (parms.Contains("reconnect too fast")) - ICCD_PERIOD++; - m_pending = false; - Reconnect(); - break; - case "PING" : - m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms); - m_writer.WriteLine(String.Format("PONG {0}", parms)); - m_writer.Flush(); - break; - case "PONG" : - break; - case "JOIN": - if (m_pending) - { - m_log.InfoFormat("[IRC-Connector-{0}] [{1}] Connected", idn, cmd); - m_pending = false; - } - m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms); - eventIrcJoin(pfx, cmd, parms); - break; - case "PART": - m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms); - eventIrcPart(pfx, cmd, parms); - break; - case "MODE": - m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms); - eventIrcMode(pfx, cmd, parms); - break; - case "NICK": - m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms); - eventIrcNickChange(pfx, cmd, parms); - break; - case "KICK": - m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms); - eventIrcKick(pfx, cmd, parms); - break; - case "QUIT": - m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms); - eventIrcQuit(pfx, cmd, parms); - break; - default : - m_log.DebugFormat("[IRC-Connector-{0}] Command '{1}' ignored, parms = {2}", idn, cmd, parms); - break; - } - - // m_log.DebugFormat("[IRC-Connector-{0}] prefix = <{1}> cmd = <{2}> complete", idn, pfx, cmd); - - } - - public void eventIrcJoin(string prefix, string command, string parms) - { - string[] args = parms.Split(CS_SPACE,2); - string IrcUser = prefix.Split('!')[0]; - string IrcChannel = args[0]; - - if (IrcChannel.StartsWith(":")) - IrcChannel = IrcChannel.Substring(1); - - m_log.DebugFormat("[IRC-Connector-{0}] Event: IRCJoin {1}:{2}", idn, m_server, m_ircChannel); - BroadcastSim(IrcUser, "/me joins {0}", IrcChannel); - } - - public void eventIrcPart(string prefix, string command, string parms) - { - string[] args = parms.Split(CS_SPACE,2); - string IrcUser = prefix.Split('!')[0]; - string IrcChannel = args[0]; - - m_log.DebugFormat("[IRC-Connector-{0}] Event: IRCPart {1}:{2}", idn, m_server, m_ircChannel); - BroadcastSim(IrcUser, "/me parts {0}", IrcChannel); - } - - public void eventIrcMode(string prefix, string command, string parms) - { - string[] args = parms.Split(CS_SPACE,2); - string UserMode = args[1]; - - m_log.DebugFormat("[IRC-Connector-{0}] Event: IRCMode {1}:{2}", idn, m_server, m_ircChannel); - if (UserMode.Substring(0, 1) == ":") - { - UserMode = UserMode.Remove(0, 1); - } - } - - public void eventIrcNickChange(string prefix, string command, string parms) - { - string[] args = parms.Split(CS_SPACE,2); - string UserOldNick = prefix.Split('!')[0]; - string UserNewNick = args[0].Remove(0, 1); - - m_log.DebugFormat("[IRC-Connector-{0}] Event: IRCNickChange {1}:{2}", idn, m_server, m_ircChannel); - BroadcastSim(UserOldNick, "/me is now known as {0}", UserNewNick); - } - - public void eventIrcKick(string prefix, string command, string parms) - { - string[] args = parms.Split(CS_SPACE,3); - string UserKicker = prefix.Split('!')[0]; - string IrcChannel = args[0]; - string UserKicked = args[1]; - string KickMessage = args[2]; - - m_log.DebugFormat("[IRC-Connector-{0}] Event: IRCKick {1}:{2}", idn, m_server, m_ircChannel); - BroadcastSim(UserKicker, "/me kicks kicks {0} off {1} saying \"{2}\"", UserKicked, IrcChannel, KickMessage); - - if (UserKicked == m_nick) - { - BroadcastSim(m_nick, "Hey, that was me!!!"); - } - - } - - public void eventIrcQuit(string prefix, string command, string parms) - { - string IrcUser = prefix.Split('!')[0]; - string QuitMessage = parms; - - m_log.DebugFormat("[IRC-Connector-{0}] Event: IRCQuit {1}:{2}", idn, m_server, m_ircChannel); - BroadcastSim(IrcUser, "/me quits saying \"{0}\"", QuitMessage); - } - - #endregion - - #region Connector Watch Dog - - // A single watch dog monitors extant connectors and makes sure that they - // are re-connected as necessary. If a connector IS connected, then it is - // pinged, but only if a PING period has elapsed. - - protected static void WatchdogHandler(Object source, ElapsedEventArgs args) - { - - // m_log.InfoFormat("[IRC-Watchdog] Status scan"); - - _pdk_ = (_pdk_+1)%PING_PERIOD; // cycle the ping trigger - _icc_++; // increment the inter-consecutive-connect-delay counter - - foreach (IRCConnector connector in m_connectors) - { - if (connector.Enabled) - { - if (!connector.Connected) - { - try - { - // m_log.DebugFormat("[IRC-Watchdog] Connecting {1}:{2}", connector.idn, connector.m_server, connector.m_ircChannel); - connector.Connect(); - } - catch (Exception e) - { - m_log.ErrorFormat("[IRC-Watchdog] Exception on connector {0}: {1} ", connector.idn, e.Message); - } - } - else - { - - if (connector.m_pending) - { - if (connector.m_timeout == 0) - { - m_log.ErrorFormat("[IRC-Watchdog] Login timed-out for connector {0}, reconnecting", connector.idn); - connector.Reconnect(); - } - else - connector.m_timeout--; - } - - if (_pdk_ == 0) - { - try - { - connector.m_writer.WriteLine(String.Format("PING :{0}", connector.m_server)); - connector.m_writer.Flush(); - } - catch (Exception /*e*/) - { - // m_log.ErrorFormat("[IRC-PingRun] Exception on connector {0}: {1} ", connector.idn, e.Message); - // m_log.Debug(e); - connector.Reconnect(); - } - } - - } - } - } - - // m_log.InfoFormat("[IRC-Watchdog] Status scan completed"); - - } - - #endregion - - } -} diff --git a/OpenSim/Region/Environment/Modules/Avatar/Chat/RegionState.cs b/OpenSim/Region/Environment/Modules/Avatar/Chat/RegionState.cs deleted file mode 100644 index 78f4265..0000000 --- a/OpenSim/Region/Environment/Modules/Avatar/Chat/RegionState.cs +++ /dev/null @@ -1,424 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using System.Reflection; -using System.Text.RegularExpressions; -using log4net; -using Nini.Config; -using OpenSim.Framework; -using OpenSim.Region.Framework.Interfaces; -using OpenSim.Region.Framework.Scenes; - -namespace OpenSim.Region.Environment.Modules.Avatar.Chat -{ - // An instance of this class exists for every active region - - internal class RegionState - { - - private static readonly ILog m_log = - LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private static readonly OpenMetaverse.Vector3 CenterOfRegion = new OpenMetaverse.Vector3(128, 128, 20); - private const int DEBUG_CHANNEL = 2147483647; - - private static int _idk_ = 0; - - // Runtime variables; these values are assigned when the - // IrcState is created and remain constant thereafter. - - internal string Region = String.Empty; - internal string Host = String.Empty; - internal string LocX = String.Empty; - internal string LocY = String.Empty; - internal string MA1 = String.Empty; - internal string MA2 = String.Empty; - internal string IDK = String.Empty; - - // System values - used only be the IRC classes themselves - - internal ChannelState cs = null; // associated IRC configuration - internal Scene scene = null; // associated scene - internal IConfig config = null; // configuration file reference - internal bool enabled = true; - - // This list is used to keep track of who is here, and by - // implication, who is not. - - internal List clients = new List(); - - // Setup runtime variable values - - public RegionState(Scene p_scene, IConfig p_config) - { - - scene = p_scene; - config = p_config; - - Region = scene.RegionInfo.RegionName; - Host = scene.RegionInfo.ExternalHostName; - LocX = Convert.ToString(scene.RegionInfo.RegionLocX); - LocY = Convert.ToString(scene.RegionInfo.RegionLocY); - MA1 = scene.RegionInfo.MasterAvatarFirstName; - MA2 = scene.RegionInfo.MasterAvatarLastName; - IDK = Convert.ToString(_idk_++); - - // OpenChannel conditionally establishes a connection to the - // IRC server. The request will either succeed, or it will - // throw an exception. - - ChannelState.OpenChannel(this, config); - - // Connect channel to world events - - scene.EventManager.OnChatFromWorld += OnSimChat; - scene.EventManager.OnChatFromClient += OnSimChat; - scene.EventManager.OnMakeRootAgent += OnMakeRootAgent; - scene.EventManager.OnMakeChildAgent += OnMakeChildAgent; - - m_log.InfoFormat("[IRC-Region {0}] Initialization complete", Region); - - } - - // Auto cleanup when abandoned - - ~RegionState() - { - if (cs != null) - cs.RemoveRegion(this); - } - - // Called by PostInitialize after all regions have been created - - public void Open() - { - cs.Open(this); - enabled = true; - } - - // Called by IRCBridgeModule.Close immediately prior to unload - // of the module for this region. This happens when the region - // is being removed or the server is terminating. The IRC - // BridgeModule will remove the region from the region list - // when control returns. - - public void Close() - { - enabled = false; - cs.Close(this); - } - - // The agent has disconnected, cleanup associated resources - - private void OnClientLoggedOut(IClientAPI client) - { - try - { - if (clients.Contains(client)) - { - if (enabled && (cs.irc.Enabled) && (cs.irc.Connected) && (cs.ClientReporting)) - { - m_log.InfoFormat("[IRC-Region {0}]: {1} has left", Region, client.Name); - cs.irc.PrivMsg(cs.NoticeMessageFormat, cs.irc.Nick, Region, String.Format("{0} has left", client.Name)); - } - client.OnLogout -= OnClientLoggedOut; - client.OnConnectionClosed -= OnClientLoggedOut; - clients.Remove(client); - } - } - catch (Exception ex) - { - m_log.ErrorFormat("[IRC-Region {0}]: ClientLoggedOut exception: {1}", Region, ex.Message); - m_log.Debug(ex); - } - } - - // This event indicates that the agent has left the building. We should treat that the same - // as if the agent has logged out (we don't want cross-region noise - or do we?) - - private void OnMakeChildAgent(ScenePresence presence) - { - - IClientAPI client = presence.ControllingClient; - - try - { - if (clients.Contains(client)) - { - if (enabled && (cs.irc.Enabled) && (cs.irc.Connected) && (cs.ClientReporting)) - { - string clientName = String.Format("{0} {1}", presence.Firstname, presence.Lastname); - m_log.DebugFormat("[IRC-Region {0}] {1} has left", Region, clientName); - cs.irc.PrivMsg(cs.NoticeMessageFormat, cs.irc.Nick, Region, String.Format("{0} has left", clientName)); - } - client.OnLogout -= OnClientLoggedOut; - client.OnConnectionClosed -= OnClientLoggedOut; - clients.Remove(client); - } - } - catch (Exception ex) - { - m_log.ErrorFormat("[IRC-Region {0}]: MakeChildAgent exception: {1}", Region, ex.Message); - m_log.Debug(ex); - } - - } - - // An agent has entered the region (from another region). Add the client to the locally - // known clients list - - private void OnMakeRootAgent(ScenePresence presence) - { - - IClientAPI client = presence.ControllingClient; - - try - { - if (!clients.Contains(client)) - { - client.OnLogout += OnClientLoggedOut; - client.OnConnectionClosed += OnClientLoggedOut; - clients.Add(client); - if (enabled && (cs.irc.Enabled) && (cs.irc.Connected) && (cs.ClientReporting)) - { - string clientName = String.Format("{0} {1}", presence.Firstname, presence.Lastname); - m_log.DebugFormat("[IRC-Region {0}] {1} has arrived", Region, clientName); - cs.irc.PrivMsg(cs.NoticeMessageFormat, cs.irc.Nick, Region, String.Format("{0} has arrived", clientName)); - } - } - } - catch (Exception ex) - { - m_log.ErrorFormat("[IRC-Region {0}]: MakeRootAgent exception: {1}", Region, ex.Message); - m_log.Debug(ex); - } - - } - - // This handler detects chat events int he virtual world. - - public void OnSimChat(Object sender, OSChatMessage msg) - { - - // early return if this comes from the IRC forwarder - - if (cs.irc.Equals(sender)) return; - - // early return if nothing to forward - - if (msg.Message.Length == 0) return; - - // check for commands coming from avatars or in-world - // object (if commands are enabled) - - if (cs.CommandsEnabled && msg.Channel == cs.CommandChannel) - { - - m_log.DebugFormat("[IRC-Region {0}] command on channel {1}: {2}", Region, msg.Channel, msg.Message); - - string[] messages = msg.Message.Split(' '); - string command = messages[0].ToLower(); - - try - { - switch (command) - { - - // These commands potentially require a change in the - // underlying ChannelState. - - case "server": - cs.Close(this); - cs = cs.UpdateServer(this, messages[1]); - cs.Open(this); - break; - case "port": - cs.Close(this); - cs = cs.UpdatePort(this, messages[1]); - cs.Open(this); - break; - case "channel": - cs.Close(this); - cs = cs.UpdateChannel(this, messages[1]); - cs.Open(this); - break; - case "nick": - cs.Close(this); - cs = cs.UpdateNickname(this, messages[1]); - cs.Open(this); - break; - - // These may also (but are less likely) to require a - // change in ChannelState. - - case "client-reporting": - cs = cs.UpdateClientReporting(this, messages[1]); - break; - case "in-channel": - cs = cs.UpdateRelayIn(this, messages[1]); - break; - case "out-channel": - cs = cs.UpdateRelayOut(this, messages[1]); - break; - - // These are all taken to be temporary changes in state - // so the underlying connector remains intact. But note - // that with regions sharing a connector, there could - // be interference. - - case "close": - enabled = false; - cs.Close(this); - break; - - case "connect": - enabled = true; - cs.Open(this); - break; - - case "reconnect": - enabled = true; - cs.Close(this); - cs.Open(this); - break; - - // This one is harmless as far as we can judge from here. - // If it is not, then the complaints will eventually make - // that evident. - - default: - m_log.DebugFormat("[IRC-Region {0}] Forwarding unrecognized command to IRC : {1}", - Region, msg.Message); - cs.irc.Send(msg.Message); - break; - } - } - catch (Exception ex) - { - m_log.WarnFormat("[IRC-Region {0}] error processing in-world command channel input: {1}", - Region, ex.Message); - m_log.Debug(ex); - } - - return; - - } - - // The command channel remains enabled, even if we have otherwise disabled the IRC - // interface. - - if (!enabled) - return; - - // drop messages unless they are on a valid in-world - // channel as configured in the ChannelState - - if (!cs.ValidInWorldChannels.Contains(msg.Channel)) - { - m_log.DebugFormat("[IRC-Region {0}] dropping message {1} on channel {2}", Region, msg, msg.Channel); - return; - } - - ScenePresence avatar = null; - string fromName = msg.From; - - if (msg.Sender != null) - { - avatar = scene.GetScenePresence(msg.Sender.AgentId); - if (avatar != null) fromName = avatar.Name; - } - - if (!cs.irc.Connected) - { - m_log.WarnFormat("[IRC-Region {0}] IRCConnector not connected: dropping message from {1}", Region, fromName); - return; - } - - m_log.DebugFormat("[IRC-Region {0}] heard on channel {1} : {2}", Region, msg.Channel, msg.Message); - - if (null != avatar && cs.RelayChat && (msg.Channel == 0 || msg.Channel == DEBUG_CHANNEL)) - { - string txt = msg.Message; - if (txt.StartsWith("/me ")) - txt = String.Format("{0} {1}", fromName, msg.Message.Substring(4)); - - cs.irc.PrivMsg(cs.PrivateMessageFormat, fromName, Region, txt); - return; - } - - if (null == avatar && cs.RelayPrivateChannels && null != cs.AccessPassword && - msg.Channel == cs.RelayChannelOut) - { - Match m = cs.AccessPasswordRegex.Match(msg.Message); - if (null != m) - { - m_log.DebugFormat("[IRC] relaying message from {0}: {1}", m.Groups["avatar"].ToString(), - m.Groups["message"].ToString()); - cs.irc.PrivMsg(cs.PrivateMessageFormat, m.Groups["avatar"].ToString(), - scene.RegionInfo.RegionName, m.Groups["message"].ToString()); - } - } - } - - // This method gives the region an opportunity to interfere with - // message delivery. For now we just enforce the enable/disable - // flag. - - internal void OSChat(Object irc, OSChatMessage msg) - { - if (enabled) - { - // m_log.DebugFormat("[IRC-OSCHAT] Region {0} being sent message", region.Region); - msg.Scene = scene; - scene.EventManager.TriggerOnChatBroadcast(irc, msg); - } - } - - // This supports any local message traffic that might be needed in - // support of command processing. At present there is none. - - internal void LocalChat(string msg) - { - if (enabled) - { - OSChatMessage osm = new OSChatMessage(); - osm.From = "IRC Agent"; - osm.Message = msg; - osm.Type = ChatTypeEnum.Region; - osm.Position = CenterOfRegion; - osm.Sender = null; - osm.SenderUUID = OpenMetaverse.UUID.Zero; // Hmph! Still? - osm.Channel = 0; - OSChat(this, osm); - } - } - - } - -} diff --git a/OpenSim/Region/Environment/Modules/Avatar/Combat/CombatModule.cs b/OpenSim/Region/Environment/Modules/Avatar/Combat/CombatModule.cs deleted file mode 100644 index f032319..0000000 --- a/OpenSim/Region/Environment/Modules/Avatar/Combat/CombatModule.cs +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Net; -using System.Net.Sockets; -using System.Reflection; -using System.Xml; -using OpenMetaverse; -using log4net; -using Nini.Config; -using Nwc.XmlRpc; -using OpenSim.Framework; -using OpenSim.Region.Framework.Interfaces; -using OpenSim.Region.Framework.Scenes; -using OpenSim.Framework.Communications.Cache; - -namespace OpenSim.Region.Environment.Modules.Avatar.Combat.CombatModule -{ - public class CombatModule : IRegionModule - { - //private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - /// - /// Region UUIDS indexed by AgentID - /// - //private Dictionary m_rootAgents = new Dictionary(); - - /// - /// Scenes by Region Handle - /// - private Dictionary m_scenel = new Dictionary(); - - /// - /// Startup - /// - /// - /// - public void Initialise(Scene scene, IConfigSource config) - { - lock (m_scenel) - { - if (m_scenel.ContainsKey(scene.RegionInfo.RegionHandle)) - { - m_scenel[scene.RegionInfo.RegionHandle] = scene; - } - else - { - m_scenel.Add(scene.RegionInfo.RegionHandle, scene); - } - } - - scene.EventManager.OnAvatarKilled += KillAvatar; - } - - public void PostInitialise() - { - } - - public void Close() - { - } - - public string Name - { - get { return "CombatModule"; } - } - - public bool IsSharedModule - { - get { return true; } - } - - private void KillAvatar(uint killerObjectLocalID, ScenePresence DeadAvatar) - { - if (killerObjectLocalID == 0) - DeadAvatar.ControllingClient.SendAgentAlertMessage("You committed suicide!", true); - else - { - bool foundResult = false; - string resultstring = ""; - List allav = DeadAvatar.Scene.GetScenePresences(); - try - { - foreach (ScenePresence av in allav) - { - if (av.LocalId == killerObjectLocalID) - { - av.ControllingClient.SendAlertMessage("You fragged " + DeadAvatar.Firstname + " " + DeadAvatar.Lastname); - resultstring = av.Firstname + " " + av.Lastname; - foundResult = true; - } - } - } catch (System.InvalidOperationException) - { - - } - - if (!foundResult) - { - SceneObjectPart part = DeadAvatar.Scene.GetSceneObjectPart(killerObjectLocalID); - if (part != null) - { - ScenePresence av = DeadAvatar.Scene.GetScenePresence(part.OwnerID); - if (av != null) - { - av.ControllingClient.SendAlertMessage("You fragged " + DeadAvatar.Firstname + " " + DeadAvatar.Lastname); - resultstring = av.Firstname + " " + av.Lastname; - DeadAvatar.ControllingClient.SendAgentAlertMessage("You got killed by " + resultstring + "!", true); - } - else - { - string killer = DeadAvatar.Scene.CommsManager.UUIDNameRequestString(part.OwnerID); - DeadAvatar.ControllingClient.SendAgentAlertMessage("You impaled yourself on " + part.Name + " owned by " + killer +"!", true); - } - //DeadAvatar.Scene. part.ObjectOwner - } - else - { - DeadAvatar.ControllingClient.SendAgentAlertMessage("You died!", true); - } - } - } - DeadAvatar.Health = 100; - DeadAvatar.Scene.TeleportClientHome(DeadAvatar.UUID, DeadAvatar.ControllingClient); - } - } -} diff --git a/OpenSim/Region/Environment/Modules/Avatar/Concierge/ConciergeModule.cs b/OpenSim/Region/Environment/Modules/Avatar/Concierge/ConciergeModule.cs deleted file mode 100644 index 5ac5dbe..0000000 --- a/OpenSim/Region/Environment/Modules/Avatar/Concierge/ConciergeModule.cs +++ /dev/null @@ -1,604 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Net; -using System.Net.Sockets; -using System.Reflection; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading; -using log4net; -using Nini.Config; -using Nwc.XmlRpc; -using OpenMetaverse; -using OpenSim.Framework; -using OpenSim.Framework.Servers; -using OpenSim.Region.Framework.Interfaces; -using OpenSim.Region.Framework.Scenes; -using OpenSim.Region.Environment.Modules.Avatar.Chat; - -namespace OpenSim.Region.Environment.Modules.Avatar.Concierge -{ - public class ConciergeModule : ChatModule, IRegionModule - { - private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private const int DEBUG_CHANNEL = 2147483647; - - private List _scenes = new List(); - private List _conciergedScenes = new List(); - private Dictionary> _sceneAttendees = - new Dictionary>(); - private Dictionary _attendeeNames = - new Dictionary(); - - private bool _replacingChatModule = false; - - private IConfig _config; - - private string _whoami = "conferencier"; - private Regex _regions = null; - private string _welcomes = null; - private int _conciergeChannel = 42; - private string _announceEntering = "{0} enters {1} (now {2} visitors in this region)"; - private string _announceLeaving = "{0} leaves {1} (back to {2} visitors in this region)"; - private string _xmlRpcPassword = String.Empty; - private string _brokerURI = String.Empty; - - internal object _syncy = new object(); - - #region IRegionModule Members - public override void Initialise(Scene scene, IConfigSource config) - { - try - { - if ((_config = config.Configs["Concierge"]) == null) - { - //_log.InfoFormat("[Concierge]: no configuration section [Concierge] in OpenSim.ini: module not configured"); - return; - } - - if (!_config.GetBoolean("enabled", false)) - { - //_log.InfoFormat("[Concierge]: module disabled by OpenSim.ini configuration"); - return; - } - } - catch (Exception) - { - _log.Info("[Concierge]: module not configured"); - return; - } - - // check whether ChatModule has been disabled: if yes, - // then we'll "stand in" - try - { - if (config.Configs["Chat"] == null) - { - _replacingChatModule = false; - } - else - { - _replacingChatModule = !config.Configs["Chat"].GetBoolean("enabled", true); - } - } - catch (Exception) - { - _replacingChatModule = false; - } - _log.InfoFormat("[Concierge] {0} ChatModule", _replacingChatModule ? "replacing" : "not replacing"); - - - // take note of concierge channel and of identity - _conciergeChannel = config.Configs["Concierge"].GetInt("concierge_channel", _conciergeChannel); - _whoami = _config.GetString("whoami", "conferencier"); - _welcomes = _config.GetString("welcomes", _welcomes); - _announceEntering = _config.GetString("announce_entering", _announceEntering); - _announceLeaving = _config.GetString("announce_leaving", _announceLeaving); - _xmlRpcPassword = _config.GetString("password", _xmlRpcPassword); - _brokerURI = _config.GetString("broker", _brokerURI); - - _log.InfoFormat("[Concierge] reporting as \"{0}\" to our users", _whoami); - - // calculate regions Regex - if (_regions == null) - { - string regions = _config.GetString("regions", String.Empty); - if (!String.IsNullOrEmpty(regions)) - { - _regions = new Regex(@regions, RegexOptions.Compiled | RegexOptions.IgnoreCase); - } - } - - scene.CommsManager.HttpServer.AddXmlRPCHandler("concierge_update_welcome", XmlRpcUpdateWelcomeMethod, false); - - lock (_syncy) - { - if (!_scenes.Contains(scene)) - { - _scenes.Add(scene); - - if (_regions == null || _regions.IsMatch(scene.RegionInfo.RegionName)) - _conciergedScenes.Add(scene); - - // subscribe to NewClient events - scene.EventManager.OnNewClient += OnNewClient; - - // subscribe to *Chat events - scene.EventManager.OnChatFromWorld += OnChatFromWorld; - if (!_replacingChatModule) - scene.EventManager.OnChatFromClient += OnChatFromClient; - scene.EventManager.OnChatBroadcast += OnChatBroadcast; - - // subscribe to agent change events - scene.EventManager.OnMakeRootAgent += OnMakeRootAgent; - scene.EventManager.OnMakeChildAgent += OnMakeChildAgent; - } - } - _log.InfoFormat("[Concierge]: initialized for {0}", scene.RegionInfo.RegionName); - } - - public override void PostInitialise() - { - } - - public override void Close() - { - } - - public override string Name - { - get { return "ConciergeModule"; } - } - - public override bool IsSharedModule - { - get { return true; } - } - - #endregion - - #region ISimChat Members - public override void OnChatBroadcast(Object sender, OSChatMessage c) - { - if (_replacingChatModule) - { - // distribute chat message to each and every avatar in - // the region - base.OnChatBroadcast(sender, c); - } - - // TODO: capture logic - return; - } - - public override void OnChatFromClient(Object sender, OSChatMessage c) - { - if (_replacingChatModule) - { - // replacing ChatModule: need to redistribute - // ChatFromClient to interested subscribers - c = FixPositionOfChatMessage(c); - - Scene scene = (Scene)c.Scene; - scene.EventManager.TriggerOnChatFromClient(sender, c); - - if (_conciergedScenes.Contains(c.Scene)) - { - // when we are replacing ChatModule, we treat - // OnChatFromClient like OnChatBroadcast for - // concierged regions, effectively extending the - // range of chat to cover the whole - // region. however, we don't do this for whisper - // (got to have some privacy) - if (c.Type != ChatTypeEnum.Whisper) - { - base.OnChatBroadcast(sender, c); - return; - } - } - - // redistribution will be done by base class - base.OnChatFromClient(sender, c); - } - - // TODO: capture chat - return; - } - - public override void OnChatFromWorld(Object sender, OSChatMessage c) - { - if (_replacingChatModule) - { - if (_conciergedScenes.Contains(c.Scene)) - { - // when we are replacing ChatModule, we treat - // OnChatFromClient like OnChatBroadcast for - // concierged regions, effectively extending the - // range of chat to cover the whole - // region. however, we don't do this for whisper - // (got to have some privacy) - if (c.Type != ChatTypeEnum.Whisper) - { - base.OnChatBroadcast(sender, c); - return; - } - } - - base.OnChatFromWorld(sender, c); - } - return; - } - #endregion - - - public override void OnNewClient(IClientAPI client) - { - client.OnLogout += OnClientLoggedOut; - - if (_replacingChatModule) - client.OnChatFromClient += OnChatFromClient; - } - - - - public void OnClientLoggedOut(IClientAPI client) - { - client.OnLogout -= OnClientLoggedOut; - client.OnConnectionClosed -= OnClientLoggedOut; - - if (_conciergedScenes.Contains(client.Scene)) - { - _log.DebugFormat("[Concierge]: {0} logs off from {1}", client.Name, client.Scene.RegionInfo.RegionName); - RemoveFromAttendeeList(client.AgentId, client.Name, client.Scene); - AnnounceToAgentsRegion(client.Scene, String.Format(_announceLeaving, client.Name, client.Scene.RegionInfo.RegionName, - _sceneAttendees[client.Scene].Count)); - UpdateBroker(client.Scene); - } - } - - - public void OnMakeRootAgent(ScenePresence agent) - { - if (_conciergedScenes.Contains(agent.Scene)) - { - _log.DebugFormat("[Concierge]: {0} enters {1}", agent.Name, agent.Scene.RegionInfo.RegionName); - AddToAttendeeList(agent.UUID, agent.Name, agent.Scene); - WelcomeAvatar(agent, agent.Scene); - AnnounceToAgentsRegion(agent.Scene, String.Format(_announceEntering, agent.Name, agent.Scene.RegionInfo.RegionName, - _sceneAttendees[agent.Scene].Count)); - UpdateBroker(agent.Scene); - } - } - - - public void OnMakeChildAgent(ScenePresence agent) - { - if (_conciergedScenes.Contains(agent.Scene)) - { - _log.DebugFormat("[Concierge]: {0} leaves {1}", agent.Name, agent.Scene.RegionInfo.RegionName); - RemoveFromAttendeeList(agent.UUID, agent.Name, agent.Scene); - AnnounceToAgentsRegion(agent.Scene, String.Format(_announceLeaving, agent.Name, agent.Scene.RegionInfo.RegionName, - _sceneAttendees[agent.Scene].Count)); - UpdateBroker(agent.Scene); - } - } - - protected void AddToAttendeeList(UUID agentID, string name, Scene scene) - { - lock (_sceneAttendees) - { - if (!_sceneAttendees.ContainsKey(scene)) - _sceneAttendees[scene] = new List(); - - List attendees = _sceneAttendees[scene]; - if (!attendees.Contains(agentID)) - { - attendees.Add(agentID); - _attendeeNames[agentID] = name; - } - } - } - - protected void RemoveFromAttendeeList(UUID agentID, String name, IScene scene) - { - lock (_sceneAttendees) - { - if (!_sceneAttendees.ContainsKey(scene)) - { - _log.WarnFormat("[Concierge]: attendee list missing for region {0}", scene.RegionInfo.RegionName); - return; - } - - List attendees = _sceneAttendees[scene]; - if (!attendees.Contains(agentID)) - { - _log.WarnFormat("[Concierge]: avatar {0} must have sneaked in to region {1} earlier", - name, scene.RegionInfo.RegionName); - return; - } - - attendees.Remove(agentID); - _attendeeNames.Remove(agentID); - } - } - - protected void UpdateBroker(IScene scene) - { - if (String.IsNullOrEmpty(_brokerURI)) - return; - - string uri = String.Format(_brokerURI, scene.RegionInfo.RegionName, scene.RegionInfo.RegionID); - - // get attendee list for the scene - List attendees; - lock (_sceneAttendees) - { - if (!_sceneAttendees.ContainsKey(scene)) - { - _log.DebugFormat("[Concierge]: attendee list missing for region {0}", scene.RegionInfo.RegionName); - return; - } - - attendees = _sceneAttendees[scene]; - } - - // create XML sniplet - StringBuilder list = new StringBuilder(); - if (0 == attendees.Count) - { - list.Append(String.Format("", - scene.RegionInfo.RegionName, scene.RegionInfo.RegionID, - DateTime.UtcNow.ToString("s"))); - } - else - { - list.Append(String.Format("\n", - attendees.Count, scene.RegionInfo.RegionName, - scene.RegionInfo.RegionID, - DateTime.UtcNow.ToString("s"))); - foreach (UUID uuid in attendees) - { - string name = _attendeeNames[uuid]; - list.Append(String.Format(" \n", name, uuid)); - } - list.Append(""); - } - string payload = list.ToString(); - - // post via REST to broker - HttpWebRequest updatePost = WebRequest.Create(uri) as HttpWebRequest; - updatePost.Method = "POST"; - updatePost.ContentType = "text/xml"; - updatePost.ContentLength = payload.Length; - updatePost.UserAgent = "OpenSim.Concierge"; - - try - { - StreamWriter payloadStream = new StreamWriter(updatePost.GetRequestStream()); - payloadStream.Write(payload); - payloadStream.Close(); - - updatePost.BeginGetResponse(UpdateBrokerDone, updatePost); - _log.DebugFormat("[Concierge] async broker POST to {0} started", uri); - } - catch (WebException we) - { - _log.ErrorFormat("[Concierge] async broker POST to {0} failed: {1}", uri, we.Status); - } - } - - private void UpdateBrokerDone(IAsyncResult result) - { - HttpWebRequest updatePost = null; - try - { - updatePost = result.AsyncState as HttpWebRequest; - using (HttpWebResponse response = updatePost.EndGetResponse(result) as HttpWebResponse) - { - _log.DebugFormat("[Concierge] broker update: status {0}", response.StatusCode); - } - } - catch (WebException we) - { - string uri = updatePost.RequestUri.OriginalString; - _log.ErrorFormat("[Concierge] broker update to {0} failed with status {1}", uri, we.Status); - if (null != we.Response) - { - using (HttpWebResponse resp = we.Response as HttpWebResponse) - { - _log.ErrorFormat("[Concierge] response from {0} status code: {1}", uri, resp.StatusCode); - _log.ErrorFormat("[Concierge] response from {0} status desc: {1}", uri, resp.StatusDescription); - _log.ErrorFormat("[Concierge] response from {0} server: {1}", uri, resp.Server); - - if (resp.ContentLength > 0) - { - StreamReader content = new StreamReader(resp.GetResponseStream()); - _log.ErrorFormat("[Concierge] response from {0} content: {1}", uri, content.ReadToEnd()); - content.Close(); - } - } - } - } - } - - protected void WelcomeAvatar(ScenePresence agent, Scene scene) - { - // welcome mechanics: check whether we have a welcomes - // directory set and wether there is a region specific - // welcome file there: if yes, send it to the agent - if (!String.IsNullOrEmpty(_welcomes)) - { - string[] welcomes = new string[] { - Path.Combine(_welcomes, agent.Scene.RegionInfo.RegionName), - Path.Combine(_welcomes, "DEFAULT")}; - foreach (string welcome in welcomes) - { - if (File.Exists(welcome)) - { - try - { - string[] welcomeLines = File.ReadAllLines(welcome); - foreach (string l in welcomeLines) - { - AnnounceToAgent(agent, String.Format(l, agent.Name, scene.RegionInfo.RegionName, _whoami)); - } - } - catch (IOException ioe) - { - _log.ErrorFormat("[Concierge]: run into trouble reading welcome file {0} for region {1} for avatar {2}: {3}", - welcome, scene.RegionInfo.RegionName, agent.Name, ioe); - } - catch (FormatException fe) - { - _log.ErrorFormat("[Concierge]: welcome file {0} is malformed: {1}", welcome, fe); - } - } - return; - } - _log.DebugFormat("[Concierge]: no welcome message for region {0}", scene.RegionInfo.RegionName); - } - } - - static private Vector3 PosOfGod = new Vector3(128, 128, 9999); - - // protected void AnnounceToAgentsRegion(Scene scene, string msg) - // { - // ScenePresence agent = null; - // if ((client.Scene is Scene) && (client.Scene as Scene).TryGetAvatar(client.AgentId, out agent)) - // AnnounceToAgentsRegion(agent, msg); - // else - // _log.DebugFormat("[Concierge]: could not find an agent for client {0}", client.Name); - // } - - protected void AnnounceToAgentsRegion(IScene scene, string msg) - { - OSChatMessage c = new OSChatMessage(); - c.Message = msg; - c.Type = ChatTypeEnum.Say; - c.Channel = 0; - c.Position = PosOfGod; - c.From = _whoami; - c.Sender = null; - c.SenderUUID = UUID.Zero; - c.Scene = scene; - - if (scene is Scene) - (scene as Scene).EventManager.TriggerOnChatBroadcast(this, c); - } - - protected void AnnounceToAgent(ScenePresence agent, string msg) - { - OSChatMessage c = new OSChatMessage(); - c.Message = msg; - c.Type = ChatTypeEnum.Say; - c.Channel = 0; - c.Position = PosOfGod; - c.From = _whoami; - c.Sender = null; - c.SenderUUID = UUID.Zero; - c.Scene = agent.Scene; - - agent.ControllingClient.SendChatMessage(msg, (byte) ChatTypeEnum.Say, PosOfGod, _whoami, UUID.Zero, - (byte)ChatSourceType.Object, (byte)ChatAudibleLevel.Fully); - } - - private static void checkStringParameters(XmlRpcRequest request, string[] param) - { - Hashtable requestData = (Hashtable) request.Params[0]; - foreach (string p in param) - { - if (!requestData.Contains(p)) - throw new Exception(String.Format("missing string parameter {0}", p)); - if (String.IsNullOrEmpty((string)requestData[p])) - throw new Exception(String.Format("parameter {0} is empty", p)); - } - } - - public XmlRpcResponse XmlRpcUpdateWelcomeMethod(XmlRpcRequest request) - { - _log.Info("[Concierge]: processing UpdateWelcome request"); - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable responseData = new Hashtable(); - - try - { - Hashtable requestData = (Hashtable)request.Params[0]; - checkStringParameters(request, new string[] { "password", "region", "welcome" }); - - // check password - if (!String.IsNullOrEmpty(_xmlRpcPassword) && - (string)requestData["password"] != _xmlRpcPassword) throw new Exception("wrong password"); - - if (String.IsNullOrEmpty(_welcomes)) - throw new Exception("welcome templates are not enabled, ask your OpenSim operator to set the \"welcomes\" option in the [Concierge] section of OpenSim.ini"); - - string msg = (string)requestData["welcome"]; - if (String.IsNullOrEmpty(msg)) - throw new Exception("empty parameter \"welcome\""); - - string regionName = (string)requestData["region"]; - IScene scene = _scenes.Find(delegate(IScene s) { return s.RegionInfo.RegionName == regionName; }); - if (scene == null) - throw new Exception(String.Format("unknown region \"{0}\"", regionName)); - - if (!_conciergedScenes.Contains(scene)) - throw new Exception(String.Format("region \"{0}\" is not a concierged region.", regionName)); - - string welcome = Path.Combine(_welcomes, regionName); - if (File.Exists(welcome)) - { - _log.InfoFormat("[Concierge]: UpdateWelcome: updating existing template \"{0}\"", welcome); - string welcomeBackup = String.Format("{0}~", welcome); - if (File.Exists(welcomeBackup)) - File.Delete(welcomeBackup); - File.Move(welcome, welcomeBackup); - } - File.WriteAllText(welcome, msg); - - responseData["success"] = "true"; - response.Value = responseData; - } - catch (Exception e) - { - _log.InfoFormat("[Concierge]: UpdateWelcome failed: {0}", e.Message); - - responseData["success"] = "false"; - responseData["error"] = e.Message; - - response.Value = responseData; - } - _log.Debug("[Concierge]: done processing UpdateWelcome request"); - return response; - } - } -} diff --git a/OpenSim/Region/Environment/Modules/Avatar/Concierge/ConciergeServer.py b/OpenSim/Region/Environment/Modules/Avatar/Concierge/ConciergeServer.py deleted file mode 100755 index 1c088fb..0000000 --- a/OpenSim/Region/Environment/Modules/Avatar/Concierge/ConciergeServer.py +++ /dev/null @@ -1,130 +0,0 @@ -#!/usr/bin/env python -# -*- encoding: utf-8 -*- -# -# Copyright (c) Contributors, http://opensimulator.org/ -# See CONTRIBUTORS.TXT for a full list of copyright holders. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# * Neither the name of the OpenSim Project nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# - -import logging -import BaseHTTPServer -import optparse -import xml.etree.ElementTree as ET -import xml.parsers.expat - - -# enable debug level logging -logging.basicConfig(level = logging.DEBUG, - format='%(asctime)s %(levelname)s %(message)s') - -options = None - -# subclassed HTTPRequestHandler -class ConciergeHandler(BaseHTTPServer.BaseHTTPRequestHandler): - def logRequest(self): - logging.info('[ConciergeHandler] %(command)s request: %(host)s:%(port)d --- %(path)s', - dict(command = self.command, - host = self.client_address[0], - port = self.client_address[1], - path = self.path)) - - def logResponse(self, status): - logging.info('[ConciergeHandler] %(command)s returned %(status)d', - dict(command = self.command, - status = status)) - - - def do_HEAD(self): - self.logRequest() - - self.send_response(200) - self.send_header('Content-type', 'text/html') - self.end_headers() - - self.logResponse(200) - - def dumpXml(self, xml): - logging.debug('[ConciergeHandler] %s', xml.tag) - for attr in xml.attrib: - logging.debug('[ConciergeHandler] %s [%s] %s', xml.tag, attr, xml.attrib[attr]) - for kid in xml.getchildren(): - self.dumpXml(kid) - - def do_POST(self): - self.logRequest() - hdrs = {} - for hdr in self.headers.headers: - logging.debug('[ConciergeHandler] POST: header: %s', hdr.rstrip()) - - length = int(self.headers.getheader('Content-Length')) - content = self.rfile.read(length) - self.rfile.close() - - logging.debug('[ConciergeHandler] POST: content: %s', content) - try: - postXml = ET.fromstring(content) - self.dumpXml(postXml) - except xml.parsers.expat.ExpatError, xmlError: - logging.error('[ConciergeHandler] POST illformed:%s', xmlError) - self.send_response(500) - return - - if not options.fail: - self.send_response(200) - self.send_header('Content-Type', 'text/html') - self.send_header('Content-Length', len('')) - self.end_headers() - self.logResponse(200) - self.wfile.write('') - self.wfile.close() - else: - self.send_response(500) - self.send_header('Content-Type', 'text/html') - self.send_header('Content-Length', len('gotcha!')) - self.end_headers() - self.wfile.write('gotcha!') - self.wfile.close() - - self.logResponse(500) - - def log_request(code, size): - pass - -if __name__ == '__main__': - - logging.info('[ConciergeServer] Concierge Broker Test Server starting') - - parser = optparse.OptionParser() - parser.add_option('-p', '--port', dest = 'port', help = 'port to listen on', metavar = 'PORT') - parser.add_option('-f', '--fail', dest = 'fail', action = 'store_true', help = 'always fail POST requests') - - (options, args) = parser.parse_args() - - httpServer = BaseHTTPServer.HTTPServer(('', 8080), ConciergeHandler) - try: - httpServer.serve_forever() - except KeyboardInterrupt: - logging.info('[ConciergeServer] terminating') - - httpServer.server_close() diff --git a/OpenSim/Region/Environment/Modules/Avatar/Currency/SampleMoney/SampleMoneyModule.cs b/OpenSim/Region/Environment/Modules/Avatar/Currency/SampleMoney/SampleMoneyModule.cs deleted file mode 100644 index 1ec5e9b..0000000 --- a/OpenSim/Region/Environment/Modules/Avatar/Currency/SampleMoney/SampleMoneyModule.cs +++ /dev/null @@ -1,1605 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Net; -using System.Net.Sockets; -using System.Reflection; -using System.Xml; -using log4net; -using Nini.Config; -using Nwc.XmlRpc; -using OpenMetaverse; -using OpenSim.Framework; -using OpenSim.Framework.Communications.Cache; -using OpenSim.Framework.Servers; -using OpenSim.Region.Framework.Interfaces; -using OpenSim.Region.Framework.Scenes; - -namespace OpenSim.Region.Environment.Modules.Avatar.Currency.SampleMoney -{ - /// - /// Demo Economy/Money Module. This is not a production quality money/economy module! - /// This is a demo for you to use when making one that works for you. - /// // To use the following you need to add: - /// -helperuri
- /// to the command line parameters you use to start up your client - /// This commonly looks like -helperuri http://127.0.0.1:9000/ - /// - /// Centralized grid structure example using OpenSimWi Redux revision 9+ - /// svn co https://opensimwiredux.svn.sourceforge.net/svnroot/opensimwiredux - ///
- public class SampleMoneyModule : IMoneyModule, IRegionModule - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - /// - /// Where Stipends come from and Fees go to. - /// - // private UUID EconomyBaseAccount = UUID.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; - - /// - /// Region UUIDS indexed by AgentID - /// - private Dictionary m_rootAgents = new Dictionary(); - - /// - /// Scenes by Region Handle - /// - private Dictionary m_scenel = new Dictionary(); - - private int m_stipend = 1000; - - private int ObjectCapacity = 45000; - private int ObjectCount = 0; - private int PriceEnergyUnit = 0; - private int PriceGroupCreate = 0; - private int PriceObjectClaim = 0; - private float PriceObjectRent = 0f; - private float PriceObjectScaleFactor = 0f; - private int PriceParcelClaim = 0; - private float PriceParcelClaimFactor = 0f; - private int PriceParcelRent = 0; - private int PricePublicObjectDecay = 0; - private int PricePublicObjectDelete = 0; - private int PriceRentLight = 0; - private int PriceUpload = 0; - private int TeleportMinPrice = 0; - - private float TeleportPriceExponent = 0f; - // private int UserLevelPaysFees = 2; - // private Scene XMLRPCHandler; - - #region IMoneyModule Members - - public event ObjectPaid OnObjectPaid; - - /// - /// Startup - /// - /// - /// - public void Initialise(Scene scene, IConfigSource config) - { - m_gConfig = config; - - IConfig startupConfig = m_gConfig.Configs["Startup"]; - IConfig economyConfig = m_gConfig.Configs["Economy"]; - - - ReadConfigAndPopulate(scene, startupConfig, "Startup"); - ReadConfigAndPopulate(scene, economyConfig, "Economy"); - - if (m_enabled) - { - scene.RegisterModuleInterface(this); - BaseHttpServer httpServer = scene.CommsManager.HttpServer; - - lock (m_scenel) - { - if (m_scenel.Count == 0) - { - // XMLRPCHandler = scene; - - // To use the following you need to add: - // -helperuri
- // to the command line parameters you use to start up your client - // This commonly looks like -helperuri http://127.0.0.1:9000/ - - if (m_MoneyAddress.Length > 0) - { - // Centralized grid structure using OpenSimWi Redux revision 9+ - // https://opensimwiredux.svn.sourceforge.net/svnroot/opensimwiredux - httpServer.AddXmlRPCHandler("balanceUpdateRequest", GridMoneyUpdate); - httpServer.AddXmlRPCHandler("userAlert", UserAlert); - } - else - { - // Local Server.. enables functionality only. - httpServer.AddXmlRPCHandler("getCurrencyQuote", quote_func); - httpServer.AddXmlRPCHandler("buyCurrency", buy_func); - httpServer.AddXmlRPCHandler("preflightBuyLandPrep", preflightBuyLandPrep_func); - httpServer.AddXmlRPCHandler("buyLandPrep", landBuy_func); - } - } - - if (m_scenel.ContainsKey(scene.RegionInfo.RegionHandle)) - { - m_scenel[scene.RegionInfo.RegionHandle] = scene; - } - else - { - m_scenel.Add(scene.RegionInfo.RegionHandle, scene); - } - } - - scene.EventManager.OnNewClient += OnNewClient; - scene.EventManager.OnMoneyTransfer += MoneyTransferAction; - scene.EventManager.OnClientClosed += ClientClosed; - scene.EventManager.OnAvatarEnteringNewParcel += AvatarEnteringParcel; - scene.EventManager.OnMakeChildAgent += MakeChildAgent; - scene.EventManager.OnClientClosed += ClientLoggedOut; - scene.EventManager.OnValidateLandBuy += ValidateLandBuy; - scene.EventManager.OnLandBuy += processLandBuy; - } - } - - // Please do not refactor these to be just one method - // Existing implementations need the distinction - // - public void ApplyUploadCharge(UUID agentID) - { - } - - public void ApplyGroupCreationCharge(UUID agentID) - { - } - - public void ApplyCharge(UUID agentID, int amount, string text) - { - } - - public bool ObjectGiveMoney(UUID objectID, UUID fromID, UUID 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 - /// - /// - /// - /// - private void ReadConfigAndPopulate(Scene scene, IConfig startupConfig, string config) - { - if (config == "Startup" && startupConfig != null) - { - gridmode = startupConfig.GetBoolean("gridmode", false); - m_enabled = (startupConfig.GetString("economymodule", "BetaGridLikeMoneyModule") == "BetaGridLikeMoneyModule"); - } - - if (config == "Economy" && startupConfig != null) - { - ObjectCapacity = startupConfig.GetInt("ObjectCapacity", 45000); - PriceEnergyUnit = startupConfig.GetInt("PriceEnergyUnit", 100); - PriceObjectClaim = startupConfig.GetInt("PriceObjectClaim", 10); - PricePublicObjectDecay = startupConfig.GetInt("PricePublicObjectDecay", 4); - PricePublicObjectDelete = startupConfig.GetInt("PricePublicObjectDelete", 4); - PriceParcelClaim = startupConfig.GetInt("PriceParcelClaim", 1); - PriceParcelClaimFactor = startupConfig.GetFloat("PriceParcelClaimFactor", 1f); - PriceUpload = startupConfig.GetInt("PriceUpload", 0); - PriceRentLight = startupConfig.GetInt("PriceRentLight", 5); - TeleportMinPrice = startupConfig.GetInt("TeleportMinPrice", 2); - TeleportPriceExponent = startupConfig.GetFloat("TeleportPriceExponent", 2f); - EnergyEfficiency = startupConfig.GetFloat("EnergyEfficiency", 1); - PriceObjectRent = startupConfig.GetFloat("PriceObjectRent", 1); - PriceObjectScaleFactor = startupConfig.GetFloat("PriceObjectScaleFactor", 10); - PriceParcelRent = startupConfig.GetInt("PriceParcelRent", 1); - PriceGroupCreate = startupConfig.GetInt("PriceGroupCreate", -1); - // string EBA = startupConfig.GetString("EconomyBaseAccount", UUID.Zero.ToString()); - // Helpers.TryParse(EBA, out EconomyBaseAccount); - - // UserLevelPaysFees = startupConfig.GetInt("UserLevelPaysFees", -1); - m_stipend = startupConfig.GetInt("UserStipend", 500); - m_minFundsBeforeRefresh = startupConfig.GetInt("IssueStipendWhenClientIsBelowAmount", 10); - m_keepMoneyAcrossLogins = startupConfig.GetBoolean("KeepMoneyAcrossLogins", true); - 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); - } - - public EconomyData GetEconomyData() - { - EconomyData edata = new EconomyData(); - edata.ObjectCapacity = ObjectCapacity; - edata.ObjectCount = ObjectCount; - edata.PriceEnergyUnit = PriceEnergyUnit; - edata.PriceGroupCreate = PriceGroupCreate; - edata.PriceObjectClaim = PriceObjectClaim; - edata.PriceObjectRent = PriceObjectRent; - edata.PriceObjectScaleFactor = PriceObjectScaleFactor; - edata.PriceParcelClaim = PriceParcelClaim; - edata.PriceParcelClaimFactor = PriceParcelClaimFactor; - edata.PriceParcelRent = PriceParcelRent; - edata.PricePublicObjectDecay = PricePublicObjectDecay; - edata.PricePublicObjectDelete = PricePublicObjectDelete; - edata.PriceRentLight = PriceRentLight; - edata.PriceUpload = PriceUpload; - edata.TeleportMinPrice = TeleportMinPrice; - return edata; - } - - private void GetClientFunds(IClientAPI client) - { - // Here we check if we're in grid mode - // I imagine that the 'check balance' - // function for the client should be here or shortly after - - if (gridmode) - { - if (m_MoneyAddress.Length == 0) - { - CheckExistAndRefreshFunds(client.AgentId); - } - else - { - bool childYN = true; - ScenePresence agent = null; - //client.SecureSessionId; - Scene s = LocateSceneClientIn(client.AgentId); - if (s != null) - { - agent = s.GetScenePresence(client.AgentId); - if (agent != null) - childYN = agent.IsChildAgent; - } - if (s != null && agent != null && childYN == false) - { - //s.RegionInfo.RegionHandle; - UUID agentID = UUID.Zero; - int funds = 0; - - Hashtable hbinfo = - GetBalanceForUserFromMoneyServer(client.AgentId, client.SecureSessionId, s.RegionInfo.originRegionID, - s.RegionInfo.regionSecret); - if ((bool) hbinfo["success"] == true) - { - UUID.TryParse((string)hbinfo["agentId"], out agentID); - 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); - client.SendAlertMessage("Unable to get your money balance, money operations will be unavailable"); - } - catch (InvalidCastException) - { - funds = 0; - } - - m_KnownClientFunds[agentID] = funds; - } - 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"]); - } - SendMoneyBalance(client, agentID, client.SessionId, UUID.Zero); - } - } - } - else - { - CheckExistAndRefreshFunds(client.AgentId); - } - - } - - /// - /// New Client Event Handler - /// - /// - private void OnNewClient(IClientAPI client) - { - GetClientFunds(client); - - // Subscribe to Money messages - client.OnEconomyDataRequest += EconomyDataRequestHandler; - client.OnMoneyBalanceRequest += SendMoneyBalance; - client.OnRequestPayPrice += requestPayPrice; - client.OnObjectBuy += ObjectBuy; - client.OnLogout += ClientClosed; - } - - /// - /// Transfer money - /// - /// - /// - /// - /// - private bool doMoneyTransfer(UUID Sender, UUID Receiver, int amount, int transactiontype, string description) - { - bool result = false; - if (amount >= 0) - { - lock (m_KnownClientFunds) - { - // 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; - } - } - else - { - // These below are redundant to make this clearer to read - result = false; - } - } - else - { - result = false; - } - } - else - { - result = TransferMoneyonMoneyServer(Sender, Receiver, amount, transactiontype, description); - } - } - } - return result; - } - - - /// - /// Sends the the stored money balance to the client - /// - /// - /// - /// - /// - public void SendMoneyBalance(IClientAPI client, UUID agentID, UUID SessionID, UUID TransactionID) - { - if (client.AgentId == agentID && client.SessionId == SessionID) - { - int returnfunds = 0; - - 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!"); - } - } - - /// - /// Gets the current balance for the user from the Grid Money Server - /// - /// - /// - /// - /// - /// - public Hashtable GetBalanceForUserFromMoneyServer(UUID agentId, UUID secureSessionID, UUID 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"] = ""; - - return ErrorHash; - } - Hashtable MoneyRespData = (Hashtable) MoneyResp.Value; - - return MoneyRespData; - } - - /// - /// This informs the Money Grid Server that the avatar is in this simulator - /// - /// - /// - /// - /// - /// - public Hashtable claim_user(UUID agentId, UUID secureSessionID, UUID 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, UUID.Zero); - } - return MoneyRespData; - } - - private SceneObjectPart findPrim(UUID objectID) - { - lock (m_scenel) - { - foreach (Scene s in m_scenel.Values) - { - SceneObjectPart part = s.GetSceneObjectPart(objectID); - if (part != null) - { - return part; - } - } - } - return null; - } - - private string resolveObjectName(UUID objectID) - { - SceneObjectPart part = findPrim(objectID); - if (part != null) - { - return part.Name; - } - return String.Empty; - } - - private string resolveAgentName(UUID agentID) - { - // try avatar username surname - Scene scene = GetRandomScene(); - CachedUserInfo profile = scene.CommsManager.UserProfileCacheService.GetUserDetails(agentID); - if (profile != null && profile.UserProfile != null) - { - string avatarname = profile.UserProfile.FirstName + " " + profile.UserProfile.SurName; - return avatarname; - } - else - { - m_log.ErrorFormat( - "[MONEY]: Could not resolve user {0}", - agentID); - } - - return String.Empty; - } - - private void BalanceUpdate(UUID senderID, UUID receiverID, bool transactionresult, string description) - { - IClientAPI sender = LocateClientObject(senderID); - IClientAPI receiver = LocateClientObject(receiverID); - - if (senderID != receiverID) - { - if (sender != null) - { - sender.SendMoneyBalance(UUID.Random(), transactionresult, Utils.StringToBytes(description), GetFundsForAgentID(senderID)); - } - - if (receiver != null) - { - receiver.SendMoneyBalance(UUID.Random(), transactionresult, Utils.StringToBytes(description), GetFundsForAgentID(receiverID)); - } - } - } - - /// - /// Informs the Money Grid Server of a transfer. - /// - /// - /// - /// - /// - public bool TransferMoneyonMoneyServer(UUID sourceId, UUID destId, int amount, int transactiontype, string description) - { - int aggregatePermInventory = 0; - int aggregatePermNextOwner = 0; - int flags = 0; - bool rvalue = false; - - IClientAPI cli = LocateClientObject(sourceId); - if (cli != null) - { - Scene userScene = null; - lock (m_rootAgents) - { - 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"]; - } - catch (InvalidCastException) - { - funds2 = 0; - } - SetLocalFundsForAgentID(destId, funds2); - } - - - rvalue = true; - } - else - { - cli.SendAgentAlertMessage((string) hresult["errorMessage"], true); - } - } - } - else - { - m_log.ErrorFormat("[MONEY]: Client {0} not found", sourceId.ToString()); - } - - return rvalue; - } - - public int GetRemoteBalance(UUID agentId) - { - int funds = 0; - - IClientAPI aClient = LocateClientObject(agentId); - if (aClient != null) - { - Scene s = LocateSceneClientIn(agentId); - if (s != null) - { - if (m_MoneyAddress.Length > 0) - { - Hashtable hbinfo = - GetBalanceForUserFromMoneyServer(aClient.AgentId, aClient.SecureSessionId, s.RegionInfo.originRegionID, - 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, UUID.Zero); - } - else - { - m_log.Debug("[MONEY]: Got balance request update for agent that is here, but couldn't find which scene."); - } - } - else - { - m_log.Debug("[MONEY]: Got balance request update for agent that isn't here."); - } - return funds; - } - - public XmlRpcResponse GridMoneyUpdate(XmlRpcRequest request) - { - m_log.Debug("[MONEY]: Dynamic balance update called."); - Hashtable requestData = (Hashtable) request.Params[0]; - - if (requestData.ContainsKey("agentId")) - { - UUID agentId = UUID.Zero; - - UUID.TryParse((string) requestData["agentId"], out agentId); - if (agentId != UUID.Zero) - { - GetRemoteBalance(agentId); - } - else - { - m_log.Debug("[MONEY]: invalid agentId specified, dropping."); - } - } - 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; - } - - /// - /// XMLRPC handler to send alert message and sound to client - /// - public XmlRpcResponse UserAlert(XmlRpcRequest request) - { - XmlRpcResponse ret = new XmlRpcResponse(); - Hashtable retparam = new Hashtable(); - Hashtable requestData = (Hashtable) request.Params[0]; - - UUID agentId; - UUID soundId; - UUID regionId; - - UUID.TryParse((string) requestData["agentId"], out agentId); - UUID.TryParse((string) requestData["soundId"], out soundId); - UUID.TryParse((string) requestData["regionId"], out regionId); - string text = (string) requestData["text"]; - string secret = (string) requestData["secret"]; - - Scene userScene = GetSceneByUUID(regionId); - if (userScene != null) - { - if (userScene.RegionInfo.regionSecret == secret) - { - - IClientAPI client = LocateClientObject(agentId); - if (client != null) - { - - if (soundId != UUID.Zero) - client.SendPlayAttachedSound(soundId, UUID.Zero, UUID.Zero, 1.0f, 0); - - client.SendBlueBoxMessage(UUID.Zero, "", text); - - retparam.Add("success", true); - } - else - { - retparam.Add("success", false); - } - } - else - { - retparam.Add("success", false); - } - } - - ret.Value = retparam; - return ret; - } - - # region Standalone box enablers only - - public XmlRpcResponse quote_func(XmlRpcRequest request) - { - Hashtable requestData = (Hashtable) request.Params[0]; - UUID agentId = UUID.Zero; - int amount = 0; - Hashtable quoteResponse = new Hashtable(); - XmlRpcResponse returnval = new XmlRpcResponse(); - - if (requestData.ContainsKey("agentId") && requestData.ContainsKey("currencyBuy")) - { - UUID.TryParse((string) requestData["agentId"], out agentId); - try - { - amount = (Int32) requestData["currencyBuy"]; - } - catch (InvalidCastException) - { - } - 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) - { - Hashtable requestData = (Hashtable) request.Params[0]; - UUID agentId = UUID.Zero; - int amount = 0; - if (requestData.ContainsKey("agentId") && requestData.ContainsKey("currencyBuy")) - { - UUID.TryParse((string) requestData["agentId"], out agentId); - try - { - amount = (Int32) requestData["currencyBuy"]; - } - catch (InvalidCastException) - { - } - if (agentId != UUID.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, UUID.Zero); - } - } - } - XmlRpcResponse returnval = new XmlRpcResponse(); - Hashtable returnresp = new Hashtable(); - returnresp.Add("success", true); - returnval.Value = returnresp; - return returnval; - } - - public XmlRpcResponse preflightBuyLandPrep_func(XmlRpcRequest request) - { - 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/"); - - Hashtable currency = new Hashtable(); - currency.Add("estimatedCost", 0); - - Hashtable membership = new Hashtable(); - membershiplevels.Add("upgrade", false); - membershiplevels.Add("action", "http://invaliddomaininvalid.com/"); - membershiplevels.Add("levels", membershiplevels); - - 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; - } - - public XmlRpcResponse landBuy_func(XmlRpcRequest request) - { - XmlRpcResponse ret = new XmlRpcResponse(); - Hashtable retparam = new Hashtable(); - Hashtable requestData = (Hashtable) request.Params[0]; - - UUID agentId = UUID.Zero; - int amount = 0; - if (requestData.ContainsKey("agentId") && requestData.ContainsKey("currencyBuy")) - { - UUID.TryParse((string) requestData["agentId"], out agentId); - try - { - amount = (Int32) requestData["currencyBuy"]; - } - catch (InvalidCastException) - { - } - if (agentId != UUID.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, UUID.Zero); - } - } - } - retparam.Add("success", true); - ret.Value = retparam; - - return ret; - } - - #endregion - - #region local Fund Management - - /// - /// Ensures that the agent accounting data is set up in this instance. - /// - /// - private void CheckExistAndRefreshFunds(UUID agentID) - { - lock (m_KnownClientFunds) - { - if (!m_KnownClientFunds.ContainsKey(agentID)) - { - m_KnownClientFunds.Add(agentID, m_stipend); - } - else - { - if (m_KnownClientFunds[agentID] <= m_minFundsBeforeRefresh) - { - m_KnownClientFunds[agentID] = m_stipend; - } - } - } - } - - /// - /// Gets the amount of Funds for an agent - /// - /// - /// - private int GetFundsForAgentID(UUID 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(UUID AgentID, int amount) - { - lock (m_KnownClientFunds) - { - if (m_KnownClientFunds.ContainsKey(AgentID)) - { - m_KnownClientFunds[AgentID] = amount; - } - else - { - m_KnownClientFunds.Add(AgentID, amount); - } - } - } - - #endregion - - #region Utility Helpers - - /// - /// Locates a IClientAPI for the client specified - /// - /// - /// - private IClientAPI LocateClientObject(UUID AgentID) - { - ScenePresence tPresence = null; - IClientAPI rclient = null; - - lock (m_scenel) - { - foreach (Scene _scene in m_scenel.Values) - { - tPresence = _scene.GetScenePresence(AgentID); - if (tPresence != null) - { - if (!tPresence.IsChildAgent) - { - rclient = tPresence.ControllingClient; - } - } - if (rclient != null) - { - return rclient; - } - } - } - return null; - } - - private Scene LocateSceneClientIn(UUID AgentId) - { - lock (m_scenel) - { - foreach (Scene _scene in m_scenel.Values) - { - ScenePresence tPresence = _scene.GetScenePresence(AgentId); - if (tPresence != null) - { - if (!tPresence.IsChildAgent) - { - return _scene; - } - } - } - } - 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) - { - foreach (Scene rs in m_scenel.Values) - return rs; - } - return null; - } - - /// - /// Utility function to get a Scene by RegionID in a module - /// - /// - /// - public Scene GetSceneByUUID(UUID RegionID) - { - lock (m_scenel) - { - foreach (Scene rs in m_scenel.Values) - { - if (rs.RegionInfo.originRegionID == RegionID) - { - return rs; - } - } - } - return null; - } - - #endregion - - #region event Handlers - - public void requestPayPrice(IClientAPI client, UUID 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(UUID AgentID) - { - lock (m_KnownClientFunds) - { - if (m_keepMoneyAcrossLogins && m_MoneyAddress.Length == 0) - { - } - else - { - m_KnownClientFunds.Remove(AgentID); - } - } - } - - /// - /// Event called Economy Data Request handler. - /// - /// - public void EconomyDataRequestHandler(UUID 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) - { - if (m_MoneyAddress.Length == 0) - { - lock (m_KnownClientFunds) - { - if (m_KnownClientFunds.ContainsKey(e.agentId)) - { - // Does the sender have enough funds to give? - if (m_KnownClientFunds[e.agentId] >= e.parcelPrice) - { - lock (e) - { - e.economyValidated = true; - } - } - } - } - } - else - { - if (GetRemoteBalance(e.agentId) >= e.parcelPrice) - { - lock (e) - { - e.economyValidated = true; - } - } - } - } - - private void processLandBuy(Object osender, EventManager.LandBuyArgs e) - { - lock (e) - { - if (e.economyValidated == true && e.transactionID == 0) - { - e.transactionID = Util.UnixTimeSinceEpoch(); - - if (doMoneyTransfer(e.agentId, e.parcelOwnerID, e.parcelPrice, 0, "Land purchase")) - { - lock (e) - { - e.amountDebited = e.parcelPrice; - } - } - } - } - } - - /// - /// 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; - - 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)"; - - receiver = LocateClientObject(part.OwnerID); - - 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 (transactionresult) - { - ObjectPaid handlerOnObjectPaid = OnObjectPaid; - if (handlerOnObjectPaid != null) - { - handlerOnObjectPaid(e.receiver, e.sender, e.amount); - } - } - - if (e.sender != e.receiver) - { - sender.SendMoneyBalance(UUID.Random(), transactionresult, Utils.StringToBytes(e.description), GetFundsForAgentID(e.sender)); - } - if (receiver != null) - { - receiver.SendMoneyBalance(UUID.Random(), transactionresult, Utils.StringToBytes(e.description), GetFundsForAgentID(part.OwnerID)); - } - } - return; - } - - 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(UUID.Random(), transactionresult, Utils.StringToBytes(e.description), GetFundsForAgentID(e.sender)); - } - } - - if (receiver != null) - { - receiver.SendMoneyBalance(UUID.Random(), transactionresult, Utils.StringToBytes(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()); - } - } - - /// - /// 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.Debug("[MONEY]: Removing " + avatar.Firstname + " " + avatar.Lastname + " as a root agent"); - } - } - } - } - - /// - /// Event Handler for when the client logs out. - /// - /// - private void ClientLoggedOut(UUID AgentId) - { - lock (m_rootAgents) - { - if (m_rootAgents.ContainsKey(AgentId)) - { - m_rootAgents.Remove(AgentId); - //m_log.Info("[MONEY]: Removing " + AgentId + ". Agent logged out."); - } - } - } - - /// - /// Call this when the client disconnects. - /// - /// - public void ClientClosed(IClientAPI client) - { - ClientClosed(client.AgentId); - } - - /// - /// Event Handler for when an Avatar enters one of the parcels in the simulator. - /// - /// - /// - /// - private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, UUID regionID) - { - 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 - { - ILandObject obj = avatar.Scene.LandChannel.GetLandObject(avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y); - if ((obj.landData.Flags & (uint)Parcel.ParcelFlags.AllowDamage) != 0) - { - avatar.Invulnerable = false; - } - else - { - avatar.Invulnerable = 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()); - } - - public int GetBalance(IClientAPI client) - { - GetClientFunds(client); - - lock (m_KnownClientFunds) - { - if (!m_KnownClientFunds.ContainsKey(client.AgentId)) - return 0; - - return m_KnownClientFunds[client.AgentId]; - } - } - - // Please do not refactor these to be just one method - // Existing implementations need the distinction - // - public bool UploadCovered(IClientAPI client) - { - return AmountCovered(client, PriceUpload); - } - - public bool GroupCreationCovered(IClientAPI client) - { - return AmountCovered(client, PriceGroupCreate); - } - - public bool AmountCovered(IClientAPI client, int amount) - { - if (GetBalance(client) < amount) - return false; - return true; - } - - #endregion - - public void ObjectBuy(IClientAPI remoteClient, UUID agentID, - UUID sessionID, UUID groupID, UUID categoryID, - uint localID, byte saleType, int salePrice) - { - GetClientFunds(remoteClient); - - if (!m_KnownClientFunds.ContainsKey(remoteClient.AgentId)) - { - remoteClient.SendAgentAlertMessage("Unable to buy now. Your account balance was not found.", false); - return; - } - - int funds = m_KnownClientFunds[remoteClient.AgentId]; - - if (salePrice != 0 && funds < salePrice) - { - remoteClient.SendAgentAlertMessage("Unable to buy now. You don't have sufficient funds.", false); - return; - } - - Scene s = LocateSceneClientIn(remoteClient.AgentId); - - SceneObjectPart part = s.GetSceneObjectPart(localID); - if (part == null) - { - remoteClient.SendAgentAlertMessage("Unable to buy now. The object was not found.", false); - return; - } - - if (s.PerformObjectBuy(remoteClient, categoryID, localID, saleType)) - doMoneyTransfer(remoteClient.AgentId, part.OwnerID, salePrice, 5000, "Object buy"); - } - } - - public enum TransactionType : int - { - SystemGenerated = 0, - RegionMoneyRequest = 1, - Gift = 2, - Purchase = 3 - } - - -} diff --git a/OpenSim/Region/Environment/Modules/Avatar/Dialog/DialogModule.cs b/OpenSim/Region/Environment/Modules/Avatar/Dialog/DialogModule.cs deleted file mode 100644 index d3ac2c0..0000000 --- a/OpenSim/Region/Environment/Modules/Avatar/Dialog/DialogModule.cs +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System.Collections.Generic; -using System.Reflection; -using log4net; -using Nini.Config; -using OpenMetaverse; -using OpenSim.Framework; -using OpenSim.Region.Framework.Interfaces; -using OpenSim.Region.Framework.Scenes; - -namespace OpenSim.Region.Environment.Modules.Avatar.Dialog -{ - public class DialogModule : IRegionModule, IDialogModule - { - //private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - protected Scene m_scene; - - public void Initialise(Scene scene, IConfigSource source) - { - m_scene = scene; - m_scene.RegisterModuleInterface(this); - } - - public void PostInitialise() {} - public void Close() {} - public string Name { get { return "Dialog Module"; } } - public bool IsSharedModule { get { return false; } } - - public void SendAlertToUser(IClientAPI client, string message) - { - SendAlertToUser(client, message, false); - } - - public void SendAlertToUser(IClientAPI client, string message, bool modal) - { - client.SendAgentAlertMessage(message, modal); - } - - public void SendAlertToUser(UUID agentID, string message) - { - SendAlertToUser(agentID, message, false); - } - - public void SendAlertToUser(UUID agentID, string message, bool modal) - { - ScenePresence sp = m_scene.GetScenePresence(agentID); - - if (sp != null) - sp.ControllingClient.SendAgentAlertMessage(message, modal); - } - - public void SendAlertToUser(string firstName, string lastName, string message, bool modal) - { - List presenceList = m_scene.GetScenePresences(); - - foreach (ScenePresence presence in presenceList) - { - if (presence.Firstname == firstName && presence.Lastname == lastName) - { - presence.ControllingClient.SendAgentAlertMessage(message, modal); - break; - } - } - } - - public void SendGeneralAlert(string message) - { - List presenceList = m_scene.GetScenePresences(); - - foreach (ScenePresence presence in presenceList) - { - if (!presence.IsChildAgent) - presence.ControllingClient.SendAlertMessage(message); - } - } - - public void SendDialogToUser( - UUID avatarID, string objectName, UUID objectID, UUID ownerID, - string message, UUID textureID, int ch, string[] buttonlabels) - { - ScenePresence sp = m_scene.GetScenePresence(avatarID); - - if (sp != null) - sp.ControllingClient.SendDialog(objectName, objectID, ownerID, message, textureID, ch, buttonlabels); - } - - public void SendUrlToUser( - UUID avatarID, string objectName, UUID objectID, UUID ownerID, bool groupOwned, string message, string url) - { - ScenePresence sp = m_scene.GetScenePresence(avatarID); - - if (sp != null) - sp.ControllingClient.SendLoadURL(objectName, objectID, ownerID, groupOwned, message, url); - } - - public void SendNotificationToUsersInEstate( - UUID fromAvatarID, string fromAvatarName, string message) - { - // TODO: This does not yet do what it says on the tin - it only sends the message to users in the same - // region as the sending avatar. - SendNotificationToUsersInRegion(fromAvatarID, fromAvatarName, message); - } - - public void SendNotificationToUsersInRegion( - UUID fromAvatarID, string fromAvatarName, string message) - { - List presenceList = m_scene.GetScenePresences(); - - foreach (ScenePresence presence in presenceList) - { - if (!presence.IsChildAgent) - presence.ControllingClient.SendBlueBoxMessage(fromAvatarID, fromAvatarName, message); - } - } - } -} diff --git a/OpenSim/Region/Environment/Modules/Avatar/Friends/FriendsModule.cs b/OpenSim/Region/Environment/Modules/Avatar/Friends/FriendsModule.cs deleted file mode 100644 index 0ed962e..0000000 --- a/OpenSim/Region/Environment/Modules/Avatar/Friends/FriendsModule.cs +++ /dev/null @@ -1,1003 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using OpenMetaverse; -using log4net; -using Nini.Config; -using Nwc.XmlRpc; -using OpenSim.Framework; -using OpenSim.Framework.Communications.Cache; -using OpenSim.Framework.Servers; -using OpenSim.Region.Framework.Interfaces; -using OpenSim.Region.Framework.Scenes; - -namespace OpenSim.Region.Environment.Modules.Avatar.Friends -{ - /* - This module handles adding/removing friends, and the the presence - notification process for login/logoff of friends. - - The presence notification works as follows: - - After the user initially connects to a region (so we now have a UDP - connection to work with), this module fetches the friends of user - (those are cached), their on-/offline status, and info about the - region they are in from the MessageServer. - - (*) It then informs the user about the on-/offline status of her friends. - - It then informs all online friends currently on this region-server about - user's new online status (this will save some network traffic, as local - messages don't have to be transferred inter-region, and it will be all - that has to be done in Standalone Mode). - - For the rest of the online friends (those not on this region-server), - this module uses the provided region-information to map users to - regions, and sends one notification to every region containing the - friends to inform on that server. - - The region-server will handle that in the following way: - - If it finds the friend, it informs her about the user being online. - - If it doesn't find the friend (maybe she TPed away in the meantime), - it stores that information. - - After it processed all friends, it returns the list of friends it - couldn't find. - - If this list isn't empty, the FriendsModule re-requests information - about those online friends that have been missed and starts at (*) - again until all friends have been found, or until it tried 3 times - (to prevent endless loops due to some uncaught error). - - NOTE: Online/Offline notifications don't need to be sent on region change. - - We implement two XMLRpc handlers here, handling all the inter-region things - we have to handle: - - On-/Offline-Notifications (bulk) - - Terminate Friendship messages (single) - */ - - public class FriendsModule : IRegionModule, IFriendsModule - { - private class Transaction - { - public UUID agentID; - public string agentName; - public uint count; - - public Transaction(UUID agentID, string agentName) - { - this.agentID = agentID; - this.agentName = agentName; - this.count = 1; - } - } - - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private Cache m_friendLists = new Cache(CacheFlags.AllowUpdate); - - private Dictionary m_rootAgents = new Dictionary(); - - private Dictionary m_pendingCallingcardRequests = new Dictionary(); - - private Scene m_initialScene; // saves a lookup if we don't have a specific scene - private Dictionary m_scenes = new Dictionary(); - private IMessageTransferModule m_TransferModule = null; - - #region IRegionModule Members - - public void Initialise(Scene scene, IConfigSource config) - { - lock (m_scenes) - { - if (m_scenes.Count == 0) - { - scene.CommsManager.HttpServer.AddXmlRPCHandler("presence_update_bulk", processPresenceUpdateBulk); - scene.CommsManager.HttpServer.AddXmlRPCHandler("terminate_friend", processTerminateFriend); - m_friendLists.DefaultTTL = new TimeSpan(1, 0, 0); // store entries for one hour max - m_initialScene = scene; - } - - if (!m_scenes.ContainsKey(scene.RegionInfo.RegionHandle)) - m_scenes[scene.RegionInfo.RegionHandle] = scene; - } - - scene.RegisterModuleInterface(this); - - scene.EventManager.OnNewClient += OnNewClient; - scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage; - scene.EventManager.OnAvatarEnteringNewParcel += AvatarEnteringParcel; - scene.EventManager.OnMakeChildAgent += MakeChildAgent; - scene.EventManager.OnClientClosed += ClientClosed; - } - - public void PostInitialise() - { - if (m_scenes.Count > 0) - { - m_TransferModule = m_initialScene.RequestModuleInterface(); - } - if (m_TransferModule == null) - m_log.Error("[FRIENDS]: Unable to find a message transfer module, friendship offers will not work"); - } - - public void Close() - { - } - - public string Name - { - get { return "FriendsModule"; } - } - - public bool IsSharedModule - { - get { return true; } - } - - #endregion - - /// - /// Receive presence information changes about clients in other regions. - /// - /// - /// - public XmlRpcResponse processPresenceUpdateBulk(XmlRpcRequest req) - { - Hashtable requestData = (Hashtable)req.Params[0]; - - List friendsNotHere = new List(); - - // this is called with the expectation that all the friends in the request are on this region-server. - // But as some time passed since we checked (on the other region-server, via the MessagingServer), - // some of the friends might have teleported away. - // Actually, even now, between this line and the sending below, some people could TP away. So, - // we'll have to lock the m_rootAgents list for the duration to prevent/delay that. - lock (m_rootAgents) - { - List friendsHere = new List(); - - try - { - UUID agentID = new UUID((string)requestData["agentID"]); - bool agentOnline = (bool)requestData["agentOnline"]; - int count = (int)requestData["friendCount"]; - for (int i = 0; i < count; ++i) - { - UUID uuid; - if (UUID.TryParse((string)requestData["friendID_" + i], out uuid)) - { - if (m_rootAgents.ContainsKey(uuid)) friendsHere.Add(GetRootPresenceFromAgentID(uuid)); - else friendsNotHere.Add(uuid); - } - } - - // now send, as long as they are still here... - UUID[] agentUUID = new UUID[] { agentID }; - if (agentOnline) - { - foreach (ScenePresence agent in friendsHere) - { - agent.ControllingClient.SendAgentOnline(agentUUID); - } - } - else - { - foreach (ScenePresence agent in friendsHere) - { - agent.ControllingClient.SendAgentOffline(agentUUID); - } - } - } - catch(Exception e) - { - m_log.Warn("[FRIENDS]: Got exception while parsing presence_update_bulk request:", e); - } - } - - // no need to lock anymore; if TPs happen now, worst case is that we have an additional agent in this region, - // which should be caught on the next iteration... - Hashtable result = new Hashtable(); - int idx = 0; - foreach (UUID uuid in friendsNotHere) - { - result["friendID_" + idx++] = uuid.ToString(); - } - result["friendCount"] = idx; - - XmlRpcResponse response = new XmlRpcResponse(); - response.Value = result; - - return response; - } - - public XmlRpcResponse processTerminateFriend(XmlRpcRequest req) - { - Hashtable requestData = (Hashtable)req.Params[0]; - - bool success = false; - - UUID agentID; - UUID friendID; - if (requestData.ContainsKey("agentID") && UUID.TryParse((string)requestData["agentID"], out agentID) && - requestData.ContainsKey("friendID") && UUID.TryParse((string)requestData["friendID"], out friendID)) - { - // try to find it and if it is there, prevent it to vanish before we sent the message - lock (m_rootAgents) - { - if (m_rootAgents.ContainsKey(agentID)) - { - m_log.DebugFormat("[FRIEND]: Sending terminate friend {0} to agent {1}", friendID, agentID); - GetRootPresenceFromAgentID(agentID).ControllingClient.SendTerminateFriend(friendID); - success = true; - } - } - } - - // return whether we were successful - Hashtable result = new Hashtable(); - result["success"] = success; - - XmlRpcResponse response = new XmlRpcResponse(); - response.Value = result; - return response; - } - - private void OnNewClient(IClientAPI client) - { - // All friends establishment protocol goes over instant message - // There's no way to send a message from the sim - // to a user to 'add a friend' without causing dialog box spam - - // Subscribe to instant messages - client.OnInstantMessage += OnInstantMessage; - - // Friend list management - client.OnApproveFriendRequest += OnApproveFriendRequest; - client.OnDenyFriendRequest += OnDenyFriendRequest; - client.OnTerminateFriendship += OnTerminateFriendship; - - // ... calling card handling... - client.OnOfferCallingCard += OnOfferCallingCard; - client.OnAcceptCallingCard += OnAcceptCallingCard; - client.OnDeclineCallingCard += OnDeclineCallingCard; - - // we need this one exactly once per agent session (see comments in the handler below) - client.OnEconomyDataRequest += OnEconomyDataRequest; - - // if it leaves, we want to know, too - client.OnLogout += OnLogout; - } - - private void ClientClosed(UUID AgentId) - { - // agent's client was closed. As we handle logout in OnLogout, this here has only to handle - // TPing away (root agent is closed) or TPing/crossing in a region far enough away (client - // agent is closed). - // NOTE: In general, this doesn't mean that the agent logged out, just that it isn't around - // in one of the regions here anymore. - lock (m_rootAgents) - { - if (m_rootAgents.ContainsKey(AgentId)) - { - m_rootAgents.Remove(AgentId); - } - } - } - - private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, UUID regionID) - { - lock (m_rootAgents) - { - m_rootAgents[avatar.UUID] = avatar.RegionHandle; - // Claim User! my user! Mine mine mine! - } - } - - private void MakeChildAgent(ScenePresence avatar) - { - lock (m_rootAgents) - { - if (m_rootAgents.ContainsKey(avatar.UUID)) - { - // only delete if the region matches. As this is a shared module, the avatar could be - // root agent in another region on this server. - if (m_rootAgents[avatar.UUID] == avatar.RegionHandle) - { - m_rootAgents.Remove(avatar.UUID); -// m_log.Debug("[FRIEND]: Removing " + avatar.Firstname + " " + avatar.Lastname + " as a root agent"); - } - } - } - } - - private ScenePresence GetRootPresenceFromAgentID(UUID AgentID) - { - ScenePresence returnAgent = null; - lock (m_scenes) - { - ScenePresence queryagent = null; - foreach (Scene scene in m_scenes.Values) - { - queryagent = scene.GetScenePresence(AgentID); - if (queryagent != null) - { - if (!queryagent.IsChildAgent) - { - returnAgent = queryagent; - break; - } - } - } - } - return returnAgent; - } - - private ScenePresence GetAnyPresenceFromAgentID(UUID AgentID) - { - ScenePresence returnAgent = null; - lock (m_scenes) - { - ScenePresence queryagent = null; - foreach (Scene scene in m_scenes.Values) - { - queryagent = scene.GetScenePresence(AgentID); - if (queryagent != null) - { - returnAgent = queryagent; - break; - } - } - } - return returnAgent; - } - - public void OfferFriendship(UUID fromUserId, IClientAPI toUserClient, string offerMessage) - { - CachedUserInfo userInfo = m_initialScene.CommsManager.UserProfileCacheService.GetUserDetails(fromUserId); - - if (userInfo != null) - { - GridInstantMessage msg = new GridInstantMessage( - toUserClient.Scene, fromUserId, userInfo.UserProfile.Name, toUserClient.AgentId, - (byte)InstantMessageDialog.FriendshipOffered, offerMessage, false, Vector3.Zero); - - FriendshipOffered(msg); - } - else - { - m_log.ErrorFormat("[FRIENDS]: No user found for id {0} in OfferFriendship()", fromUserId); - } - } - - #region FriendRequestHandling - - private void OnInstantMessage(IClientAPI client, GridInstantMessage im) - { - // Friend Requests go by Instant Message.. using the dialog param - // https://wiki.secondlife.com/wiki/ImprovedInstantMessage - - if (im.dialog == (byte)InstantMessageDialog.FriendshipOffered) // 38 - { - // fromAgentName is the *destination* name (the friend we offer friendship to) - ScenePresence initiator = GetAnyPresenceFromAgentID(new UUID(im.fromAgentID)); - im.fromAgentName = initiator != null ? initiator.Name : "(hippo)"; - - FriendshipOffered(im); - } - else if (im.dialog == (byte)InstantMessageDialog.FriendshipAccepted) // 39 - { - FriendshipAccepted(client, im); - } - else if (im.dialog == (byte)InstantMessageDialog.FriendshipDeclined) // 40 - { - FriendshipDeclined(client, im); - } - } - - /// - /// Invoked when a user offers a friendship. - /// - /// - /// - /// - private void FriendshipOffered(GridInstantMessage im) - { - // this is triggered by the initiating agent: - // A local agent offers friendship to some possibly remote friend. - // A IM is triggered, processed here and sent to the friend (possibly in a remote region). - - m_log.DebugFormat("[FRIEND]: Offer(38) - From: {0}, FromName: {1} To: {2}, Session: {3}, Message: {4}, Offline {5}", - im.fromAgentID, im.fromAgentName, im.toAgentID, im.imSessionID, im.message, im.offline); - - // 1.20 protocol sends an UUID in the message field, instead of the friendship offer text. - // For interoperability, we have to clear that - if (Util.isUUID(im.message)) im.message = ""; - - // be sneeky and use the initiator-UUID as transactionID. This means we can be stateless. - // we have to look up the agent name on friendship-approval, though. - im.imSessionID = im.fromAgentID; - - if (m_TransferModule != null) - { - // Send it to whoever is the destination. - // If new friend is local, it will send an IM to the viewer. - // If new friend is remote, it will cause a OnGridInstantMessage on the remote server - m_TransferModule.SendInstantMessage( - im, - delegate(bool success) - { - m_log.DebugFormat("[FRIEND]: sending IM success = {0}", success); - } - ); - } - } - - /// - /// Invoked when a user accepts a friendship offer. - /// - /// - /// - private void FriendshipAccepted(IClientAPI client, GridInstantMessage im) - { - m_log.DebugFormat("[FRIEND]: 39 - from client {0}, agent {2} {3}, imsession {4} to {5}: {6} (dialog {7})", - client.AgentId, im.fromAgentID, im.fromAgentName, im.imSessionID, im.toAgentID, im.message, im.dialog); - } - - /// - /// Invoked when a user declines a friendship offer. - /// - /// May not currently be used - see OnDenyFriendRequest() instead - /// - /// - private void FriendshipDeclined(IClientAPI client, GridInstantMessage im) - { - UUID fromAgentID = new UUID(im.fromAgentID); - UUID toAgentID = new UUID(im.toAgentID); - - // declining the friendship offer causes a type 40 IM being sent to the (possibly remote) initiator - // toAgentID is initiator, fromAgentID declined friendship - m_log.DebugFormat("[FRIEND]: 40 - from client {0}, agent {1} {2}, imsession {3} to {4}: {5} (dialog {6})", - client != null ? client.AgentId.ToString() : "", - fromAgentID, im.fromAgentName, im.imSessionID, im.toAgentID, im.message, im.dialog); - - // Send the decline to whoever is the destination. - GridInstantMessage msg - = new GridInstantMessage( - client.Scene, fromAgentID, client.Name, toAgentID, - im.dialog, im.message, im.offline != 0, im.Position); - - // If new friend is local, it will send an IM to the viewer. - // If new friend is remote, it will cause a OnGridInstantMessage on the remote server - m_TransferModule.SendInstantMessage(msg, - delegate(bool success) { - m_log.DebugFormat("[FRIEND]: sending IM success = {0}", success); - } - ); - } - - private void OnGridInstantMessage(GridInstantMessage msg) - { - // This event won't be raised unless we have that agent, - // so we can depend on the above not trying to send - // via grid again - m_log.DebugFormat("[FRIEND]: Got GridIM from {0}, to {1}, imSession {2}, message {3}, dialog {4}", - msg.fromAgentID, msg.toAgentID, msg.imSessionID, msg.message, msg.dialog); - - if (msg.dialog == (byte)InstantMessageDialog.FriendshipOffered || - msg.dialog == (byte)InstantMessageDialog.FriendshipAccepted || - msg.dialog == (byte)InstantMessageDialog.FriendshipDeclined) - { - // this should succeed as we *know* the root agent is here. - m_TransferModule.SendInstantMessage(msg, - delegate(bool success) { - m_log.DebugFormat("[FRIEND]: sending IM success = {0}", success); - } - ); - } - - if (msg.dialog == (byte)InstantMessageDialog.FriendshipAccepted) - { - // for accept friendship, we have to do a bit more - ApproveFriendship(new UUID(msg.fromAgentID), new UUID(msg.toAgentID), msg.fromAgentName); - } - } - - private void ApproveFriendship(UUID fromAgentID, UUID toAgentID, string fromName) - { - m_log.DebugFormat("[FRIEND]: Approve friendship from {0} (ID: {1}) to {2}", - fromAgentID, fromName, toAgentID); - - // a new friend was added in the initiator's and friend's data, so the cache entries are wrong now. - lock (m_friendLists) - { - m_friendLists.Invalidate(fromAgentID); - m_friendLists.Invalidate(toAgentID); - } - - // now send presence update and add a calling card for the new friend - - ScenePresence initiator = GetAnyPresenceFromAgentID(toAgentID); - if (initiator == null) - { - // quite wrong. Shouldn't happen. - m_log.WarnFormat("[FRIEND]: Coudn't find initiator of friend request {0}", toAgentID); - return; - } - - m_log.DebugFormat("[FRIEND]: Tell {0} that {1} is online", - initiator.Name, fromName); - // tell initiator that friend is online - initiator.ControllingClient.SendAgentOnline(new UUID[] { fromAgentID }); - - // find the folder for the friend... - InventoryFolderImpl folder = - initiator.Scene.CommsManager.UserProfileCacheService.GetUserDetails(toAgentID).FindFolderForType((int)InventoryType.CallingCard); - if (folder != null) - { - // ... and add the calling card - CreateCallingCard(initiator.ControllingClient, fromAgentID, folder.ID, fromName); - } - } - - private void OnApproveFriendRequest(IClientAPI client, UUID agentID, UUID friendID, List callingCardFolders) - { - m_log.DebugFormat("[FRIEND]: Got approve friendship from {0} {1}, agentID {2}, tid {3}", - client.Name, client.AgentId, agentID, friendID); - - // store the new friend persistently for both avatars - m_initialScene.StoreAddFriendship(friendID, agentID, (uint) FriendRights.CanSeeOnline); - - // The cache entries aren't valid anymore either, as we just added a friend to both sides. - lock (m_friendLists) - { - m_friendLists.Invalidate(agentID); - m_friendLists.Invalidate(friendID); - } - - // if it's a local friend, we don't have to do the lookup - ScenePresence friendPresence = GetAnyPresenceFromAgentID(friendID); - - if (friendPresence != null) - { - m_log.Debug("[FRIEND]: Local agent detected."); - - // create calling card - CreateCallingCard(client, friendID, callingCardFolders[0], friendPresence.Name); - - // local message means OnGridInstantMessage won't be triggered, so do the work here. - friendPresence.ControllingClient.SendInstantMessage(agentID, agentID.ToString(), friendID, client.Name, - (byte)InstantMessageDialog.FriendshipAccepted, - (uint)Util.UnixTimeSinceEpoch()); - ApproveFriendship(agentID, friendID, client.Name); - } - else - { - m_log.Debug("[FRIEND]: Remote agent detected."); - - // fetch the friend's name for the calling card. - CachedUserInfo info = m_initialScene.CommsManager.UserProfileCacheService.GetUserDetails(friendID); - - // create calling card - CreateCallingCard(client, friendID, callingCardFolders[0], - info.UserProfile.FirstName + " " + info.UserProfile.SurName); - - // Compose (remote) response to friend. - GridInstantMessage msg = new GridInstantMessage(client.Scene, agentID, client.Name, friendID, - (byte)InstantMessageDialog.FriendshipAccepted, - agentID.ToString(), false, Vector3.Zero); - if (m_TransferModule != null) - { - m_TransferModule.SendInstantMessage(msg, - delegate(bool success) { - m_log.DebugFormat("[FRIEND]: sending IM success = {0}", success); - } - ); - } - } - - // tell client that new friend is online - client.SendAgentOnline(new UUID[] { friendID }); - } - - private void OnDenyFriendRequest(IClientAPI client, UUID agentID, UUID friendID, List callingCardFolders) - { - m_log.DebugFormat("[FRIEND]: Got deny friendship from {0} {1}, agentID {2}, tid {3}", - client.Name, client.AgentId, agentID, friendID); - - // Compose response to other agent. - GridInstantMessage msg = new GridInstantMessage(client.Scene, agentID, client.Name, friendID, - (byte)InstantMessageDialog.FriendshipDeclined, - agentID.ToString(), false, Vector3.Zero); - // send decline to initiator - if (m_TransferModule != null) - { - m_TransferModule.SendInstantMessage(msg, - delegate(bool success) { - m_log.DebugFormat("[FRIEND]: sending IM success = {0}", success); - } - ); - } - } - - private void OnTerminateFriendship(IClientAPI client, UUID agentID, UUID exfriendID) - { - // client.AgentId == agentID! - - // this removes the friends from the stored friendlists. After the next login, they will be gone... - m_initialScene.StoreRemoveFriendship(agentID, exfriendID); - - // ... now tell the two involved clients that they aren't friends anymore. - - // I don't know why we have to tell , as this was caused by her, but that's how it works in SL... - client.SendTerminateFriend(exfriendID); - - // now send the friend, if online - ScenePresence presence = GetAnyPresenceFromAgentID(exfriendID); - if (presence != null) - { - m_log.DebugFormat("[FRIEND]: Sending terminate friend {0} to agent {1}", agentID, exfriendID); - presence.ControllingClient.SendTerminateFriend(agentID); - } - else - { - // retry 3 times, in case the agent TPed from the last known region... - for (int retry = 0; retry < 3; ++retry) - { - // wasn't sent, so ex-friend wasn't around on this region-server. Fetch info and try to send - UserAgentData data = m_initialScene.CommsManager.UserService.GetAgentByUUID(exfriendID); - - if (null == data) - break; - - if (!data.AgentOnline) - { - m_log.DebugFormat("[FRIEND]: {0} is offline, so not sending TerminateFriend", exfriendID); - break; // if ex-friend isn't online, we don't need to send - } - - m_log.DebugFormat("[FRIEND]: Sending remote terminate friend {0} to agent {1}@{2}", - agentID, exfriendID, data.Handle); - - // try to send to foreign region, retry if it fails (friend TPed away, for example) - if (m_initialScene.TriggerTerminateFriend(data.Handle, exfriendID, agentID)) break; - } - } - - // clean up cache: FriendList is wrong now... - lock (m_friendLists) - { - m_friendLists.Invalidate(agentID); - m_friendLists.Invalidate(exfriendID); - } - } - - #endregion - - #region CallingCards - - private void OnOfferCallingCard(IClientAPI client, UUID destID, UUID transactionID) - { - m_log.DebugFormat("[CALLING CARD]: got offer from {0} for {1}, transaction {2}", - client.AgentId, destID, transactionID); - // This might be slightly wrong. On a multi-region server, we might get the child-agent instead of the root-agent - // (or the root instead of the child) - ScenePresence destAgent = GetAnyPresenceFromAgentID(destID); - if (destAgent == null) - { - client.SendAlertMessage("The person you have offered a card to can't be found anymore."); - return; - } - - lock (m_pendingCallingcardRequests) - { - m_pendingCallingcardRequests[transactionID] = client.AgentId; - } - // inform the destination agent about the offer - destAgent.ControllingClient.SendOfferCallingCard(client.AgentId, transactionID); - } - - private void CreateCallingCard(IClientAPI client, UUID creator, UUID folder, string name) - { - InventoryItemBase item = new InventoryItemBase(); - item.AssetID = UUID.Zero; - item.AssetType = (int)AssetType.CallingCard; - item.BasePermissions = (uint)PermissionMask.Copy; - item.CreationDate = Util.UnixTimeSinceEpoch(); - item.Creator = creator; - item.CurrentPermissions = item.BasePermissions; - item.Description = ""; - item.EveryOnePermissions = (uint)PermissionMask.None; - item.Flags = 0; - item.Folder = folder; - item.GroupID = UUID.Zero; - item.GroupOwned = false; - item.ID = UUID.Random(); - item.InvType = (int)InventoryType.CallingCard; - item.Name = name; - item.NextPermissions = item.EveryOnePermissions; - item.Owner = client.AgentId; - item.SalePrice = 10; - item.SaleType = (byte)SaleType.Not; - ((Scene)client.Scene).AddInventoryItem(client, item); - } - - private void OnAcceptCallingCard(IClientAPI client, UUID transactionID, UUID folderID) - { - m_log.DebugFormat("[CALLING CARD]: User {0} ({1} {2}) accepted tid {3}, folder {4}", - client.AgentId, - client.FirstName, client.LastName, - transactionID, folderID); - UUID destID; - lock (m_pendingCallingcardRequests) - { - if (!m_pendingCallingcardRequests.TryGetValue(transactionID, out destID)) - { - m_log.WarnFormat("[CALLING CARD]: Got a AcceptCallingCard from {0} without an offer before.", - client.Name); - return; - } - // else found pending calling card request with that transaction. - m_pendingCallingcardRequests.Remove(transactionID); - } - - - ScenePresence destAgent = GetAnyPresenceFromAgentID(destID); - // inform sender of the card that destination declined the offer - if (destAgent != null) destAgent.ControllingClient.SendAcceptCallingCard(transactionID); - - // put a calling card into the inventory of receiver - CreateCallingCard(client, destID, folderID, destAgent.Name); - } - - private void OnDeclineCallingCard(IClientAPI client, UUID transactionID) - { - m_log.DebugFormat("[CALLING CARD]: User {0} (ID:{1}) declined card, tid {2}", - client.Name, client.AgentId, transactionID); - UUID destID; - lock (m_pendingCallingcardRequests) - { - if (!m_pendingCallingcardRequests.TryGetValue(transactionID, out destID)) - { - m_log.WarnFormat("[CALLING CARD]: Got a AcceptCallingCard from {0} without an offer before.", - client.Name); - return; - } - // else found pending calling card request with that transaction. - m_pendingCallingcardRequests.Remove(transactionID); - } - - ScenePresence destAgent = GetAnyPresenceFromAgentID(destID); - // inform sender of the card that destination declined the offer - if (destAgent != null) destAgent.ControllingClient.SendDeclineCallingCard(transactionID); - } - - /// - /// Send presence information about a client to other clients in both this region and others. - /// - /// - /// - /// - private void SendPresenceState(IClientAPI client, List friendList, bool iAmOnline) - { - //m_log.DebugFormat("[FRIEND]: {0} logged {1}; sending presence updates", client.Name, iAmOnline ? "in" : "out"); - - if (friendList == null || friendList.Count == 0) - { - //m_log.DebugFormat("[FRIEND]: {0} doesn't have friends.", client.Name); - return; // nothing we can do if she doesn't have friends... - } - - // collect sets of friendIDs; to send to (online and offline), and to receive from - // TODO: If we ever switch to .NET >= 3, replace those Lists with HashSets. - // I can't believe that we have Dictionaries, but no Sets, considering Java introduced them years ago... - List friendIDsToSendTo = new List(); - List candidateFriendIDsToReceive = new List(); - - foreach (FriendListItem item in friendList) - { - if (((item.FriendListOwnerPerms | item.FriendPerms) & (uint)FriendRights.CanSeeOnline) != 0) - { - // friend is allowed to see my presence => add - if ((item.FriendListOwnerPerms & (uint)FriendRights.CanSeeOnline) != 0) - friendIDsToSendTo.Add(item.Friend); - - if ((item.FriendPerms & (uint)FriendRights.CanSeeOnline) != 0) - candidateFriendIDsToReceive.Add(item.Friend); - } - } - - // we now have a list of "interesting" friends (which we have to find out on-/offline state for), - // friends we want to send our online state to (if *they* are online, too), and - // friends we want to receive online state for (currently unknown whether online or not) - - // as this processing might take some time and friends might TP away, we try up to three times to - // reach them. Most of the time, we *will* reach them, and this loop won't loop - int retry = 0; - do - { - // build a list of friends to look up region-information and on-/offline-state for - List friendIDsToLookup = new List(friendIDsToSendTo); - foreach (UUID uuid in candidateFriendIDsToReceive) - { - if (!friendIDsToLookup.Contains(uuid)) friendIDsToLookup.Add(uuid); - } - - m_log.DebugFormat( - "[FRIEND]: {0} to lookup, {1} to send to, {2} candidates to receive from for agent {3}", - friendIDsToLookup.Count, friendIDsToSendTo.Count, candidateFriendIDsToReceive.Count, client.Name); - - // we have to fetch FriendRegionInfos, as the (cached) FriendListItems don't - // necessarily contain the correct online state... - Dictionary friendRegions = m_initialScene.GetFriendRegionInfos(friendIDsToLookup); - m_log.DebugFormat( - "[FRIEND]: Found {0} regionInfos for {1} friends of {2}", - friendRegions.Count, friendIDsToLookup.Count, client.Name); - - // argument for SendAgentOn/Offline; we shouldn't generate that repeatedly within loops. - UUID[] agentArr = new UUID[] { client.AgentId }; - - // first, send to friend presence state to me, if I'm online... - if (iAmOnline) - { - List friendIDsToReceive = new List(); - - for (int i = candidateFriendIDsToReceive.Count - 1; i >= 0; --i) - { - UUID uuid = candidateFriendIDsToReceive[i]; - FriendRegionInfo info; - if (friendRegions.TryGetValue(uuid, out info) && info != null && info.isOnline) - { - friendIDsToReceive.Add(uuid); - } - } - - m_log.DebugFormat( - "[FRIEND]: Sending {0} online friends to {1}", friendIDsToReceive.Count, client.Name); - - if (friendIDsToReceive.Count > 0) - client.SendAgentOnline(friendIDsToReceive.ToArray()); - - // clear them for a possible second iteration; we don't have to repeat this - candidateFriendIDsToReceive.Clear(); - } - - // now, send my presence state to my friends - for (int i = friendIDsToSendTo.Count - 1; i >= 0; --i) - { - UUID uuid = friendIDsToSendTo[i]; - FriendRegionInfo info; - if (friendRegions.TryGetValue(uuid, out info) && info != null && info.isOnline) - { - // any client is good enough, root or child... - ScenePresence agent = GetAnyPresenceFromAgentID(uuid); - if (agent != null) - { - m_log.DebugFormat("[FRIEND]: Found local agent {0}", agent.Name); - - // friend is online and on this server... - if (iAmOnline) agent.ControllingClient.SendAgentOnline(agentArr); - else agent.ControllingClient.SendAgentOffline(agentArr); - - // done, remove it - friendIDsToSendTo.RemoveAt(i); - } - } - else - { - m_log.DebugFormat("[FRIEND]: Friend {0} ({1}) is offline; not sending.", uuid, i); - - // friend is offline => no need to try sending - friendIDsToSendTo.RemoveAt(i); - } - } - - m_log.DebugFormat("[FRIEND]: Have {0} friends to contact via inter-region comms.", friendIDsToSendTo.Count); - - // we now have all the friends left that are online (we think), but not on this region-server - if (friendIDsToSendTo.Count > 0) - { - // sort them into regions - Dictionary> friendsInRegion = new Dictionary>(); - foreach (UUID uuid in friendIDsToSendTo) - { - ulong handle = friendRegions[uuid].regionHandle; // this can't fail as we filtered above already - List friends; - if (!friendsInRegion.TryGetValue(handle, out friends)) - { - friends = new List(); - friendsInRegion[handle] = friends; - } - friends.Add(uuid); - } - m_log.DebugFormat("[FRIEND]: Found {0} regions to send to.", friendRegions.Count); - - // clear uuids list and collect missed friends in it for the next retry - friendIDsToSendTo.Clear(); - - // send bulk updates to the region - foreach (KeyValuePair> pair in friendsInRegion) - { - m_log.DebugFormat("[FRIEND]: Inform {0} friends in region {1} that user {2} is {3}line", - pair.Value.Count, pair.Key, client.Name, iAmOnline ? "on" : "off"); - - friendIDsToSendTo.AddRange(m_initialScene.InformFriendsInOtherRegion(client.AgentId, pair.Key, pair.Value, iAmOnline)); - } - } - // now we have in friendIDsToSendTo only the agents left that TPed away while we tried to contact them. - // In most cases, it will be empty, and it won't loop here. But sometimes, we have to work harder and try again... - } - while (++retry < 3 && friendIDsToSendTo.Count > 0); - } - - private void OnEconomyDataRequest(UUID agentID) - { - // KLUDGE: This is the only way I found to get a message (only) after login was completed and the - // client is connected enough to receive UDP packets). - // This packet seems to be sent only once, just after connection was established to the first - // region after login. - // We use it here to trigger a presence update; the old update-on-login was never be heard by - // the freshly logged in viewer, as it wasn't connected to the region at that time. - // TODO: Feel free to replace this by a better solution if you find one. - - // get the agent. This should work every time, as we just got a packet from it - //ScenePresence agent = GetRootPresenceFromAgentID(agentID); - // KLUDGE 2: As this is sent quite early, the avatar isn't here as root agent yet. So, we have to cheat a bit - ScenePresence agent = GetAnyPresenceFromAgentID(agentID); - - // just to be paranoid... - if (agent == null) - { - m_log.ErrorFormat("[FRIEND]: Got a packet from agent {0} who can't be found anymore!?", agentID); - return; - } - - List fl; - lock (m_friendLists) - { - fl = (List)m_friendLists.Get(agent.ControllingClient.AgentId, - m_initialScene.GetFriendList); - } - - // tell everyone that we are online - SendPresenceState(agent.ControllingClient, fl, true); - } - - private void OnLogout(IClientAPI remoteClient) - { - List fl; - lock (m_friendLists) - { - fl = (List)m_friendLists.Get(remoteClient.AgentId, - m_initialScene.GetFriendList); - } - - // tell everyone that we are offline - SendPresenceState(remoteClient, fl, false); - } - } - - #endregion -} diff --git a/OpenSim/Region/Environment/Modules/Avatar/Gestures/GesturesModule.cs b/OpenSim/Region/Environment/Modules/Avatar/Gestures/GesturesModule.cs deleted file mode 100644 index 969c1d8..0000000 --- a/OpenSim/Region/Environment/Modules/Avatar/Gestures/GesturesModule.cs +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using log4net; -using Nini.Config; -using OpenMetaverse; -using OpenSim.Framework; -using OpenSim.Framework.Communications; -using OpenSim.Framework.Communications.Cache; -using OpenSim.Region.Framework.Interfaces; -using OpenSim.Region.Framework.Scenes; -using System.Reflection; - -namespace OpenSim.Region.Environment.Modules.Avatar.Gestures -{ - public class GesturesModule : IRegionModule - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - protected Scene m_scene; - - public void Initialise(Scene scene, IConfigSource source) - { - m_scene = scene; - - m_scene.EventManager.OnNewClient += OnNewClient; - } - - public void PostInitialise() {} - public void Close() {} - public string Name { get { return "Gestures Module"; } } - public bool IsSharedModule { get { return false; } } - - private void OnNewClient(IClientAPI client) - { - client.OnActivateGesture += ActivateGesture; - client.OnDeactivateGesture += DeactivateGesture; - } - - public virtual void ActivateGesture(IClientAPI client, UUID assetId, UUID gestureId) - { - CachedUserInfo userInfo = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(client.AgentId); - - if (userInfo != null) - { - InventoryItemBase item = userInfo.RootFolder.FindItem(gestureId); - if (item != null) - { - item.Flags = 1; - userInfo.UpdateItem(item); - } - else - m_log.ErrorFormat( - "[GESTURES]: Unable to find gesture to activate {0} for {1}", gestureId, client.Name); - } - else - m_log.ErrorFormat("[GESTURES]: Unable to find user {0}", client.Name); - } - - public virtual void DeactivateGesture(IClientAPI client, UUID gestureId) - { - CachedUserInfo userInfo = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(client.AgentId); - - if (userInfo != null) - { - InventoryItemBase item = userInfo.RootFolder.FindItem(gestureId); - if (item != null) - { - item.Flags = 0; - userInfo.UpdateItem(item); - } - else - m_log.ErrorFormat( - "[GESTURES]: Unable to find gesture to deactivate {0} for {1}", gestureId, client.Name); - } - else - m_log.ErrorFormat("[GESTURES]: Unable to find user {0}", client.Name); - } - } -} \ 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 deleted file mode 100644 index e654912..0000000 --- a/OpenSim/Region/Environment/Modules/Avatar/Groups/GroupsModule.cs +++ /dev/null @@ -1,223 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using System.Reflection; -using OpenMetaverse; -using log4net; -using Nini.Config; -using OpenSim.Framework; -using OpenSim.Region.Framework.Interfaces; -using OpenSim.Region.Framework.Scenes; - -namespace OpenSim.Region.Environment.Modules.Avatar.Groups -{ - public class GroupsModule : IRegionModule - { - private static readonly ILog m_log = - LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private Dictionary m_GroupMap = - new Dictionary(); - - private Dictionary m_ClientMap = - new Dictionary(); - - private UUID opensimulatorGroupID = - new UUID("00000000-68f9-1111-024e-222222111123"); - - private List m_SceneList = new List(); - - private static GroupMembershipData osGroup = - new GroupMembershipData(); - - #region IRegionModule Members - - public void Initialise(Scene scene, IConfigSource config) - { - IConfig groupsConfig = config.Configs["Groups"]; - - if (groupsConfig == null) - { - m_log.Info("[GROUPS]: No configuration found. Using defaults"); - } - else - { - if (!groupsConfig.GetBoolean("Enabled", false)) - { - m_log.Info("[GROUPS]: Groups disabled in configuration"); - return; - } - - if (groupsConfig.GetString("Module", "Default") != "Default") - return; - } - - lock (m_SceneList) - { - if (!m_SceneList.Contains(scene)) - { - if (m_SceneList.Count == 0) - { - osGroup.GroupID = opensimulatorGroupID; - osGroup.GroupName = "OpenSimulator Testing"; - osGroup.GroupPowers = - (uint)(GroupPowers.AllowLandmark | - GroupPowers.AllowSetHome); - m_GroupMap[opensimulatorGroupID] = osGroup; - } - m_SceneList.Add(scene); - } - } - - scene.EventManager.OnNewClient += OnNewClient; - scene.EventManager.OnClientClosed += OnClientClosed; - scene.EventManager.OnIncomingInstantMessage += - OnGridInstantMessage; - } - - public void PostInitialise() - { - } - - public void Close() - { -// m_log.Debug("[GROUPS]: Shutting down group module."); - - lock (m_ClientMap) - { - m_ClientMap.Clear(); - } - - lock (m_GroupMap) - { - m_GroupMap.Clear(); - } - } - - public string Name - { - get { return "GroupsModule"; } - } - - public bool IsSharedModule - { - get { return true; } - } - - #endregion - - private void OnNewClient(IClientAPI client) - { - // Subscribe to instant messages - client.OnInstantMessage += OnInstantMessage; - client.OnAgentDataUpdateRequest += OnAgentDataUpdateRequest; - client.OnUUIDGroupNameRequest += HandleUUIDGroupNameRequest; - lock (m_ClientMap) - { - if (!m_ClientMap.ContainsKey(client.AgentId)) - { - m_ClientMap.Add(client.AgentId, client); - } - } - - GroupMembershipData[] updateGroups = new GroupMembershipData[1]; - updateGroups[0] = osGroup; - - client.SendGroupMembership(updateGroups); - } - - private void OnAgentDataUpdateRequest(IClientAPI remoteClient, - UUID AgentID, UUID SessionID) - { - UUID ActiveGroupID; - string ActiveGroupName; - ulong ActiveGroupPowers; - - string firstname = remoteClient.FirstName; - string lastname = remoteClient.LastName; - - string ActiveGroupTitle = "I IZ N0T"; - - ActiveGroupID = osGroup.GroupID; - ActiveGroupName = osGroup.GroupName; - ActiveGroupPowers = osGroup.GroupPowers; - - remoteClient.SendAgentDataUpdate(AgentID, ActiveGroupID, firstname, - lastname, ActiveGroupPowers, ActiveGroupName, - ActiveGroupTitle); - } - - private void OnInstantMessage(IClientAPI client, GridInstantMessage im) - { - } - - private void OnGridInstantMessage(GridInstantMessage msg) - { - // Trigger the above event handler - OnInstantMessage(null, msg); - } - - private void HandleUUIDGroupNameRequest(UUID id,IClientAPI remote_client) - { - string groupnamereply = "Unknown"; - UUID groupUUID = UUID.Zero; - - lock (m_GroupMap) - { - if (m_GroupMap.ContainsKey(id)) - { - GroupMembershipData grp = m_GroupMap[id]; - groupnamereply = grp.GroupName; - groupUUID = grp.GroupID; - } - } - remote_client.SendGroupNameReply(groupUUID, groupnamereply); - } - - private void OnClientClosed(UUID agentID) - { - lock (m_ClientMap) - { - if (m_ClientMap.ContainsKey(agentID)) - { -// IClientAPI cli = m_ClientMap[agentID]; -// if (cli != null) -// { -// //m_log.Info("[GROUPS]: Removing all reference to groups for " + cli.Name); -// } -// else -// { -// //m_log.Info("[GROUPS]: Removing all reference to groups for " + agentID.ToString()); -// } - m_ClientMap.Remove(agentID); - } - } - } - } -} diff --git a/OpenSim/Region/Environment/Modules/Avatar/InstantMessage/InstantMessageModule.cs b/OpenSim/Region/Environment/Modules/Avatar/InstantMessage/InstantMessageModule.cs deleted file mode 100644 index 3a1b282..0000000 --- a/OpenSim/Region/Environment/Modules/Avatar/InstantMessage/InstantMessageModule.cs +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using System.Net; -using System.Threading; -using OpenMetaverse; -using log4net; -using Nini.Config; -using Nwc.XmlRpc; -using OpenSim.Framework; -using OpenSim.Framework.Client; -using OpenSim.Region.Framework.Interfaces; -using OpenSim.Region.Framework.Scenes; - -namespace OpenSim.Region.Environment.Modules.Avatar.InstantMessage -{ - public class InstantMessageModule : IRegionModule - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - /// - /// Is this module enabled? - /// - private bool m_enabled = false; - - private readonly List m_scenes = new List(); - - #region IRegionModule Members - - private IMessageTransferModule m_TransferModule = null; - - public void Initialise(Scene scene, IConfigSource config) - { - if (config.Configs["Messaging"] != null) - { - if (config.Configs["Messaging"].GetString( - "InstantMessageModule", "InstantMessageModule") != - "InstantMessageModule") - return; - } - - m_enabled = true; - - lock (m_scenes) - { - if (!m_scenes.Contains(scene)) - { - m_scenes.Add(scene); - scene.EventManager.OnClientConnect += OnClientConnect; - scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage; - } - } - } - - void OnClientConnect(IClientCore client) - { - IClientIM clientIM; - if (client.TryGet(out clientIM)) - { - clientIM.OnInstantMessage += OnInstantMessage; - } - } - - public void PostInitialise() - { - if (!m_enabled) - return; - - m_TransferModule = - m_scenes[0].RequestModuleInterface(); - - if (m_TransferModule == null) - m_log.Error("[INSTANT MESSAGE]: No message transfer module, "+ - "IM will not work!"); - } - - public void Close() - { - } - - public string Name - { - get { return "InstantMessageModule"; } - } - - public bool IsSharedModule - { - get { return true; } - } - - #endregion - - public void OnInstantMessage(IClientAPI client, GridInstantMessage im) - { - byte dialog = im.dialog; - - if ( dialog != (byte)InstantMessageDialog.MessageFromAgent - && dialog != (byte)InstantMessageDialog.StartTyping - && dialog != (byte)InstantMessageDialog.StopTyping) - { - return; - } - - if (m_TransferModule != null) - { - m_TransferModule.SendInstantMessage(im, - delegate(bool success) - { - if (dialog == (uint)InstantMessageDialog.StartTyping || - dialog == (uint)InstantMessageDialog.StopTyping) - { - return; - } - - if ((client != null) && !success) - { - client.SendInstantMessage(new UUID(im.toAgentID), - "Unable to send instant message. "+ - "User is not logged in.", - new UUID(im.fromAgentID), "System", - (byte)InstantMessageDialog.BusyAutoResponse, - (uint)Util.UnixTimeSinceEpoch()); - } - } - ); - } - } - - /// - /// - /// - /// - private void OnGridInstantMessage(GridInstantMessage msg) - { - // Just call the Text IM handler above - // This event won't be raised unless we have that agent, - // so we can depend on the above not trying to send - // via grid again - // - OnInstantMessage(null, msg); - } - } -} diff --git a/OpenSim/Region/Environment/Modules/Avatar/InstantMessage/MessageTransferModule.cs b/OpenSim/Region/Environment/Modules/Avatar/InstantMessage/MessageTransferModule.cs deleted file mode 100644 index 347c305..0000000 --- a/OpenSim/Region/Environment/Modules/Avatar/InstantMessage/MessageTransferModule.cs +++ /dev/null @@ -1,655 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using System.Net; -using System.Threading; -using OpenMetaverse; -using log4net; -using Nini.Config; -using Nwc.XmlRpc; -using OpenSim.Framework; -using OpenSim.Framework.Client; -using OpenSim.Region.Framework.Interfaces; -using OpenSim.Region.Framework.Scenes; - -namespace OpenSim.Region.Environment.Modules.Avatar.InstantMessage -{ - public class MessageTransferModule : IRegionModule, IMessageTransferModule - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - // private bool m_Enabled = false; - private bool m_Gridmode = false; - private List m_Scenes = new List(); - private Dictionary m_UserRegionMap = new Dictionary(); - - public void Initialise(Scene scene, IConfigSource config) - { - IConfig cnf = config.Configs["Messaging"]; - if (cnf != null && cnf.GetString( - "MessageTransferModule", "MessageTransferModule") != - "MessageTransferModule") - return; - - cnf = config.Configs["Startup"]; - if (cnf != null) - m_Gridmode = cnf.GetBoolean("gridmode", false); - - // m_Enabled = true; - - lock (m_Scenes) - { - if (m_Scenes.Count == 0) - { - scene.CommsManager.HttpServer.AddXmlRPCHandler( - "grid_instant_message", processXMLRPCGridInstantMessage); - } - - scene.RegisterModuleInterface(this); - m_Scenes.Add(scene); - } - } - - public void PostInitialise() - { - } - - public void Close() - { - } - - public string Name - { - get { return "MessageTransferModule"; } - } - - public bool IsSharedModule - { - get { return true; } - } - - public void SendInstantMessage(GridInstantMessage im, MessageResultNotification result) - { - UUID toAgentID = new UUID(im.toAgentID); - - m_log.DebugFormat("[INSTANT MESSAGE]: Attempting delivery of IM from {0} to {1}", im.fromAgentName, toAgentID.ToString()); - - // Try root avatar only first - foreach (Scene scene in m_Scenes) - { - if (scene.Entities.ContainsKey(toAgentID) && - scene.Entities[toAgentID] is ScenePresence) - { - m_log.DebugFormat("[INSTANT MESSAGE]: Looking for {0} in {1}", toAgentID.ToString(), scene.RegionInfo.RegionName); - // Local message - ScenePresence user = (ScenePresence) scene.Entities[toAgentID]; - if (!user.IsChildAgent) - { - m_log.DebugFormat("[INSTANT MESSAGE]: Delivering to client"); - user.ControllingClient.SendInstantMessage( - new UUID(im.fromAgentID), - im.message, - new UUID(im.toAgentID), - im.fromAgentName, - im.dialog, - im.timestamp, - new UUID(im.imSessionID), - im.fromGroup, - im.binaryBucket); - // Message sent - result(true); - return; - } - } - } - - // try child avatar second - foreach (Scene scene in m_Scenes) - { -// m_log.DebugFormat( -// "[INSTANT MESSAGE]: Looking for child of {0} in {1}", toAgentID, scene.RegionInfo.RegionName); - - if (scene.Entities.ContainsKey(toAgentID) && - scene.Entities[toAgentID] is ScenePresence) - { - // Local message - ScenePresence user = (ScenePresence) scene.Entities[toAgentID]; - - m_log.DebugFormat("[INSTANT MESSAGE]: Delivering to client"); - user.ControllingClient.SendInstantMessage( - new UUID(im.fromAgentID), - im.message, - new UUID(im.toAgentID), - im.fromAgentName, - im.dialog, - im.timestamp, - new UUID(im.imSessionID), - im.fromGroup, - im.binaryBucket); - // Message sent - result(true); - return; - } - } - - if (m_Gridmode) - { - //m_log.DebugFormat("[INSTANT MESSAGE]: Delivering via grid"); - // Still here, try send via Grid - SendGridInstantMessageViaXMLRPC(im, result); - return; - } - - //m_log.DebugFormat("[INSTANT MESSAGE]: Undeliverable"); - result(false); - return; - } - - /// - /// Process a XMLRPC Grid Instant Message - /// - /// XMLRPC parameters - /// - /// Nothing much - protected virtual XmlRpcResponse processXMLRPCGridInstantMessage(XmlRpcRequest request) - { - bool successful = false; - - // TODO: For now, as IMs seem to be a bit unreliable on OSGrid, catch all exception that - // happen here and aren't caught and log them. - try - { - // various rational defaults - UUID fromAgentID = UUID.Zero; - UUID toAgentID = UUID.Zero; - UUID imSessionID = UUID.Zero; - uint timestamp = 0; - string fromAgentName = ""; - string message = ""; - byte dialog = (byte)0; - bool fromGroup = false; - byte offline = (byte)0; - uint ParentEstateID=0; - Vector3 Position = Vector3.Zero; - UUID RegionID = UUID.Zero ; - byte[] binaryBucket = new byte[0]; - - float pos_x = 0; - float pos_y = 0; - float pos_z = 0; - //m_log.Info("Processing IM"); - - - Hashtable requestData = (Hashtable)request.Params[0]; - // Check if it's got all the data - if (requestData.ContainsKey("from_agent_id") - && requestData.ContainsKey("to_agent_id") && requestData.ContainsKey("im_session_id") - && requestData.ContainsKey("timestamp") && requestData.ContainsKey("from_agent_name") - && requestData.ContainsKey("message") && requestData.ContainsKey("dialog") - && requestData.ContainsKey("from_group") - && requestData.ContainsKey("offline") && requestData.ContainsKey("parent_estate_id") - && requestData.ContainsKey("position_x") && requestData.ContainsKey("position_y") - && requestData.ContainsKey("position_z") && requestData.ContainsKey("region_id") - && requestData.ContainsKey("binary_bucket")) - { - // Do the easy way of validating the UUIDs - UUID.TryParse((string)requestData["from_agent_id"], out fromAgentID); - UUID.TryParse((string)requestData["to_agent_id"], out toAgentID); - UUID.TryParse((string)requestData["im_session_id"], out imSessionID); - UUID.TryParse((string)requestData["region_id"], out RegionID); - - try - { - timestamp = (uint)Convert.ToInt32((string)requestData["timestamp"]); - } - catch (ArgumentException) - { - } - catch (FormatException) - { - } - catch (OverflowException) - { - } - - fromAgentName = (string)requestData["from_agent_name"]; - message = (string)requestData["message"]; - - // Bytes don't transfer well over XMLRPC, so, we Base64 Encode them. - string requestData1 = (string)requestData["dialog"]; - if (string.IsNullOrEmpty(requestData1)) - { - dialog = 0; - } - else - { - byte[] dialogdata = Convert.FromBase64String(requestData1); - dialog = dialogdata[0]; - } - - if ((string)requestData["from_group"] == "TRUE") - fromGroup = true; - - string requestData2 = (string)requestData["offline"]; - if (String.IsNullOrEmpty(requestData2)) - { - offline = 0; - } - else - { - byte[] offlinedata = Convert.FromBase64String(requestData2); - offline = offlinedata[0]; - } - - try - { - ParentEstateID = (uint)Convert.ToInt32((string)requestData["parent_estate_id"]); - } - catch (ArgumentException) - { - } - catch (FormatException) - { - } - catch (OverflowException) - { - } - - try - { - pos_x = (uint)Convert.ToInt32((string)requestData["position_x"]); - } - catch (ArgumentException) - { - } - catch (FormatException) - { - } - catch (OverflowException) - { - } - try - { - pos_y = (uint)Convert.ToInt32((string)requestData["position_y"]); - } - catch (ArgumentException) - { - } - catch (FormatException) - { - } - catch (OverflowException) - { - } - try - { - pos_z = (uint)Convert.ToInt32((string)requestData["position_z"]); - } - catch (ArgumentException) - { - } - catch (FormatException) - { - } - catch (OverflowException) - { - } - - Position = new Vector3(pos_x, pos_y, pos_z); - - string requestData3 = (string)requestData["binary_bucket"]; - if (string.IsNullOrEmpty(requestData3)) - { - binaryBucket = new byte[0]; - } - else - { - binaryBucket = Convert.FromBase64String(requestData3); - } - - // Create a New GridInstantMessageObject the the data - GridInstantMessage gim = new GridInstantMessage(); - gim.fromAgentID = fromAgentID.Guid; - gim.fromAgentName = fromAgentName; - gim.fromGroup = fromGroup; - gim.imSessionID = imSessionID.Guid; - gim.RegionID = RegionID.Guid; - gim.timestamp = timestamp; - gim.toAgentID = toAgentID.Guid; - gim.message = message; - gim.dialog = dialog; - gim.offline = offline; - gim.ParentEstateID = ParentEstateID; - gim.Position = Position; - gim.binaryBucket = binaryBucket; - - - // Trigger the Instant message in the scene. - foreach (Scene scene in m_Scenes) - { - if (scene.Entities.ContainsKey(toAgentID) && - scene.Entities[toAgentID] is ScenePresence) - { - ScenePresence user = - (ScenePresence)scene.Entities[toAgentID]; - - if (!user.IsChildAgent) - { - scene.EventManager.TriggerIncomingInstantMessage(gim); - successful = true; - } - } - } - if (!successful) - { - // If the message can't be delivered to an agent, it - // is likely to be a group IM. On a group IM, the - // imSessionID = toAgentID = group id. Raise the - // unhandled IM event to give the groups module - // a chance to pick it up. We raise that in a random - // scene, since the groups module is shared. - // - m_Scenes[0].EventManager.TriggerUnhandledInstantMessage(gim); - } - } - } - catch (Exception e) - { - m_log.Error("[INSTANT MESSAGE]: Caught unexpected exception:", e); - successful = false; - } - - //Send response back to region calling if it was successful - // calling region uses this to know when to look up a user's location again. - XmlRpcResponse resp = new XmlRpcResponse(); - Hashtable respdata = new Hashtable(); - if (successful) - respdata["success"] = "TRUE"; - else - respdata["success"] = "FALSE"; - resp.Value = respdata; - - return resp; - } - - /// - /// delegate for sending a grid instant message asynchronously - /// - public delegate void GridInstantMessageDelegate(GridInstantMessage im, MessageResultNotification result, ulong prevRegionHandle); - - private void GridInstantMessageCompleted(IAsyncResult iar) - { - GridInstantMessageDelegate icon = - (GridInstantMessageDelegate)iar.AsyncState; - icon.EndInvoke(iar); - } - - - protected virtual void SendGridInstantMessageViaXMLRPC(GridInstantMessage im, MessageResultNotification result) - { - GridInstantMessageDelegate d = SendGridInstantMessageViaXMLRPCAsync; - - d.BeginInvoke(im, result, 0, GridInstantMessageCompleted, d); - } - - /// - /// Recursive SendGridInstantMessage over XMLRPC method. - /// This is called from within a dedicated thread. - /// The first time this is called, prevRegionHandle will be 0 Subsequent times this is called from - /// itself, prevRegionHandle will be the last region handle that we tried to send. - /// If the handles are the same, we look up the user's location using the grid. - /// If the handles are still the same, we end. The send failed. - /// - /// - /// Pass in 0 the first time this method is called. It will be called recursively with the last - /// regionhandle tried - /// - protected virtual void SendGridInstantMessageViaXMLRPCAsync(GridInstantMessage im, MessageResultNotification result, ulong prevRegionHandle) - { - UUID toAgentID = new UUID(im.toAgentID); - - UserAgentData upd = null; - - bool lookupAgent = false; - - lock (m_UserRegionMap) - { - if (m_UserRegionMap.ContainsKey(toAgentID)) - { - upd = new UserAgentData(); - upd.AgentOnline = true; - upd.Handle = m_UserRegionMap[toAgentID]; - - // We need to compare the current regionhandle with the previous region handle - // or the recursive loop will never end because it will never try to lookup the agent again - if (prevRegionHandle == upd.Handle) - { - lookupAgent = true; - } - } - else - { - lookupAgent = true; - } - } - - - // Are we needing to look-up an agent? - if (lookupAgent) - { - // Non-cached user agent lookup. - upd = m_Scenes[0].CommsManager.UserService.GetAgentByUUID(toAgentID); - - if (upd != null) - { - // check if we've tried this before.. - // This is one way to end the recursive loop - // - if (upd.Handle == prevRegionHandle) - { - m_log.Error("[GRID INSTANT MESSAGE]: Unable to deliver an instant message"); - result(false); - return; - } - } - else - { - m_log.Error("[GRID INSTANT MESSAGE]: Unable to deliver an instant message"); - result(false); - return; - } - } - - if (upd != null) - { - if (upd.AgentOnline) - { - RegionInfo reginfo = m_Scenes[0].SceneGridService.RequestNeighbouringRegionInfo(upd.Handle); - if (reginfo != null) - { - Hashtable msgdata = ConvertGridInstantMessageToXMLRPC(im); - // Not actually used anymore, left in for compatibility - // Remove at next interface change - // - msgdata["region_handle"] = 0; - bool imresult = doIMSending(reginfo, msgdata); - if (imresult) - { - // IM delivery successful, so store the Agent's location in our local cache. - lock (m_UserRegionMap) - { - if (m_UserRegionMap.ContainsKey(toAgentID)) - { - m_UserRegionMap[toAgentID] = upd.Handle; - } - else - { - m_UserRegionMap.Add(toAgentID, upd.Handle); - } - } - result(true); - } - else - { - // try again, but lookup user this time. - // Warning, this must call the Async version - // of this method or we'll be making thousands of threads - // The version within the spawned thread is SendGridInstantMessageViaXMLRPCAsync - // The version that spawns the thread is SendGridInstantMessageViaXMLRPC - - // This is recursive!!!!! - SendGridInstantMessageViaXMLRPCAsync(im, result, - upd.Handle); - } - - } - else - { - m_log.WarnFormat("[GRID INSTANT MESSAGE]: Unable to find region {0}", upd.Handle); - result(false); - } - } - else - { - result(false); - } - } - else - { - m_log.WarnFormat("[GRID INSTANT MESSAGE]: Unable to find user {0}", toAgentID); - result(false); - } - - } - - /// - /// This actually does the XMLRPC Request - /// - /// RegionInfo we pull the data out of to send the request to - /// The Instant Message data Hashtable - /// Bool if the message was successfully delivered at the other side. - private bool doIMSending(RegionInfo reginfo, Hashtable xmlrpcdata) - { - - ArrayList SendParams = new ArrayList(); - SendParams.Add(xmlrpcdata); - XmlRpcRequest GridReq = new XmlRpcRequest("grid_instant_message", SendParams); - try - { - - XmlRpcResponse GridResp = GridReq.Send("http://" + reginfo.ExternalHostName + ":" + reginfo.HttpPort, 3000); - - Hashtable responseData = (Hashtable)GridResp.Value; - - if (responseData.ContainsKey("success")) - { - if ((string)responseData["success"] == "TRUE") - { - return true; - } - else - { - return false; - } - } - else - { - return false; - } - } - catch (WebException e) - { - m_log.ErrorFormat("[GRID INSTANT MESSAGE]: Error sending message to http://{0}:{1} the host didn't respond ({2})", - reginfo.ExternalHostName, reginfo.HttpPort, e.Message); - } - - return false; - } - - /// - /// Get ulong region handle for region by it's Region UUID. - /// We use region handles over grid comms because there's all sorts of free and cool caching. - /// - /// UUID of region to get the region handle for - /// -// private ulong getLocalRegionHandleFromUUID(UUID regionID) -// { -// ulong returnhandle = 0; -// -// lock (m_Scenes) -// { -// foreach (Scene sn in m_Scenes) -// { -// if (sn.RegionInfo.RegionID == regionID) -// { -// returnhandle = sn.RegionInfo.RegionHandle; -// break; -// } -// } -// } -// return returnhandle; -// } - - /// - /// Takes a GridInstantMessage and converts it into a Hashtable for XMLRPC - /// - /// The GridInstantMessage object - /// Hashtable containing the XMLRPC request - private Hashtable ConvertGridInstantMessageToXMLRPC(GridInstantMessage msg) - { - Hashtable gim = new Hashtable(); - gim["from_agent_id"] = msg.fromAgentID.ToString(); - // Kept for compatibility - gim["from_agent_session"] = UUID.Zero.ToString(); - gim["to_agent_id"] = msg.toAgentID.ToString(); - gim["im_session_id"] = msg.imSessionID.ToString(); - gim["timestamp"] = msg.timestamp.ToString(); - gim["from_agent_name"] = msg.fromAgentName; - gim["message"] = msg.message; - byte[] dialogdata = new byte[1];dialogdata[0] = msg.dialog; - gim["dialog"] = Convert.ToBase64String(dialogdata,Base64FormattingOptions.None); - - if (msg.fromGroup) - gim["from_group"] = "TRUE"; - else - gim["from_group"] = "FALSE"; - byte[] offlinedata = new byte[1]; offlinedata[0] = msg.offline; - gim["offline"] = Convert.ToBase64String(offlinedata, Base64FormattingOptions.None); - gim["parent_estate_id"] = msg.ParentEstateID.ToString(); - gim["position_x"] = msg.Position.X.ToString(); - gim["position_y"] = msg.Position.Y.ToString(); - gim["position_z"] = msg.Position.Z.ToString(); - gim["region_id"] = msg.RegionID.ToString(); - gim["binary_bucket"] = Convert.ToBase64String(msg.binaryBucket,Base64FormattingOptions.None); - return gim; - } - - } -} diff --git a/OpenSim/Region/Environment/Modules/Avatar/InstantMessage/PresenceModule.cs b/OpenSim/Region/Environment/Modules/Avatar/InstantMessage/PresenceModule.cs deleted file mode 100644 index c84d3d5..0000000 --- a/OpenSim/Region/Environment/Modules/Avatar/InstantMessage/PresenceModule.cs +++ /dev/null @@ -1,426 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using System.Net; -using System.Threading; -using OpenMetaverse; -using log4net; -using Nini.Config; -using Nwc.XmlRpc; -using OpenSim.Framework; -using OpenSim.Framework.Client; -using OpenSim.Region.Framework.Interfaces; -using OpenSim.Region.Framework.Scenes; - -namespace OpenSim.Region.Environment.Modules.Avatar.InstantMessage -{ - public class PresenceModule : IRegionModule, IPresenceModule - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private bool m_Enabled = false; - private bool m_Gridmode = false; - - // some default scene for doing things that aren't connected to a specific scene. Avoids locking. - private Scene m_initialScene; - - private List m_Scenes = new List(); - - // we currently are only interested in root-agents. If the root isn't here, we don't know the region the - // user is in, so we have to ask the messaging server anyway. - private Dictionary m_RootAgents = - new Dictionary(); - - public event PresenceChange OnPresenceChange; - public event BulkPresenceData OnBulkPresenceData; - - public void Initialise(Scene scene, IConfigSource config) - { - lock (m_Scenes) - { - // This is a shared module; Initialise will be called for every region on this server. - // Only check config once for the first region. - if (m_Scenes.Count == 0) - { - IConfig cnf = config.Configs["Messaging"]; - if (cnf != null && cnf.GetString( - "PresenceModule", "PresenceModule") != - "PresenceModule") - return; - - cnf = config.Configs["Startup"]; - if (cnf != null) - m_Gridmode = cnf.GetBoolean("gridmode", false); - - m_Enabled = true; - - m_initialScene = scene; - } - - if (m_Gridmode) - NotifyMessageServerOfStartup(scene); - - m_Scenes.Add(scene); - } - - scene.RegisterModuleInterface(this); - - scene.EventManager.OnNewClient += OnNewClient; - scene.EventManager.OnSetRootAgentScene += OnSetRootAgentScene; - scene.EventManager.OnMakeChildAgent += OnMakeChildAgent; - } - - public void PostInitialise() - { - } - - public void Close() - { - if (!m_Gridmode || !m_Enabled) - return; - - if (OnPresenceChange != null) - { - lock (m_RootAgents) - { - // on shutdown, users are kicked, too - foreach (KeyValuePair pair in m_RootAgents) - { - OnPresenceChange(new PresenceInfo(pair.Key, UUID.Zero)); - } - } - } - - lock (m_Scenes) - { - foreach (Scene scene in m_Scenes) - NotifyMessageServerOfShutdown(scene); - } - } - - public string Name - { - get { return "PresenceModule"; } - } - - public bool IsSharedModule - { - get { return true; } - } - - public void RequestBulkPresenceData(UUID[] users) - { - if (OnBulkPresenceData != null) - { - PresenceInfo[] result = new PresenceInfo[users.Length]; - if (m_Gridmode) - { - // first check the local information - List uuids = new List(); // the uuids to check remotely - List indices = new List(); // just for performance. - lock (m_RootAgents) - { - for (int i = 0; i < uuids.Count; ++i) - { - Scene scene; - if (m_RootAgents.TryGetValue(users[i], out scene)) - { - result[i] = new PresenceInfo(users[i], scene.RegionInfo.RegionID); - } - else - { - uuids.Add(users[i]); - indices.Add(i); - } - } - } - - // now we have filtered out all the local root agents. The rest we have to request info about - Dictionary infos = m_initialScene.GetFriendRegionInfos(uuids); - for (int i = 0; i < uuids.Count; ++i) - { - FriendRegionInfo info; - if (infos.TryGetValue(uuids[i], out info) && info.isOnline) - { - UUID regionID = info.regionID; - if (regionID == UUID.Zero) - { - // TODO this is the old messaging-server protocol; only the regionHandle is available. - // Fetch region-info to get the id - RegionInfo regionInfo = m_initialScene.RequestNeighbouringRegionInfo(info.regionHandle); - regionID = regionInfo.RegionID; - } - result[indices[i]] = new PresenceInfo(uuids[i], regionID); - } - else result[indices[i]] = new PresenceInfo(uuids[i], UUID.Zero); - } - } - else - { - // in standalone mode, we have all the info locally available. - lock (m_RootAgents) - { - for (int i = 0; i < users.Length; ++i) - { - Scene scene; - if (m_RootAgents.TryGetValue(users[i], out scene)) - { - result[i] = new PresenceInfo(users[i], scene.RegionInfo.RegionID); - } - else - { - result[i] = new PresenceInfo(users[i], UUID.Zero); - } - } - } - } - - // tell everyone - OnBulkPresenceData(result); - } - } - - // new client doesn't mean necessarily that user logged in, it just means it entered one of the - // the regions on this server - public void OnNewClient(IClientAPI client) - { - client.OnConnectionClosed += OnConnectionClosed; - client.OnLogout += OnLogout; - - // KLUDGE: See handler for details. - client.OnEconomyDataRequest += OnEconomyDataRequest; - } - - // connection closed just means *one* client connection has been closed. It doesn't mean that the - // user has logged off; it might have just TPed away. - public void OnConnectionClosed(IClientAPI client) - { - // TODO: Have to think what we have to do here... - // Should we just remove the root from the list (if scene matches)? - if (!(client.Scene is Scene)) - return; - Scene scene = (Scene)client.Scene; - - lock (m_RootAgents) - { - Scene rootScene; - if (!(m_RootAgents.TryGetValue(client.AgentId, out rootScene)) || scene != rootScene) - return; - - m_RootAgents.Remove(client.AgentId); - } - - // Should it have logged off, we'll do the logout part in OnLogout, even if no root is stored - // anymore. It logged off, after all... - } - - // Triggered when the user logs off. - public void OnLogout(IClientAPI client) - { - if (!(client.Scene is Scene)) - return; - Scene scene = (Scene)client.Scene; - - // On logout, we really remove the client from rootAgents, even if the scene doesn't match - lock (m_RootAgents) - { - if (m_RootAgents.ContainsKey(client.AgentId)) m_RootAgents.Remove(client.AgentId); - } - - // now inform the messaging server and anyone who is interested - NotifyMessageServerOfAgentLeaving(client.AgentId, scene.RegionInfo.RegionID, scene.RegionInfo.RegionHandle); - if (OnPresenceChange != null) OnPresenceChange(new PresenceInfo(client.AgentId, UUID.Zero)); - } - - public void OnSetRootAgentScene(UUID agentID, Scene scene) - { - // OnSetRootAgentScene can be called from several threads at once (with different agentID). - // Concurrent access to m_RootAgents is prone to failure on multi-core/-processor systems without - // correct locking). - lock (m_RootAgents) - { - Scene rootScene; - if (m_RootAgents.TryGetValue(agentID, out rootScene) && scene == rootScene) - { - return; - } - m_RootAgents[agentID] = scene; - } - // inform messaging server that agent changed the region - NotifyMessageServerOfAgentLocation(agentID, scene.RegionInfo.RegionID, scene.RegionInfo.RegionHandle); - } - - private void OnEconomyDataRequest(UUID agentID) - { - // KLUDGE: This is the only way I found to get a message (only) after login was completed and the - // client is connected enough to receive UDP packets. - // This packet seems to be sent only once, just after connection was established to the first - // region after login. - // We use it here to trigger a presence update; the old update-on-login was never be heard by - // the freshly logged in viewer, as it wasn't connected to the region at that time. - // TODO: Feel free to replace this by a better solution if you find one. - - // get the agent. This should work every time, as we just got a packet from it - ScenePresence agent = null; - lock (m_Scenes) - { - foreach (Scene scene in m_Scenes) - { - agent = scene.GetScenePresence(agentID); - if (agent != null) break; - } - } - - // just to be paranoid... - if (agent == null) - { - m_log.ErrorFormat("[PRESENCE]: Got a packet from agent {0} who can't be found anymore!?", agentID); - return; - } - - // we are a bit premature here, but the next packet will switch this child agent to root. - if (OnPresenceChange != null) OnPresenceChange(new PresenceInfo(agentID, agent.Scene.RegionInfo.RegionID)); - } - - public void OnMakeChildAgent(ScenePresence agent) - { - // OnMakeChildAgent can be called from several threads at once (with different agent). - // Concurrent access to m_RootAgents is prone to failure on multi-core/-processor systems without - // correct locking). - lock (m_RootAgents) - { - Scene rootScene; - if (m_RootAgents.TryGetValue(agent.UUID, out rootScene) && agent.Scene == rootScene) - { - m_RootAgents.Remove(agent.UUID); - } - } - // don't notify the messaging-server; either this agent just had been downgraded and another one will be upgraded - // to root momentarily (which will notify the messaging-server), or possibly it will be closed in a moment, - // which will update the messaging-server, too. - } - - private void NotifyMessageServerOfStartup(Scene scene) - { - Hashtable xmlrpcdata = new Hashtable(); - xmlrpcdata["RegionUUID"] = scene.RegionInfo.RegionID.ToString(); - ArrayList SendParams = new ArrayList(); - SendParams.Add(xmlrpcdata); - try - { - XmlRpcRequest UpRequest = new XmlRpcRequest("region_startup", SendParams); - XmlRpcResponse resp = UpRequest.Send(scene.CommsManager.NetworkServersInfo.MessagingURL, 5000); - - Hashtable responseData = (Hashtable)resp.Value; - if (responseData == null || (!responseData.ContainsKey("success")) || (string)responseData["success"] != "TRUE") - { - m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of region startup for region {0}", scene.RegionInfo.RegionName); - } - } - catch (System.Net.WebException) - { - m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of region startup for region {0}", scene.RegionInfo.RegionName); - } - } - - private void NotifyMessageServerOfShutdown(Scene scene) - { - Hashtable xmlrpcdata = new Hashtable(); - xmlrpcdata["RegionUUID"] = scene.RegionInfo.RegionID.ToString(); - ArrayList SendParams = new ArrayList(); - SendParams.Add(xmlrpcdata); - try - { - XmlRpcRequest DownRequest = new XmlRpcRequest("region_shutdown", SendParams); - XmlRpcResponse resp = DownRequest.Send(scene.CommsManager.NetworkServersInfo.MessagingURL, 5000); - - Hashtable responseData = (Hashtable)resp.Value; - if ((!responseData.ContainsKey("success")) || (string)responseData["success"] != "TRUE") - { - m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of region shutdown for region {0}", scene.RegionInfo.RegionName); - } - } - catch (System.Net.WebException) - { - m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of region shutdown for region {0}", scene.RegionInfo.RegionName); - } - } - - private void NotifyMessageServerOfAgentLocation(UUID agentID, UUID region, ulong regionHandle) - { - Hashtable xmlrpcdata = new Hashtable(); - xmlrpcdata["AgentID"] = agentID.ToString(); - xmlrpcdata["RegionUUID"] = region.ToString(); - xmlrpcdata["RegionHandle"] = regionHandle.ToString(); - ArrayList SendParams = new ArrayList(); - SendParams.Add(xmlrpcdata); - try - { - XmlRpcRequest LocationRequest = new XmlRpcRequest("agent_location", SendParams); - XmlRpcResponse resp = LocationRequest.Send(m_Scenes[0].CommsManager.NetworkServersInfo.MessagingURL, 5000); - - Hashtable responseData = (Hashtable)resp.Value; - if ((!responseData.ContainsKey("success")) || (string)responseData["success"] != "TRUE") - { - m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of agent location for {0}", agentID.ToString()); - } - } - catch (System.Net.WebException) - { - m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of agent location for {0}", agentID.ToString()); - } - } - - private void NotifyMessageServerOfAgentLeaving(UUID agentID, UUID region, ulong regionHandle) - { - Hashtable xmlrpcdata = new Hashtable(); - xmlrpcdata["AgentID"] = agentID.ToString(); - xmlrpcdata["RegionUUID"] = region.ToString(); - xmlrpcdata["RegionHandle"] = regionHandle.ToString(); - ArrayList SendParams = new ArrayList(); - SendParams.Add(xmlrpcdata); - try - { - XmlRpcRequest LeavingRequest = new XmlRpcRequest("agent_leaving", SendParams); - XmlRpcResponse resp = LeavingRequest.Send(m_Scenes[0].CommsManager.NetworkServersInfo.MessagingURL, 5000); - - Hashtable responseData = (Hashtable)resp.Value; - if ((!responseData.ContainsKey("success")) || (string)responseData["success"] != "TRUE") - { - m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of agent leaving for {0}", agentID.ToString()); - } - } - catch (System.Net.WebException) - { - m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of agent leaving for {0}", agentID.ToString()); - } - } - } -} diff --git a/OpenSim/Region/Environment/Modules/Avatar/Inventory/Archiver/InventoryArchiveReadRequest.cs b/OpenSim/Region/Environment/Modules/Avatar/Inventory/Archiver/InventoryArchiveReadRequest.cs deleted file mode 100644 index 3a58202..0000000 --- a/OpenSim/Region/Environment/Modules/Avatar/Inventory/Archiver/InventoryArchiveReadRequest.cs +++ /dev/null @@ -1,279 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using System.IO; -using System.IO.Compression; -using System.Reflection; -using System.Xml; -using OpenMetaverse; -using OpenSim.Region.Framework.Scenes; -using OpenSim.Region.Environment.Modules.World.Archiver; -using OpenSim.Framework; -using OpenSim.Framework.Communications; -using OpenSim.Framework.Communications.Cache; -using log4net; -using OpenSim.Region.Environment.Modules.World.Serialiser; - - -namespace OpenSim.Region.Environment.Modules.Avatar.Inventory.Archiver -{ - public class InventoryArchiveReadRequest - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - protected Scene scene; - protected TarArchiveReader archive; - private static System.Text.ASCIIEncoding m_asciiEncoding = new System.Text.ASCIIEncoding(); - - CommunicationsManager commsManager; - - public InventoryArchiveReadRequest(Scene currentScene, CommunicationsManager commsManager) - { - //List serialisedObjects = new List(); - scene = currentScene; - this.commsManager = commsManager; - } - - protected InventoryItemBase loadInvItem(string path, string contents) - { - InventoryItemBase item = new InventoryItemBase(); - StringReader sr = new StringReader(contents); - XmlTextReader reader = new XmlTextReader(sr); - - if (contents.Equals("")) return null; - - reader.ReadStartElement("InventoryObject"); - reader.ReadStartElement("Name"); - item.Name = reader.ReadString(); - reader.ReadEndElement(); - reader.ReadStartElement("ID"); - item.ID = UUID.Parse(reader.ReadString()); - reader.ReadEndElement(); - reader.ReadStartElement("InvType"); - item.InvType = System.Convert.ToInt32(reader.ReadString()); - reader.ReadEndElement(); - reader.ReadStartElement("CreatorUUID"); - item.Creator = UUID.Parse(reader.ReadString()); - reader.ReadEndElement(); - reader.ReadStartElement("CreationDate"); - item.CreationDate = System.Convert.ToInt32(reader.ReadString()); - reader.ReadEndElement(); - reader.ReadStartElement("Owner"); - item.Owner = UUID.Parse(reader.ReadString()); - reader.ReadEndElement(); - //No description would kill it - if (reader.IsEmptyElement) - { - reader.ReadStartElement("Description"); - } - else - { - reader.ReadStartElement("Description"); - item.Description = reader.ReadString(); - reader.ReadEndElement(); - } - reader.ReadStartElement("AssetType"); - item.AssetType = System.Convert.ToInt32(reader.ReadString()); - reader.ReadEndElement(); - reader.ReadStartElement("AssetID"); - item.AssetID = UUID.Parse(reader.ReadString()); - reader.ReadEndElement(); - reader.ReadStartElement("SaleType"); - item.SaleType = System.Convert.ToByte(reader.ReadString()); - reader.ReadEndElement(); - reader.ReadStartElement("SalePrice"); - item.SalePrice = System.Convert.ToInt32(reader.ReadString()); - reader.ReadEndElement(); - reader.ReadStartElement("BasePermissions"); - item.BasePermissions = System.Convert.ToUInt32(reader.ReadString()); - reader.ReadEndElement(); - reader.ReadStartElement("CurrentPermissions"); - item.CurrentPermissions = System.Convert.ToUInt32(reader.ReadString()); - reader.ReadEndElement(); - reader.ReadStartElement("EveryOnePermssions"); - item.EveryOnePermissions = System.Convert.ToUInt32(reader.ReadString()); - reader.ReadEndElement(); - reader.ReadStartElement("NextPermissions"); - item.NextPermissions = System.Convert.ToUInt32(reader.ReadString()); - reader.ReadEndElement(); - reader.ReadStartElement("Flags"); - item.Flags = System.Convert.ToUInt32(reader.ReadString()); - reader.ReadEndElement(); - reader.ReadStartElement("GroupID"); - item.GroupID = UUID.Parse(reader.ReadString()); - reader.ReadEndElement(); - reader.ReadStartElement("GroupOwned"); - item.GroupOwned = System.Convert.ToBoolean(reader.ReadString()); - reader.ReadEndElement(); - //reader.ReadStartElement("ParentFolderID"); - //item.Folder = UUID.Parse(reader.ReadString()); - //reader.ReadEndElement(); - //reader.ReadEndElement(); - - return item; - } - - public void execute(string firstName, string lastName, string invPath, string loadPath) - { - string filePath = "ERROR"; - int successfulAssetRestores = 0; - int failedAssetRestores = 0; - int successfulItemRestores = 0; - - UserProfileData userProfile = commsManager.UserService.GetUserProfile(firstName, lastName); - if (null == userProfile) - { - m_log.ErrorFormat("[CONSOLE]: Failed to find user {0} {1}", firstName, lastName); - return; - } - - CachedUserInfo userInfo = commsManager.UserProfileCacheService.GetUserDetails(userProfile.ID); - if (null == userInfo) - { - m_log.ErrorFormat( - "[CONSOLE]: Failed to find user info for {0} {1} {2}", - firstName, lastName, userProfile.ID); - - return; - } - - if (!userInfo.HasReceivedInventory) - { - m_log.ErrorFormat( - "[CONSOLE]: Have not yet received inventory info for user {0} {1} {2}", - firstName, lastName, userProfile.ID); - - return; - } - - InventoryFolderImpl inventoryFolder = userInfo.RootFolder.FindFolderByPath(invPath); - - if (null == inventoryFolder) - { - // TODO: Later on, automatically create this folder if it does not exist - m_log.ErrorFormat("[ARCHIVER]: Inventory path {0} does not exist", invPath); - - return; - } - - archive - = new TarArchiveReader(new GZipStream( - new FileStream(loadPath, FileMode.Open), CompressionMode.Decompress)); - - byte[] data; - TarArchiveReader.TarEntryType entryType; - while ((data = archive.ReadEntry(out filePath, out entryType)) != null) - { - if (entryType == TarArchiveReader.TarEntryType.TYPE_DIRECTORY) { - m_log.WarnFormat("[ARCHIVER]: Ignoring directory entry {0}", filePath); - } else if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH)) - { - if (LoadAsset(filePath, data)) - successfulAssetRestores++; - else - failedAssetRestores++; - } - else - { - InventoryItemBase item = loadInvItem(filePath, m_asciiEncoding.GetString(data)); - - if (item != null) - { - item.Creator = userProfile.ID; - item.Owner = userProfile.ID; - - // Reset folder ID to the one in which we want to load it - // TODO: Properly restore entire folder structure. At the moment all items are dumped in this - // single folder no matter where in the saved folder structure they are. - item.Folder = inventoryFolder.ID; - - userInfo.AddItem(item); - successfulItemRestores++; - } - } - } - - archive.Close(); - - m_log.DebugFormat("[ARCHIVER]: Restored {0} assets", successfulAssetRestores); - m_log.InfoFormat("[ARCHIVER]: Restored {0} items", successfulItemRestores); - } - - /// - /// Load an asset - /// - /// - /// - /// true if asset was successfully loaded, false otherwise - private bool LoadAsset(string assetPath, byte[] data) - { - //IRegionSerialiser serialiser = scene.RequestModuleInterface(); - // Right now we're nastily obtaining the UUID from the filename - string filename = assetPath.Remove(0, ArchiveConstants.ASSETS_PATH.Length); - int i = filename.LastIndexOf(ArchiveConstants.ASSET_EXTENSION_SEPARATOR); - - if (i == -1) - { - m_log.ErrorFormat( - "[ARCHIVER]: Could not find extension information in asset path {0} since it's missing the separator {1}. Skipping", - assetPath, ArchiveConstants.ASSET_EXTENSION_SEPARATOR); - - return false; - } - - string extension = filename.Substring(i); - string uuid = filename.Remove(filename.Length - extension.Length); - - if (ArchiveConstants.EXTENSION_TO_ASSET_TYPE.ContainsKey(extension)) - { - sbyte assetType = ArchiveConstants.EXTENSION_TO_ASSET_TYPE[extension]; - - m_log.DebugFormat("[ARCHIVER]: Importing asset {0}, type {1}", uuid, assetType); - - AssetBase asset = new AssetBase(new UUID(uuid), "RandomName"); - - asset.Metadata.Type = assetType; - asset.Data = data; - - scene.AssetCache.AddAsset(asset); - - - return true; - } - else - { - m_log.ErrorFormat( - "[ARCHIVER]: Tried to dearchive data with path {0} with an unknown type extension {1}", - assetPath, extension); - - return false; - } - } - } -} diff --git a/OpenSim/Region/Environment/Modules/Avatar/Inventory/Archiver/InventoryArchiveWriteRequest.cs b/OpenSim/Region/Environment/Modules/Avatar/Inventory/Archiver/InventoryArchiveWriteRequest.cs deleted file mode 100644 index e23f2a8..0000000 --- a/OpenSim/Region/Environment/Modules/Avatar/Inventory/Archiver/InventoryArchiveWriteRequest.cs +++ /dev/null @@ -1,247 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using System.IO; -using System.IO.Compression; -using System.Reflection; -using System.Xml; -using OpenMetaverse; -using OpenSim.Region.Framework.Scenes; -using OpenSim.Region.Environment.Modules.World.Archiver; -using OpenSim.Framework; -using OpenSim.Framework.Communications; -using OpenSim.Framework.Communications.Cache; -using log4net; - - -namespace OpenSim.Region.Environment.Modules.Avatar.Inventory.Archiver -{ - public class InventoryArchiveWriteRequest - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - protected Scene scene; - protected TarArchiveWriter archive; - protected CommunicationsManager commsManager; - Dictionary assetUuids; - - /// - /// The path to which the inventory archive will be saved. - /// - private string m_savePath; - - public InventoryArchiveWriteRequest(Scene currentScene, CommunicationsManager commsManager) - { - scene = currentScene; - archive = new TarArchiveWriter(); - this.commsManager = commsManager; - assetUuids = new Dictionary(); - } - - protected void ReceivedAllAssets(IDictionary assetsFound, ICollection assetsNotFoundUuids) - { - AssetsArchiver assetsArchiver = new AssetsArchiver(assetsFound); - assetsArchiver.Archive(archive); - archive.WriteTar(new GZipStream(new FileStream(m_savePath, FileMode.Create), CompressionMode.Compress)); - } - - protected void saveInvItem(InventoryItemBase inventoryItem, string path) - { - string filename - = string.Format("{0}{1}_{2}.xml", - path, inventoryItem.Name, inventoryItem.ID); - StringWriter sw = new StringWriter(); - XmlTextWriter writer = new XmlTextWriter(sw); - writer.WriteStartElement("InventoryObject"); - writer.WriteStartElement("Name"); - writer.WriteString(inventoryItem.Name); - writer.WriteEndElement(); - writer.WriteStartElement("ID"); - writer.WriteString(inventoryItem.ID.ToString()); - writer.WriteEndElement(); - writer.WriteStartElement("InvType"); - writer.WriteString(inventoryItem.InvType.ToString()); - writer.WriteEndElement(); - writer.WriteStartElement("CreatorUUID"); - writer.WriteString(inventoryItem.Creator.ToString()); - writer.WriteEndElement(); - writer.WriteStartElement("CreationDate"); - writer.WriteString(inventoryItem.CreationDate.ToString()); - writer.WriteEndElement(); - writer.WriteStartElement("Owner"); - writer.WriteString(inventoryItem.Owner.ToString()); - writer.WriteEndElement(); - writer.WriteStartElement("Description"); - if (inventoryItem.Description.Length > 0) - writer.WriteString(inventoryItem.Description); - else writer.WriteString("No Description"); - writer.WriteEndElement(); - writer.WriteStartElement("AssetType"); - writer.WriteString(inventoryItem.AssetType.ToString()); - writer.WriteEndElement(); - writer.WriteStartElement("AssetID"); - writer.WriteString(inventoryItem.AssetID.ToString()); - writer.WriteEndElement(); - writer.WriteStartElement("SaleType"); - writer.WriteString(inventoryItem.SaleType.ToString()); - writer.WriteEndElement(); - writer.WriteStartElement("SalePrice"); - writer.WriteString(inventoryItem.SalePrice.ToString()); - writer.WriteEndElement(); - writer.WriteStartElement("BasePermissions"); - writer.WriteString(inventoryItem.BasePermissions.ToString()); - writer.WriteEndElement(); - writer.WriteStartElement("CurrentPermissions"); - writer.WriteString(inventoryItem.CurrentPermissions.ToString()); - writer.WriteEndElement(); - writer.WriteStartElement("EveryOnePermssions"); - writer.WriteString(inventoryItem.EveryOnePermissions.ToString()); - writer.WriteEndElement(); - writer.WriteStartElement("NextPermissions"); - writer.WriteString(inventoryItem.NextPermissions.ToString()); - writer.WriteEndElement(); - writer.WriteStartElement("Flags"); - writer.WriteString(inventoryItem.Flags.ToString()); - writer.WriteEndElement(); - writer.WriteStartElement("GroupID"); - writer.WriteString(inventoryItem.GroupID.ToString()); - writer.WriteEndElement(); - writer.WriteStartElement("GroupOwned"); - writer.WriteString(inventoryItem.GroupOwned.ToString()); - writer.WriteEndElement(); - writer.WriteStartElement("ParentFolderID"); - writer.WriteString(inventoryItem.Folder.ToString()); - writer.WriteEndElement(); - writer.WriteEndElement(); - - archive.AddFile(filename, sw.ToString()); - - assetUuids[inventoryItem.AssetID] = 1; - } - - protected void saveInvDir(InventoryFolderImpl inventoryFolder, string path) - { - List inventories = inventoryFolder.RequestListOfFolderImpls(); - List items = inventoryFolder.RequestListOfItems(); - string newPath = path + inventoryFolder.Name + InventoryFolderImpl.PATH_DELIMITER; - archive.AddDir(newPath); - foreach (InventoryFolderImpl folder in inventories) - { - saveInvDir(folder, newPath); - } - foreach (InventoryItemBase item in items) - { - saveInvItem(item, newPath); - } - } - - public void execute(string firstName, string lastName, string invPath, string savePath) - { - m_savePath = savePath; - - UserProfileData userProfile = commsManager.UserService.GetUserProfile(firstName, lastName); - if (null == userProfile) - { - m_log.ErrorFormat("[CONSOLE]: Failed to find user {0} {1}", firstName, lastName); - return; - } - - CachedUserInfo userInfo = commsManager.UserProfileCacheService.GetUserDetails(userProfile.ID); - if (null == userInfo) - { - m_log.ErrorFormat("[CONSOLE]: Failed to find user info for {0} {1} {2}", firstName, lastName, userProfile.ID); - return; - } - - InventoryFolderImpl inventoryFolder = null; - InventoryItemBase inventoryItem = null; - - if (userInfo.HasReceivedInventory) - { - // Eliminate double slashes and any leading / on the path. This might be better done within InventoryFolderImpl - // itself (possibly at a small loss in efficiency). - string[] components - = invPath.Split(new string[] { InventoryFolderImpl.PATH_DELIMITER }, StringSplitOptions.RemoveEmptyEntries); - invPath = String.Empty; - foreach (string c in components) - { - invPath += c + InventoryFolderImpl.PATH_DELIMITER; - } - - // Annoyingly Split actually returns the original string if the input string consists only of delimiters - // Therefore if we still start with a / after the split, then we need the root folder - if (invPath.Length == 0) - { - inventoryFolder = userInfo.RootFolder; - } - else - { - invPath = invPath.Remove(invPath.LastIndexOf(InventoryFolderImpl.PATH_DELIMITER)); - inventoryFolder = userInfo.RootFolder.FindFolderByPath(invPath); - } - - // The path may point to an item instead - if (inventoryFolder == null) - { - inventoryItem = userInfo.RootFolder.FindItemByPath(invPath); - } - } - else - { - m_log.ErrorFormat("[CONSOLE]: Have not yet received inventory info for user {0} {1} {2}", firstName, lastName, userProfile.ID); - return; - } - - if (null == inventoryFolder) - { - if (null == inventoryItem) - { - m_log.ErrorFormat("[CONSOLE]: Could not find inventory entry at path {0}", invPath); - return; - } - else - { - m_log.InfoFormat("[CONSOLE]: Found item {0} {1} at {2}", inventoryItem.Name, inventoryItem.ID, - invPath); - //get and export item info - saveInvItem(inventoryItem, invPath); - } - } - else - { - m_log.InfoFormat("[CONSOLE]: Found folder {0} {1} at {2}", inventoryFolder.Name, inventoryFolder.ID, - invPath); - //recurse through all dirs getting dirs and files - saveInvDir(inventoryFolder, ""); - } - - new AssetsRequest(assetUuids.Keys, scene.AssetCache, ReceivedAllAssets).Execute(); - } - } -} diff --git a/OpenSim/Region/Environment/Modules/Avatar/Inventory/Transfer/InventoryTransferModule.cs b/OpenSim/Region/Environment/Modules/Avatar/Inventory/Transfer/InventoryTransferModule.cs deleted file mode 100644 index 62fb3a2..0000000 --- a/OpenSim/Region/Environment/Modules/Avatar/Inventory/Transfer/InventoryTransferModule.cs +++ /dev/null @@ -1,389 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using OpenMetaverse; -using log4net; -using Nini.Config; -using OpenSim.Framework; -using OpenSim.Region.Framework.Interfaces; -using OpenSim.Region.Framework.Scenes; -using OpenSim.Framework.Communications.Cache; - -namespace OpenSim.Region.Environment.Modules.Avatar.Inventory.Transfer -{ - public class InventoryTransferModule : IInventoryTransferModule, IRegionModule - { - private static readonly ILog m_log - = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - /// - private List m_Scenelist = new List(); - private Dictionary m_AgentRegions = - new Dictionary(); - - private IMessageTransferModule m_TransferModule = null; - - #region IRegionModule Members - - public void Initialise(Scene scene, IConfigSource config) - { - if (config.Configs["Messaging"] != null) - { - // Allow disabling this module in config - // - if (config.Configs["Messaging"].GetString( - "InventoryTransferModule", "InventoryTransferModule") != - "InventoryTransferModule") - return; - } - - if (!m_Scenelist.Contains(scene)) - { - if (m_Scenelist.Count == 0) - { - m_TransferModule = scene.RequestModuleInterface(); - if (m_TransferModule == null) - m_log.Error("[INVENTORY TRANSFER] No Message transfer module found, transfers will be local only"); - } - - m_Scenelist.Add(scene); - - scene.RegisterModuleInterface(this); - - scene.EventManager.OnNewClient += OnNewClient; - scene.EventManager.OnClientClosed += ClientLoggedOut; - } - } - - public void PostInitialise() - { - } - - public void Close() - { - } - - public string Name - { - get { return "InventoryModule"; } - } - - public bool IsSharedModule - { - get { return true; } - } - - #endregion - - private void OnNewClient(IClientAPI client) - { - // Inventory giving is conducted via instant message - client.OnInstantMessage += OnInstantMessage; - } - - private Scene FindClientScene(UUID agentId) - { - lock (m_Scenelist) - { - foreach (Scene scene in m_Scenelist) - { - ScenePresence presence = scene.GetScenePresence(agentId); - if (presence != null) - { - if (!presence.IsChildAgent) - return scene; - } - } - } - return null; - } - - private void OnInstantMessage(IClientAPI client, GridInstantMessage im) - { - Scene scene = FindClientScene(client.AgentId); - - if (scene == null) // Something seriously wrong here. - return; - - if (im.dialog == (byte) InstantMessageDialog.InventoryOffered) - { - //m_log.DebugFormat("Asset type {0}", ((AssetType)im.binaryBucket[0])); - - ScenePresence user = scene.GetScenePresence(new UUID(im.toAgentID)); - UUID copyID; - - // First byte is the asset type - AssetType assetType = (AssetType)im.binaryBucket[0]; - - if (AssetType.Folder == assetType) - { - UUID folderID = new UUID(im.binaryBucket, 1); - - m_log.DebugFormat("[AGENT INVENTORY]: Inserting original folder {0} "+ - "into agent {1}'s inventory", - folderID, new UUID(im.toAgentID)); - - InventoryFolderImpl folderCopy - = scene.GiveInventoryFolder(new UUID(im.toAgentID), client.AgentId, folderID, UUID.Zero); - - if (folderCopy == null) - { - client.SendAgentAlertMessage("Can't find folder to give. Nothing given.", false); - return; - } - - // The outgoing binary bucket should contain only the byte which signals an asset folder is - // being copied and the following bytes for the copied folder's UUID - copyID = folderCopy.ID; - byte[] copyIDBytes = copyID.GetBytes(); - im.binaryBucket = new byte[1 + copyIDBytes.Length]; - im.binaryBucket[0] = (byte)AssetType.Folder; - Array.Copy(copyIDBytes, 0, im.binaryBucket, 1, copyIDBytes.Length); - - if (user != null && !user.IsChildAgent) - { - user.ControllingClient.SendBulkUpdateInventory(folderCopy); - } - } - else - { - // First byte of the array is probably the item type - // Next 16 bytes are the UUID - - UUID itemID = new UUID(im.binaryBucket, 1); - - m_log.DebugFormat("[AGENT INVENTORY]: Inserting item {0} "+ - "into agent {1}'s inventory", - itemID, new UUID(im.toAgentID)); - - InventoryItemBase itemCopy = scene.GiveInventoryItem( - new UUID(im.toAgentID), - client.AgentId, itemID); - - if (itemCopy == null) - { - client.SendAgentAlertMessage("Can't find item to give. Nothing given.", false); - return; - } - - copyID = itemCopy.ID; - Array.Copy(copyID.GetBytes(), 0, im.binaryBucket, 1, 16); - - if (user != null && !user.IsChildAgent) - { - user.ControllingClient.SendBulkUpdateInventory(itemCopy); - } - } - - // Send the IM to the recipient. The item is already - // in their inventory, so it will not be lost if - // they are offline. - // - if (user != null && !user.IsChildAgent) - { - // And notify. Transaction ID is the item ID. We get that - // same ID back on the reply so we know what to act on - // - user.ControllingClient.SendInstantMessage( - new UUID(im.fromAgentID), im.message, - new UUID(im.toAgentID), - im.fromAgentName, im.dialog, im.timestamp, - copyID, false, im.binaryBucket); - - return; - } - else - { - if (m_TransferModule != null) - m_TransferModule.SendInstantMessage(im, delegate(bool success) {} ); - } - } - else if (im.dialog == (byte) InstantMessageDialog.InventoryAccepted) - { - ScenePresence user = scene.GetScenePresence(new UUID(im.toAgentID)); - - if (user != null) // Local - { - user.ControllingClient.SendInstantMessage( - new UUID(im.fromAgentID), im.message, - new UUID(im.toAgentID), - im.fromAgentName, im.dialog, im.timestamp, - UUID.Zero, false, im.binaryBucket); - } - else - { - if (m_TransferModule != null) - m_TransferModule.SendInstantMessage(im, delegate(bool success) {} ); - } - } - else if (im.dialog == (byte) InstantMessageDialog.InventoryDeclined) - { - // Here, the recipient is local and we can assume that the - // inventory is loaded. Courtesy of the above bulk update, - // It will have been pushed to the client, too - // - - CachedUserInfo userInfo = - scene.CommsManager.UserProfileCacheService. - GetUserDetails(client.AgentId); - - if (userInfo != null) - { - InventoryFolderImpl trashFolder = - userInfo.FindFolderForType((int)AssetType.TrashFolder); - - UUID inventoryEntityID = new UUID(im.imSessionID); // The inventory item/folder, back from it's trip - - InventoryItemBase item = userInfo.RootFolder.FindItem(inventoryEntityID); - InventoryFolderBase folder = null; - - if (item != null && trashFolder != null) - { - item.Folder = trashFolder.ID; - - userInfo.DeleteItem(inventoryEntityID); - - scene.AddInventoryItem(client, item); - } - else - { - folder = userInfo.RootFolder.FindFolder(inventoryEntityID); - - if (folder != null & trashFolder != null) - { - userInfo.MoveFolder(inventoryEntityID, trashFolder.ID); - } - } - - if ((null == item && null == folder) | null == trashFolder) - { - string reason = String.Empty; - - if (trashFolder == null) - reason += " Trash folder not found."; - if (item == null) - reason += " Item not found."; - if (folder == null) - reason += " Folder not found."; - - client.SendAgentAlertMessage("Unable to delete "+ - "received inventory" + reason, false); - } - } - - ScenePresence user = scene.GetScenePresence(new UUID(im.toAgentID)); - - if (user != null) // Local - { - user.ControllingClient.SendInstantMessage( - new UUID(im.fromAgentID), im.message, - new UUID(im.toAgentID), - im.fromAgentName, im.dialog, im.timestamp, - UUID.Zero, false, im.binaryBucket); - } - else - { - if (m_TransferModule != null) - m_TransferModule.SendInstantMessage(im, delegate(bool success) {} ); - } - } - } - - public void SetRootAgentScene(UUID agentID, Scene scene) - { - m_AgentRegions[agentID] = scene; - } - - public bool NeedSceneCacheClear(UUID agentID, Scene scene) - { - if (!m_AgentRegions.ContainsKey(agentID)) - { - // Since we can get here two ways, we need to scan - // the scenes here. This is somewhat more expensive - // but helps avoid a nasty bug - // - - foreach (Scene s in m_Scenelist) - { - ScenePresence presence; - - if (s.TryGetAvatar(agentID, out presence)) - { - // If the agent is in this scene, then we - // are being called twice in a single - // teleport. This is wasteful of cycles - // but harmless due to this 2nd level check - // - // If the agent is found in another scene - // then the list wasn't current - // - // If the agent is totally unknown, then what - // are we even doing here?? - // - if (s == scene) - { - //m_log.Debug("[INVTRANSFERMOD]: s == scene. Returning true in " + scene.RegionInfo.RegionName); - return true; - } - else - { - //m_log.Debug("[INVTRANSFERMOD]: s != scene. Returning false in " + scene.RegionInfo.RegionName); - return false; - } - } - } - //m_log.Debug("[INVTRANSFERMOD]: agent not in scene. Returning true in " + scene.RegionInfo.RegionName); - return true; - } - - // The agent is left in current Scene, so we must be - // going to another instance - // - if (m_AgentRegions[agentID] == scene) - { - //m_log.Debug("[INVTRANSFERMOD]: m_AgentRegions[agentID] == scene. Returning true in " + scene.RegionInfo.RegionName); - m_AgentRegions.Remove(agentID); - return true; - } - - // Another region has claimed the agent - // - //m_log.Debug("[INVTRANSFERMOD]: last resort. Returning false in " + scene.RegionInfo.RegionName); - return false; - } - - public void ClientLoggedOut(UUID agentID) - { - if (m_AgentRegions.ContainsKey(agentID)) - m_AgentRegions.Remove(agentID); - } - } -} diff --git a/OpenSim/Region/Environment/Modules/Avatar/Lure/LureModule.cs b/OpenSim/Region/Environment/Modules/Avatar/Lure/LureModule.cs deleted file mode 100644 index 79d5409..0000000 --- a/OpenSim/Region/Environment/Modules/Avatar/Lure/LureModule.cs +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using System.Net; -using System.Threading; -using OpenMetaverse; -using log4net; -using Nini.Config; -using Nwc.XmlRpc; -using OpenSim.Framework; -using OpenSim.Framework.Client; -using OpenSim.Region.Framework.Interfaces; -using OpenSim.Region.Framework.Scenes; - -namespace OpenSim.Region.Environment.Modules.Avatar.Lure -{ - public class LureModule : IRegionModule - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private readonly List m_scenes = new List(); - - private IMessageTransferModule m_TransferModule = null; - - public void Initialise(Scene scene, IConfigSource config) - { - if (config.Configs["Messaging"] != null) - { - if (config.Configs["Messaging"].GetString( - "LureModule", "LureModule") != - "LureModule") - return; - } - - lock (m_scenes) - { - if (!m_scenes.Contains(scene)) - { - m_scenes.Add(scene); - scene.EventManager.OnNewClient += OnNewClient; - scene.EventManager.OnIncomingInstantMessage += - OnGridInstantMessage; - } - } - } - - void OnNewClient(IClientAPI client) - { - client.OnInstantMessage += OnInstantMessage; - client.OnStartLure += OnStartLure; - client.OnTeleportLureRequest += OnTeleportLureRequest; - } - - public void PostInitialise() - { - m_TransferModule = - m_scenes[0].RequestModuleInterface(); - - if (m_TransferModule == null) - m_log.Error("[INSTANT MESSAGE]: No message transfer module, "+ - "lures will not work!"); - } - - public void Close() - { - } - - public string Name - { - get { return "LureModule"; } - } - - public bool IsSharedModule - { - get { return true; } - } - - public void OnInstantMessage(IClientAPI client, GridInstantMessage im) - { - } - - public void OnStartLure(byte lureType, string message, UUID targetid, IClientAPI client) - { - if (!(client.Scene is Scene)) - return; - - Scene scene = (Scene)(client.Scene); - ScenePresence presence = scene.GetScenePresence(client.AgentId); - - UUID dest = Util.BuildFakeParcelID( - scene.RegionInfo.RegionHandle, - (uint)presence.AbsolutePosition.X, - (uint)presence.AbsolutePosition.Y, - (uint)presence.AbsolutePosition.Z); - - m_log.DebugFormat("TP invite with message {0}", message); - - GridInstantMessage m = new GridInstantMessage(scene, client.AgentId, - client.FirstName+" "+client.LastName, targetid, - (byte)InstantMessageDialog.RequestTeleport, false, - message, dest, false, presence.AbsolutePosition, - new Byte[0]); - - if (m_TransferModule != null) - { - m_TransferModule.SendInstantMessage(m, - delegate(bool success) { }); - } - } - - public void OnTeleportLureRequest(UUID lureID, uint teleportFlags, IClientAPI client) - { - if (!(client.Scene is Scene)) - return; - - Scene scene = (Scene)(client.Scene); - - ulong handle = 0; - uint x = 128; - uint y = 128; - uint z = 70; - - Util.ParseFakeParcelID(lureID, out handle, out x, out y, out z); - - Vector3 position = new Vector3(); - position.X = (float)x; - position.Y = (float)y; - position.Z = (float)z; - - scene.RequestTeleportLocation(client, handle, position, - Vector3.Zero, teleportFlags); - } - - private void OnGridInstantMessage(GridInstantMessage msg) - { - // Forward remote teleport requests - // - if (msg.dialog != 22) - return; - - if (m_TransferModule != null) - { - m_TransferModule.SendInstantMessage(msg, - delegate(bool success) { }); - } - } - } -} diff --git a/OpenSim/Region/Environment/Modules/Avatar/ObjectCaps/ObjectAdd.cs b/OpenSim/Region/Environment/Modules/Avatar/ObjectCaps/ObjectAdd.cs deleted file mode 100644 index c853582..0000000 --- a/OpenSim/Region/Environment/Modules/Avatar/ObjectCaps/ObjectAdd.cs +++ /dev/null @@ -1,368 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Reflection; -using log4net; -using Nini.Config; -using OpenMetaverse; -using OpenMetaverse.StructuredData; -using OpenSim.Framework; -using OpenSim.Framework.Servers; -using OpenSim.Region.Framework.Interfaces; -using OpenSim.Region.Framework.Scenes; -using Caps = OpenSim.Framework.Communications.Capabilities.Caps; - -namespace OpenSim.Region.Environment.Modules.Avatar.ObjectCaps -{ - public class ObjectAdd : IRegionModule - { - private static readonly ILog m_log = - LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - private Scene m_scene; - #region IRegionModule Members - - public void Initialise(Scene pScene, IConfigSource pSource) - { - m_scene = pScene; - m_scene.EventManager.OnRegisterCaps += RegisterCaps; - } - - public void PostInitialise() - { - - } - - public void RegisterCaps(UUID agentID, Caps caps) - { - UUID capuuid = UUID.Random(); - - m_log.InfoFormat("[OBJECTADD]: {0}", "/CAPS/OA/" + capuuid + "/"); - - caps.RegisterHandler("ObjectAdd", - new RestHTTPHandler("POST", "/CAPS/OA/" + capuuid + "/", - delegate(Hashtable m_dhttpMethod) - { - return ProcessAdd(m_dhttpMethod, agentID, caps); - })); - } - - public Hashtable ProcessAdd(Hashtable request, UUID AgentId, Caps cap) - { - Hashtable responsedata = new Hashtable(); - responsedata["int_response_code"] = 400; //501; //410; //404; - responsedata["content_type"] = "text/plain"; - responsedata["keepalive"] = false; - responsedata["str_response_string"] = "Request wasn't what was expected"; - ScenePresence avatar; - - if (!m_scene.TryGetAvatar(AgentId, out avatar)) - return responsedata; - - - OSD r = OSDParser.DeserializeLLSDXml((string)request["requestbody"]); - //UUID session_id = UUID.Zero; - bool bypass_raycast = false; - uint everyone_mask = 0; - uint group_mask = 0; - uint next_owner_mask = 0; - uint flags = 0; - UUID group_id = UUID.Zero; - int hollow = 0; - int material = 0; - int p_code = 0; - int path_begin = 0; - int path_curve = 0; - int path_end = 0; - int path_radius_offset = 0; - int path_revolutions = 0; - int path_scale_x = 0; - int path_scale_y = 0; - int path_shear_x = 0; - int path_shear_y = 0; - int path_skew = 0; - int path_taper_x = 0; - int path_taper_y = 0; - int path_twist = 0; - int path_twist_begin = 0; - int profile_begin = 0; - int profile_curve = 0; - int profile_end = 0; - Vector3 ray_end = Vector3.Zero; - bool ray_end_is_intersection = false; - Vector3 ray_start = Vector3.Zero; - UUID ray_target_id = UUID.Zero; - Quaternion rotation = Quaternion.Identity; - Vector3 scale = Vector3.Zero; - int state = 0; - - if (r.Type != OSDType.Map) // not a proper req - return responsedata; - - OSDMap rm = (OSDMap)r; - - if (rm.ContainsKey("ObjectData")) //v2 - { - if (rm["ObjectData"].Type != OSDType.Map) - { - responsedata["str_response_string"] = "Has ObjectData key, but data not in expected format"; - return responsedata; - } - - OSDMap ObjMap = (OSDMap) rm["ObjectData"]; - - bypass_raycast = ObjMap["BypassRaycast"].AsBoolean(); - everyone_mask = readuintval(ObjMap["EveryoneMask"]); - flags = readuintval(ObjMap["Flags"]); - group_mask = readuintval(ObjMap["GroupMask"]); - material = ObjMap["Material"].AsInteger(); - next_owner_mask = readuintval(ObjMap["NextOwnerMask"]); - p_code = ObjMap["PCode"].AsInteger(); - - if (ObjMap.ContainsKey("Path")) - { - if (ObjMap["Path"].Type != OSDType.Map) - { - responsedata["str_response_string"] = "Has Path key, but data not in expected format"; - return responsedata; - } - - OSDMap PathMap = (OSDMap)ObjMap["Path"]; - path_begin = PathMap["Begin"].AsInteger(); - path_curve = PathMap["Curve"].AsInteger(); - path_end = PathMap["End"].AsInteger(); - path_radius_offset = PathMap["RadiusOffset"].AsInteger(); - path_revolutions = PathMap["Revolutions"].AsInteger(); - path_scale_x = PathMap["ScaleX"].AsInteger(); - path_scale_y = PathMap["ScaleY"].AsInteger(); - path_shear_x = PathMap["ShearX"].AsInteger(); - path_shear_y = PathMap["ShearY"].AsInteger(); - path_skew = PathMap["Skew"].AsInteger(); - path_taper_x = PathMap["TaperX"].AsInteger(); - path_taper_y = PathMap["TaperY"].AsInteger(); - path_twist = PathMap["Twist"].AsInteger(); - path_twist_begin = PathMap["TwistBegin"].AsInteger(); - - } - - if (ObjMap.ContainsKey("Profile")) - { - if (ObjMap["Profile"].Type != OSDType.Map) - { - responsedata["str_response_string"] = "Has Profile key, but data not in expected format"; - return responsedata; - } - - OSDMap ProfileMap = (OSDMap)ObjMap["Profile"]; - - profile_begin = ProfileMap["Begin"].AsInteger(); - profile_curve = ProfileMap["Curve"].AsInteger(); - profile_end = ProfileMap["End"].AsInteger(); - hollow = ProfileMap["Hollow"].AsInteger(); - } - ray_end_is_intersection = ObjMap["RayEndIsIntersection"].AsBoolean(); - - ray_target_id = ObjMap["RayTargetId"].AsUUID(); - state = ObjMap["State"].AsInteger(); - try - { - ray_end = ((OSDArray) ObjMap["RayEnd"]).AsVector3(); - ray_start = ((OSDArray) ObjMap["RayStart"]).AsVector3(); - scale = ((OSDArray) ObjMap["Scale"]).AsVector3(); - rotation = ((OSDArray)ObjMap["Rotation"]).AsQuaternion(); - } - catch (Exception) - { - responsedata["str_response_string"] = "RayEnd, RayStart, Scale or Rotation wasn't in the expected format"; - return responsedata; - } - - if (rm.ContainsKey("AgentData")) - { - if (rm["AgentData"].Type != OSDType.Map) - { - responsedata["str_response_string"] = "Has AgentData key, but data not in expected format"; - return responsedata; - } - - OSDMap AgentDataMap = (OSDMap) rm["AgentData"]; - - //session_id = AgentDataMap["SessionId"].AsUUID(); - group_id = AgentDataMap["GroupId"].AsUUID(); - } - - } - else - { //v1 - bypass_raycast = rm["bypass_raycast"].AsBoolean(); - - everyone_mask = readuintval(rm["everyone_mask"]); - flags = readuintval(rm["flags"]); - group_id = rm["group_id"].AsUUID(); - group_mask = readuintval(rm["group_mask"]); - hollow = rm["hollow"].AsInteger(); - material = rm["material"].AsInteger(); - next_owner_mask = readuintval(rm["next_owner_mask"]); - hollow = rm["hollow"].AsInteger(); - p_code = rm["p_code"].AsInteger(); - path_begin = rm["path_begin"].AsInteger(); - path_curve = rm["path_curve"].AsInteger(); - path_end = rm["path_end"].AsInteger(); - path_radius_offset = rm["path_radius_offset"].AsInteger(); - path_revolutions = rm["path_revolutions"].AsInteger(); - path_scale_x = rm["path_scale_x"].AsInteger(); - path_scale_y = rm["path_scale_y"].AsInteger(); - path_shear_x = rm["path_shear_x"].AsInteger(); - path_shear_y = rm["path_shear_y"].AsInteger(); - path_skew = rm["path_skew"].AsInteger(); - path_taper_x = rm["path_taper_x"].AsInteger(); - path_taper_y = rm["path_taper_y"].AsInteger(); - path_twist = rm["path_twist"].AsInteger(); - path_twist_begin = rm["path_twist_begin"].AsInteger(); - profile_begin = rm["profile_begin"].AsInteger(); - profile_curve = rm["profile_curve"].AsInteger(); - profile_end = rm["profile_end"].AsInteger(); - - ray_end_is_intersection = rm["ray_end_is_intersection"].AsBoolean(); - - ray_target_id = rm["ray_target_id"].AsUUID(); - - - //session_id = rm["session_id"].AsUUID(); - state = rm["state"].AsInteger(); - try - { - ray_end = ((OSDArray)rm["ray_end"]).AsVector3(); - ray_start = ((OSDArray)rm["ray_start"]).AsVector3(); - rotation = ((OSDArray)rm["rotation"]).AsQuaternion(); - scale = ((OSDArray)rm["scale"]).AsVector3(); - } - catch (Exception) - { - responsedata["str_response_string"] = "RayEnd, RayStart, Scale or Rotation wasn't in the expected format"; - return responsedata; - } - } - - - - Vector3 pos = m_scene.GetNewRezLocation(ray_start, ray_end, ray_target_id, rotation, (bypass_raycast) ? (byte)1 : (byte)0, (ray_end_is_intersection) ? (byte)1 : (byte)0, true, scale, false); - - PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox(); - - pbs.PathBegin = (ushort)path_begin; - pbs.PathCurve = (byte)path_curve; - pbs.PathEnd = (ushort)path_end; - pbs.PathRadiusOffset = (sbyte)path_radius_offset; - pbs.PathRevolutions = (byte)path_revolutions; - pbs.PathScaleX = (byte)path_scale_x; - pbs.PathScaleY = (byte)path_scale_y; - pbs.PathShearX = (byte) path_shear_x; - pbs.PathShearY = (byte)path_shear_y; - pbs.PathSkew = (sbyte)path_skew; - pbs.PathTaperX = (sbyte)path_taper_x; - pbs.PathTaperY = (sbyte)path_taper_y; - pbs.PathTwist = (sbyte)path_twist; - pbs.PathTwistBegin = (sbyte)path_twist_begin; - pbs.HollowShape = (HollowShape) hollow; - pbs.PCode = (byte)p_code; - pbs.ProfileBegin = (ushort) profile_begin; - pbs.ProfileCurve = (byte) profile_curve; - pbs.ProfileEnd = (ushort)profile_end; - pbs.Scale = scale; - pbs.State = (byte)state; - - SceneObjectGroup obj = null; ; - - if (m_scene.Permissions.CanRezObject(1, avatar.UUID, pos)) - { - // rez ON the ground, not IN the ground - pos.Z += 0.25F; - - obj = m_scene.AddNewPrim(avatar.UUID, group_id, pos, rotation, pbs); - } - - - if (obj == null) - return responsedata; - - SceneObjectPart rootpart = obj.RootPart; - rootpart.Shape = pbs; - rootpart.Flags |= (PrimFlags)flags; - rootpart.EveryoneMask = everyone_mask; - rootpart.GroupID = group_id; - rootpart.GroupMask = group_mask; - rootpart.NextOwnerMask = next_owner_mask; - rootpart.Material = (byte)material; - - - - m_scene.PhysicsScene.AddPhysicsActorTaint(rootpart.PhysActor); - - responsedata["int_response_code"] = 200; //501; //410; //404; - responsedata["content_type"] = "text/plain"; - responsedata["keepalive"] = false; - responsedata["str_response_string"] = String.Format("local_id{0}",ConvertUintToBytes(obj.LocalId)); - - return responsedata; - } - - private uint readuintval(OSD obj) - { - byte[] tmp = obj.AsBinary(); - if (BitConverter.IsLittleEndian) - Array.Reverse(tmp); - return Utils.BytesToUInt(tmp); - - } - private string ConvertUintToBytes(uint val) - { - byte[] resultbytes = Utils.UIntToBytes(val); - if (BitConverter.IsLittleEndian) - Array.Reverse(resultbytes); - return String.Format("{0}",Convert.ToBase64String(resultbytes)); - } - - public void Close() - { - - } - - public string Name - { - get { return "ObjectAddModule"; } - } - - public bool IsSharedModule - { - get { return false; } - } - - #endregion - } -} diff --git a/OpenSim/Region/Environment/Modules/Avatar/Profiles/AvatarProfilesModule.cs b/OpenSim/Region/Environment/Modules/Avatar/Profiles/AvatarProfilesModule.cs deleted file mode 100644 index a7e9849..0000000 --- a/OpenSim/Region/Environment/Modules/Avatar/Profiles/AvatarProfilesModule.cs +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Globalization; -using System.Reflection; -using OpenMetaverse; -using log4net; -using Nini.Config; -using OpenSim.Framework; -using OpenSim.Region.Framework.Interfaces; -using OpenSim.Region.Framework.Scenes; - -namespace OpenSim.Region.Environment.Modules.Avatar.Profiles -{ - public class AvatarProfilesModule : IRegionModule - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - private Scene m_scene; - - public AvatarProfilesModule() - { - } - - #region IRegionModule Members - - public void Initialise(Scene scene, IConfigSource config) - { - m_scene = scene; - m_scene.EventManager.OnNewClient += NewClient; - } - - public void PostInitialise() - { - } - - public void Close() - { - } - - public string Name - { - get { return "AvatarProfilesModule"; } - } - - public bool IsSharedModule - { - get { return false; } - } - - #endregion - - public void NewClient(IClientAPI client) - { - client.OnRequestAvatarProperties += RequestAvatarProperty; - client.OnUpdateAvatarProperties += UpdateAvatarProperties; - } - - public void RemoveClient(IClientAPI client) - { - client.OnRequestAvatarProperties -= RequestAvatarProperty; - client.OnUpdateAvatarProperties -= UpdateAvatarProperties; - } - - /// - /// - /// - /// - /// - public void RequestAvatarProperty(IClientAPI remoteClient, UUID avatarID) - { - // FIXME: finish adding fields such as url, masking, etc. - UserProfileData profile = m_scene.CommsManager.UserService.GetUserProfile(avatarID); - if (null != profile) - { - Byte[] charterMember; - if (profile.CustomType == "") - { - charterMember = new Byte[1]; - charterMember[0] = (Byte)((profile.UserFlags & 0xf00) >> 8); - } - else - { - charterMember = Utils.StringToBytes(profile.CustomType); - } - - remoteClient.SendAvatarProperties(profile.ID, profile.AboutText, - Util.ToDateTime(profile.Created).ToString("M/d/yyyy", CultureInfo.InvariantCulture), - charterMember, profile.FirstLifeAboutText, (uint)(profile.UserFlags & 0xff), - profile.FirstLifeImage, profile.Image, String.Empty, profile.Partner); - } - else - { - m_log.Debug("[AvatarProfilesModule]: Got null for profile for " + avatarID.ToString()); - } - } - - 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) - { - Profile.Image = newProfile.Image; - Profile.FirstLifeImage = newProfile.FirstLifeImage; - Profile.AboutText = newProfile.AboutText; - Profile.FirstLifeAboutText = newProfile.FirstLifeAboutText; - } - else - { - return; - } - - if (m_scene.CommsManager.UserService.UpdateUserProfile(Profile)) - { - RequestAvatarProperty(remoteClient, newProfile.ID); - } - } - } -} diff --git a/OpenSim/Region/Environment/Modules/Avatar/Voice/AsterixVoice/AsteriskVoiceModule.cs b/OpenSim/Region/Environment/Modules/Avatar/Voice/AsterixVoice/AsteriskVoiceModule.cs deleted file mode 100644 index 33d7135..0000000 --- a/OpenSim/Region/Environment/Modules/Avatar/Voice/AsterixVoice/AsteriskVoiceModule.cs +++ /dev/null @@ -1,292 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Reflection; -using OpenMetaverse; -using log4net; -using Nini.Config; -using Nwc.XmlRpc; -using OpenSim.Framework; -using OpenSim.Framework.Communications.Cache; -using OpenSim.Framework.Communications.Capabilities; -using OpenSim.Framework.Servers; -using OpenSim.Region.Framework.Interfaces; -using OpenSim.Region.Framework.Scenes; -using Caps=OpenSim.Framework.Communications.Capabilities.Caps; - -namespace OpenSim.Region.Environment.Modules.Avatar.Voice.AsterixVoice -{ - public class AsteriskVoiceModule : IRegionModule - { - private static readonly ILog m_log = - LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - 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_confDomain; - private IConfig m_config; - private Scene m_scene; - private string m_sipDomain; - - #region IRegionModule Members - - public void Initialise(Scene scene, IConfigSource config) - { - m_scene = scene; - m_config = config.Configs["AsteriskVoice"]; - - if (null == m_config) - { - m_log.Info("[ASTERISKVOICE] no config found, plugin disabled"); - return; - } - - if (!m_config.GetBoolean("enabled", false)) - { - m_log.Info("[ASTERISKVOICE] plugin disabled by configuration"); - return; - } - m_log.Info("[ASTERISKVOICE] plugin enabled"); - - try - { - m_sipDomain = m_config.GetString("sip_domain", String.Empty); - m_log.InfoFormat("[ASTERISKVOICE] using SIP domain {0}", m_sipDomain); - - m_confDomain = m_config.GetString("conf_domain", String.Empty); - m_log.InfoFormat("[ASTERISKVOICE] using conf domain {0}", m_confDomain); - - m_asterisk = m_config.GetString("asterisk_frontend", String.Empty); - m_asterisk_password = m_config.GetString("asterisk_password", String.Empty); - m_asterisk_timeout = m_config.GetInt("asterisk_timeout", 3000); - m_asterisk_salt = m_config.GetString("asterisk_salt", "Wuffwuff"); - 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) - { - m_log.ErrorFormat("[ASTERISKVOICE] plugin initialization failed: {0}", e.Message); - m_log.DebugFormat("[ASTERISKVOICE] plugin initialization failed: {0}", e.ToString()); - return; - } - } - - public void PostInitialise() - { - } - - public void Close() - { - } - - public string Name - { - get { return "AsteriskVoiceModule"; } - } - - public bool IsSharedModule - { - get { return false; } - } - - #endregion - - public void OnRegisterCaps(UUID agentID, Caps caps) - { - m_log.DebugFormat("[ASTERISKVOICE] OnRegisterCaps: agentID {0} caps {1}", agentID, caps); - string capsBase = "/CAPS/" + caps.CapsObjectPath; - caps.RegisterHandler("ParcelVoiceInfoRequest", - new RestStreamHandler("POST", capsBase + m_parcelVoiceInfoRequestPath, - delegate(string request, string path, string param, - OSHttpRequest httpRequest, OSHttpResponse httpResponse) - { - return ParcelVoiceInfoRequest(request, path, param, - agentID, caps); - })); - caps.RegisterHandler("ProvisionVoiceAccountRequest", - new RestStreamHandler("POST", capsBase + m_provisionVoiceAccountRequestPath, - delegate(string request, string path, string param, - OSHttpRequest httpRequest, OSHttpResponse httpResponse) - { - return ProvisionVoiceAccountRequest(request, path, param, - agentID, caps); - })); - } - - /// - /// Callback for a client request for ParcelVoiceInfo - /// - /// - /// - /// - /// - /// - /// - public string ParcelVoiceInfoRequest(string request, string path, string param, - UUID 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}", - request, path, param); - - - // setup response to client - Hashtable creds = new Hashtable(); - 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 = - new LLSDParcelVoiceInfoResponse(regionName, land.LocalID, creds); - - string r = LLSDHelpers.SerialiseLLSDReply(parcelVoiceInfo); - - - // update region on asterisk-opensim frontend - Hashtable requestData = new Hashtable(); - requestData["admin_password"] = m_asterisk_password; - requestData["region"] = m_scene.RegionInfo.RegionID.ToString(); - 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; - - if (!responseData.ContainsKey("success")) throw new Exception("region_update call failed"); - - bool success = Convert.ToBoolean((string) responseData["success"]); - if (!success) throw new Exception("region_update failed"); - - - m_log.DebugFormat("[ASTERISKVOICE][PARCELVOICE]: {0}", r); - return r; - } - catch (Exception e) - { - m_log.ErrorFormat("[ASTERISKVOICE][CAPS][PARCELVOICE]: {0}, retry later", e.Message); - m_log.DebugFormat("[ASTERISKVOICE][CAPS][PARCELVOICE]: {0} failed", e.ToString()); - - return "undef"; - } - } - - /// - /// Callback for a client request for Voice Account Details - /// - /// - /// - /// - /// - /// - /// - public string ProvisionVoiceAccountRequest(string request, string path, string param, - UUID agentID, Caps caps) - { - // we need to - // - get user data from UserProfileCacheService - // - generate nonce for user voice account password - // - issue XmlRpc request to asterisk opensim front end: - // + user: base 64 encoded user name (otherwise SL - // client is unhappy) - // + password: nonce - // - the XmlRpc call to asteris-opensim was successful: - // send account details back to client - try - { - m_log.DebugFormat("[ASTERISKVOICE][PROVISIONVOICE]: request: {0}, path: {1}, param: {2}", - request, path, param); - - // get user data & prepare voice account response - string voiceUser = "x" + Convert.ToBase64String(agentID.GetBytes()); - voiceUser = voiceUser.Replace('+', '-').Replace('/', '_'); - - CachedUserInfo userInfo = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(agentID); - if (null == userInfo) throw new Exception("cannot get user details"); - - // we generate a nonce everytime - string voicePassword = "$1$" + Util.Md5Hash(DateTime.UtcNow.ToLongTimeString() + m_asterisk_salt); - LLSDVoiceAccountResponse voiceAccountResponse = - new LLSDVoiceAccountResponse(voiceUser, voicePassword); - string r = LLSDHelpers.SerialiseLLSDReply(voiceAccountResponse); - m_log.DebugFormat("[CAPS][PROVISIONVOICE]: {0}", r); - - - // update user account on asterisk frontend - Hashtable requestData = new Hashtable(); - requestData["admin_password"] = m_asterisk_password; - requestData["username"] = voiceUser; - 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; - - if (!responseData.ContainsKey("success")) throw new Exception("account_update call failed"); - - bool success = Convert.ToBoolean((string) responseData["success"]); - if (!success) throw new Exception("account_update failed"); - - return r; - } - catch (Exception e) - { - m_log.ErrorFormat("[ASTERISKVOICE][CAPS][PROVISIONVOICE]: {0}, retry later", e.Message); - m_log.DebugFormat("[ASTERISKVOICE][CAPS][PROVISIONVOICE]: {0} failed", e.ToString()); - - return "undef"; - } - } - } -} diff --git a/OpenSim/Region/Environment/Modules/Avatar/Voice/SIPVoice/SIPVoiceModule.cs b/OpenSim/Region/Environment/Modules/Avatar/Voice/SIPVoice/SIPVoiceModule.cs deleted file mode 100644 index e4d9b7c..0000000 --- a/OpenSim/Region/Environment/Modules/Avatar/Voice/SIPVoice/SIPVoiceModule.cs +++ /dev/null @@ -1,202 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Reflection; -using OpenMetaverse; -using log4net; -using Nini.Config; -using OpenSim.Framework; -using OpenSim.Framework.Communications.Cache; -using OpenSim.Framework.Communications.Capabilities; -using OpenSim.Framework.Servers; -using OpenSim.Region.Framework.Interfaces; -using OpenSim.Region.Framework.Scenes; -using Caps=OpenSim.Framework.Communications.Capabilities.Caps; - -namespace OpenSim.Region.Environment.Modules.Avatar.Voice.SIPVoice -{ - public class SIPVoiceModule : IRegionModule - { - private static readonly ILog m_log = - LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - 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; - - #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)) - { - m_log.Info("[VOICE] plugin disabled"); - return; - } - m_log.Info("[VOICE] plugin enabled"); - - m_sipDomain = m_config.GetString("sip_domain", String.Empty); - if (String.IsNullOrEmpty(m_sipDomain)) - { - m_log.Error("[VOICE] plugin mis-configured: missing sip_domain configuration"); - m_log.Info("[VOICE] plugin disabled"); - return; - } - m_log.InfoFormat("[VOICE] using SIP domain {0}", m_sipDomain); - - scene.EventManager.OnRegisterCaps += OnRegisterCaps; - } - - public void PostInitialise() - { - } - - public void Close() - { - } - - public string Name - { - get { return "VoiceModule"; } - } - - public bool IsSharedModule - { - get { return false; } - } - - #endregion - - public void OnRegisterCaps(UUID agentID, Caps caps) - { - m_log.DebugFormat("[VOICE] OnRegisterCaps: agentID {0} caps {1}", agentID, caps); - string capsBase = "/CAPS/" + caps.CapsObjectPath; - caps.RegisterHandler("ParcelVoiceInfoRequest", - new RestStreamHandler("POST", capsBase + m_parcelVoiceInfoRequestPath, - delegate(string request, string path, string param, - OSHttpRequest httpRequest, OSHttpResponse httpResponse) - { - return ParcelVoiceInfoRequest(request, path, param, - agentID, caps); - })); - caps.RegisterHandler("ProvisionVoiceAccountRequest", - new RestStreamHandler("POST", capsBase + m_provisionVoiceAccountRequestPath, - delegate(string request, string path, string param, - OSHttpRequest httpRequest, OSHttpResponse httpResponse) - { - return ProvisionVoiceAccountRequest(request, path, param, - agentID, caps); - })); - } - - /// - /// Callback for a client request for ParcelVoiceInfo - /// - /// - /// - /// - /// - /// - /// - public string ParcelVoiceInfoRequest(string request, string path, string param, - UUID agentID, Caps caps) - { - try - { - m_log.DebugFormat("[VOICE][PARCELVOICE]: request: {0}, path: {1}, param: {2}", request, path, param); - - // FIXME: get the creds from region file or from config - 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 = - new LLSDParcelVoiceInfoResponse(regionName, land.LocalID, creds); - - string r = LLSDHelpers.SerialiseLLSDReply(parcelVoiceInfo); - m_log.DebugFormat("[VOICE][PARCELVOICE]: {0}", r); - - return r; - } - catch (Exception e) - { - m_log.ErrorFormat("[CAPS]: {0}, try again later", e.ToString()); - } - - return null; - } - - /// - /// Callback for a client request for Voice Account Details - /// - /// - /// - /// - /// - /// - /// - public string ProvisionVoiceAccountRequest(string request, string path, string param, - UUID agentID, Caps caps) - { - try - { - m_log.DebugFormat("[VOICE][PROVISIONVOICE]: request: {0}, path: {1}, param: {2}", - request, path, param); - - string voiceUser = "x" + Convert.ToBase64String(agentID.GetBytes()); - voiceUser = voiceUser.Replace('+', '-').Replace('/', '_'); - - CachedUserInfo userInfo = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(agentID); - if (null == userInfo) throw new Exception("cannot get user details"); - - LLSDVoiceAccountResponse voiceAccountResponse = - new LLSDVoiceAccountResponse(voiceUser, "$1$" + userInfo.UserProfile.PasswordHash); - string r = LLSDHelpers.SerialiseLLSDReply(voiceAccountResponse); - m_log.DebugFormat("[CAPS][PROVISIONVOICE]: {0}", r); - return r; - } - catch (Exception e) - { - m_log.ErrorFormat("[CAPS][PROVISIONVOICE]: {0}, retry later", e.Message); - } - - return null; - } - } -} -- cgit v1.1