Exemplo n.º 1
0
        private Hashtable HomeLocation(Hashtable mDhttpMethod, UUID agentID)
        {
            OSDMap rm = (OSDMap)OSDParser.DeserializeLLSDXml((string)mDhttpMethod["requestbody"]);
            OSDMap HomeLocation = rm["HomeLocation"] as OSDMap;
            OSDMap pos = HomeLocation["LocationPos"] as OSDMap;
            Vector3 position = new Vector3((float)pos["X"].AsReal(),
                (float)pos["Y"].AsReal(),
                (float)pos["Z"].AsReal());
            OSDMap lookat = HomeLocation["LocationLookAt"] as OSDMap;
            Vector3 lookAt = new Vector3((float)lookat["X"].AsReal(),
                (float)lookat["Y"].AsReal(),
                (float)lookat["Z"].AsReal());
            int locationID = HomeLocation["LocationId"].AsInteger();

            PresenceInfo presence = m_presenceService.GetAgents(new string[] { agentID.ToString() })[0];
            bool r = m_gridUserService.SetHome(agentID.ToString(), presence.RegionID, position, lookAt);

            rm.Add("success", OSD.FromBoolean(r));

            //Send back data
            Hashtable responsedata = new Hashtable();
            responsedata["int_response_code"] = 200; //501; //410; //404;
            responsedata["content_type"] = "text/plain";
            responsedata["keepalive"] = false;
            responsedata["str_response_string"] = OSDParser.SerializeLLSDXmlString(rm);
            return responsedata;
        }
        void pipeline_OnDownloadFinished(UUID id, bool success)
        {
            ImageDownload download;
            if (currentDownloads.TryGetValue(id, out download))
            {
                lock (currentDownloads)
                    currentDownloads.Remove(id);

                if (success)
                {
                    // Set the texture to the downloaded texture data
                    AssetTexture texture = new AssetTexture(id, Pipeline.GetTextureToRender(id).AssetData);
                    download.Texture = texture;

                    Pipeline.RemoveFromPipeline(id);

                    // Store this texture in the local asset store for later
                    server.Assets.StoreAsset(texture);

                    SendTexture(download.Agent, download.Texture, download.DiscardLevel, download.CurrentPacket, download.Priority);
                }
                else
                {
                    Logger.Log("[Periscope] Failed to download texture " + id.ToString(), Helpers.LogLevel.Warning);

                    ImageNotInDatabasePacket notfound = new ImageNotInDatabasePacket();
                    notfound.ImageID.ID = id;
                    server.UDP.SendPacket(download.Agent.Avatar.ID, notfound, PacketCategory.Texture);
                }
            }
            else
            {
                Logger.Log("[Periscope] Pipeline downloaded a texture we're not tracking, " + id.ToString(), Helpers.LogLevel.Warning);
            }
        }
        public UserAccountData[] GetActiveAccounts(UUID scopeID, string query, string excludeTerm)
        {
            string[] words = query.Split(new char[] { ' ' });

            for (int i = 0; i < words.Length; i++)
            {
                if (words[i].Length < 3)
                {
                    if (i != words.Length - 1)
                        Array.Copy(words, i + 1, words, i, words.Length - i - 1);
                    Array.Resize(ref words, words.Length - 1);
                }
            }

            if (words.Length == 0)
                return new UserAccountData[0];

            if (words.Length > 2)
                return new UserAccountData[0];

            SqliteCommand cmd = new SqliteCommand();

            if (words.Length == 1)
            {
                cmd.CommandText = String.Format("select * from {0} where (ScopeID='{1}' or ScopeID='00000000-0000-0000-0000-000000000000') and (FirstName like '{2}%' or LastName like '{2}%') and (FirstName not like '{3}%')",
                    m_Realm, scopeID.ToString(), words[0], excludeTerm);
            }
            else
            {
                cmd.CommandText = String.Format("select * from {0} where (ScopeID='{1}' or ScopeID='00000000-0000-0000-0000-000000000000') and (FirstName like '{2}%' or LastName like '{3}%') and (FirstName not like '{4}%')",
                    m_Realm, scopeID.ToString(), words[0], words[1], excludeTerm);
            }

            return m_DatabaseHandler.DoQuery(cmd);
        }
Exemplo n.º 4
0
        public IAgentInfo GetAgent(UUID PrincipalID)
        {
            IAgentInfo agent;
            if (!m_cache.TryGetValue(PrincipalID, out agent))
                return agent;

            Dictionary<string, object> sendData = new Dictionary<string, object>();

            sendData["PRINCIPALID"] = PrincipalID.ToString();
            sendData["METHOD"] = "getagent";

            string reqString = WebUtils.BuildQueryString(sendData);

            try
            {
                List<string> m_ServerURIs =
                    m_registry.RequestModuleInterface<IConfigurationService>().FindValueOf(PrincipalID.ToString(),
                                                                                           "RemoteServerURI");
                foreach (Dictionary<string, object> replyData in from m_ServerURI in m_ServerURIs select SynchronousRestFormsRequester.MakeRequest("POST",
                                                                                                                                   m_ServerURI + "/auroradata",
                                                                                                                                   reqString) into reply where reply != string.Empty select WebUtils.ParseXmlResponse(reply))
                {
                    if (replyData != null)
                    {
                        if (!replyData.ContainsKey("result"))
                            return null;

                        Dictionary<string, object>.ValueCollection replyvalues = replyData.Values;
                        foreach (object f in replyvalues)
                        {
                            if (f is Dictionary<string, object>)
                            {
                                agent = new IAgentInfo();
                                agent.FromKVP((Dictionary<string, object>) f);
                                m_cache.AddOrUpdate(PrincipalID, agent, new TimeSpan(0, 30, 0));
                            }
                            else
                                MainConsole.Instance.DebugFormat(
                                    "[AuroraRemoteAgentConnector]: GetAgent {0} received invalid response type {1}",
                                    PrincipalID, f.GetType());
                        }
                        // Success
                        return agent;
                    }

                    else
                        MainConsole.Instance.DebugFormat("[AuroraRemoteAgentConnector]: GetAgent {0} received null response",
                                          PrincipalID);
                }
            }
            catch (Exception e)
            {
                MainConsole.Instance.DebugFormat("[AuroraRemoteAgentConnector]: Exception when contacting server: {0}", e);
            }

            return null;
        }
        public override string Execute(string[] args, UUID fromAgentID)
        {
            if (args.Length != 1 && args.Length != 2)
                return "Usage: downloadtexture [texture-uuid] [discardlevel]";

            TextureID = UUID.Zero;
            DownloadHandle.Reset();
            Image = null;
            Asset = null;

            if (UUID.TryParse(args[0], out TextureID))
            {
                int discardLevel = 0;

                if (args.Length > 1)
                {
                    if (!Int32.TryParse(args[1], out discardLevel))
                        return "Usage: downloadtexture [texture-uuid] [discardlevel]";
                }

                Client.Assets.RequestImage(TextureID, ImageType.Normal, 1000000.0f, discardLevel, 0);

                if (DownloadHandle.WaitOne(120 * 1000, false))
                {
                    if (Image != null && Image.Success)
                    {
                        if (Asset != null && Asset.Decode())
                        {
                            try { File.WriteAllBytes(Image.ID.ToString() + ".jp2", Asset.AssetData); }
                            catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, Client, ex); }

                            return String.Format("Saved {0}.jp2 ({1}x{2})", Image.ID, Asset.Image.Width, Asset.Image.Height);
                        }
                        else
                        {
                            return "Failed to decode texture " + TextureID.ToString();
                        }
                    }
                    else if (Image != null && Image.NotFound)
                    {
                        return "Simulator reported texture not found: " + TextureID.ToString();
                    }
                    else
                    {
                        return "Download failed for texture " + TextureID.ToString();
                    }
                }
                else
                {
                    return "Timed out waiting for texture download";
                }
            }
            else
            {
                return "Usage: downloadtexture [texture-uuid]";
            }
        }
Exemplo n.º 6
0
 public void Build()
 {
     cache = new Cache();
     cacheItemUUID = UUID.Random();
     MemoryCacheItem cachedItem = new MemoryCacheItem(cacheItemUUID.ToString(),DateTime.Now + TimeSpan.FromDays(1));
     byte[] foo = new byte[1];
     foo[0] = 255;
     cachedItem.Store(foo);
     cache.Store(cacheItemUUID.ToString(), cachedItem);
 }
Exemplo n.º 7
0
 public void Build()
 {
     cache = new Cache();
     cache = new Cache(CacheMedium.Memory,CacheStrategy.Aggressive,CacheFlags.AllowUpdate);
     cacheItemUUID = UUID.Random();
     MemoryCacheItem cachedItem = new MemoryCacheItem(cacheItemUUID.ToString(),DateTime.Now + TimeSpan.FromDays(1));
     byte[] foo = new byte[1];
     foo[0] = 255;
     cachedItem.Store(foo);
     cache.Store(cacheItemUUID.ToString(), cachedItem);
 }
Exemplo n.º 8
0
        void Groups_OnGroupLeft(UUID groupID, bool success)
        {
            Console.WriteLine(Client.ToString() + (success ? " has left group " : " failed to left group ") + groupID.ToString());

            leftGroup = success;
            GroupsEvent.Set();
        }
        public string Authenticate(UUID principalID, string password, int lifetime)
        {
            Dictionary<string, object> sendData = new Dictionary<string, object>();
            sendData["LIFETIME"] = lifetime.ToString();
            sendData["PRINCIPAL"] = principalID.ToString();
            sendData["PASSWORD"] = password;

            sendData["METHOD"] = "authenticate";

            foreach (string m_ServerURI in m_ServerURIs)
            {
                string reply = SynchronousRestFormsRequester.MakeRequest("POST",
                    m_ServerURI + "/auth/plain",
                    WebUtils.BuildQueryString(sendData));

                Dictionary<string, object> replyData = WebUtils.ParseXmlResponse(
                        reply);

                if (replyData["Result"].ToString() != "Success")
                    return String.Empty;

                return replyData["Token"].ToString();
            }
            return "";
        }
Exemplo n.º 10
0
 public bool IsMuted(UUID PrincipalID, UUID PossibleMuteID)
 {
     OSDMap map = null;
     if (SimianUtils.GetGenericEntry(PrincipalID, "MuteList", PossibleMuteID.ToString(), m_ServerURI, out map))
         return true;
     return false;
 }
Exemplo n.º 11
0
 public void AddTelehub(Telehub telehub, UUID SessionID)
 {
     foreach (string m_ServerURI in m_ServerURIs)
     {
         SimianUtils.AddGeneric(telehub.RegionID, "RegionTelehub", SessionID.ToString(), telehub.ToOSD(), m_ServerURI);
     }
 }
Exemplo n.º 12
0
        public IUserProfileInfo GetUserProfile (UUID PrincipalID)
        {
            try
            {
                List<string> serverURIs = m_registry.RequestModuleInterface<IConfigurationService> ().FindValueOf (PrincipalID.ToString (), "RemoteServerURI");
                foreach (string url in serverURIs)
                {
                    OSDMap map = new OSDMap();
                    map["Method"] = "getprofile";
                    map["PrincipalID"] = PrincipalID;
                    OSDMap response = WebUtils.PostToService (url + "osd", map, true, true);
                    if (response["_Result"].Type == OSDType.Map)
                    {
                        OSDMap responsemap = (OSDMap)response["_Result"];
                        if (responsemap.Count == 0)
                            continue;
                        IUserProfileInfo info = new IUserProfileInfo ();
                        info.FromOSD (responsemap);
                        return info;
                    }
                }
            }
            catch (Exception e)
            {
                m_log.DebugFormat ("[AuroraRemoteProfileConnector]: Exception when contacting server: {0}", e.ToString ());
            }

            return null;
        }
 /// <summary>
 ///   Get a specific region's parcel info
 /// </summary>
 /// <param name = "RegionID"></param>
 /// <param name = "ParcelID"></param>
 /// <returns></returns>
 public LandData GetLandData(UUID RegionID, UUID ParcelID)
 {
     LandData data = GenericUtils.GetGeneric<LandData>(RegionID, "LandData", ParcelID.ToString(), GD);
     //Stored seperately, so rebuild it
     BuildParcelAccessList(data);
     return data;
 }
Exemplo n.º 14
0
        public static bool AddGeneric(UUID ownerID, string type, string key, OSDMap map, string m_ServerURI)
        {
            string value = OSDParser.SerializeJsonString(map);

            NameValueCollection RequestArgs = new NameValueCollection
            {
                { "RequestMethod", "AddGeneric" },
                { "OwnerID", ownerID.ToString() },
                { "Type", type },
                { "Key", key },
                { "Value", value}
            };


            OSDMap Response = CachedPostRequest(RequestArgs, m_ServerURI);
            if (Response["Success"].AsBoolean())
            {
                return true;
            }
            else
            {
                //m_log.WarnFormat("[SIMIAN GROUPS CONNECTOR]: Error {0}, {1}, {2}, {3}", ownerID, type, key, Response["Message"]);
                return false;
            }
        }
Exemplo n.º 15
0
        public IUserProfileInfo GetUserProfile(UUID PrincipalID)
        {
            NameValueCollection requestArgs = new NameValueCollection
            {
                { "RequestMethod", "GetUser" },
                { "UserID", PrincipalID.ToString() }
            };

            OSDMap result = PostUserData(PrincipalID, requestArgs);

            if (result == null)
                return null;

            if (result.ContainsKey("Profile"))
            {
                OSDMap profilemap = (OSDMap)OSDParser.DeserializeJson(result["Profile"].AsString());

                IUserProfileInfo profile = new IUserProfileInfo();
                profile.FromOSD(profilemap);

                return profile;
            }

            return null;
        }
Exemplo n.º 16
0
        public Bitmap LoadBitmap(UUID assetID)
        {
            byte[] bmp = m_scene.AssetService.GetData(assetID.ToString());
            Image img = m_scene.RequestModuleInterface<IJ2KDecoder>().DecodeToImage(bmp);

            return new Bitmap(img);
        }
Exemplo n.º 17
0
        public void UUIDs()
        {
            // Creation
            UUID a = new UUID();
            byte[] bytes = a.GetBytes();
            for (int i = 0; i < 16; i++)
                Assert.IsTrue(bytes[i] == 0x00);

            // Comparison
            a = new UUID(new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A,
                0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0xFF, 0xFF }, 0);
            UUID b = new UUID(new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A,
                0x0B, 0x0C, 0x0D, 0x0E, 0x0F }, 0);

            Assert.IsTrue(a == b, "UUID comparison operator failed, " + a.ToString() + " should equal " + 
                b.ToString());

            // From string
            a = new UUID(new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A,
                0x0B, 0x0C, 0x0D, 0x0E, 0x0F }, 0);
            string zeroonetwo = "00010203-0405-0607-0809-0a0b0c0d0e0f";
            b = new UUID(zeroonetwo);

            Assert.IsTrue(a == b, "UUID hyphenated string constructor failed, should have " + a.ToString() + 
                " but we got " + b.ToString());

            // ToString()            
            Assert.IsTrue(a == b);                        
            Assert.IsTrue(a == (UUID)zeroonetwo);

            // TODO: CRC test
        }
Exemplo n.º 18
0
        public static string Serialize(UUID userID, string firstName, string lastName)
        {
            StringWriter sw = new StringWriter();
            XmlTextWriter xtw = new XmlTextWriter(sw);
            xtw.Formatting = Formatting.Indented;
            xtw.WriteStartDocument();
            
            xtw.WriteStartElement("user_profile");
            xtw.WriteAttributeString("major_version", MAJOR_VERSION.ToString());
            xtw.WriteAttributeString("minor_version", MINOR_VERSION.ToString());
                       
            xtw.WriteElementString("name", firstName + " " + lastName);
            xtw.WriteElementString("id", userID.ToString());
            xtw.WriteElementString("about", "");
  
            // Not sure if we're storing this yet, need to take a look
//            xtw.WriteElementString("Url", profile.Url);
            // or, indeed, interests

            xtw.WriteEndElement();
            
            xtw.Close();
            sw.Close();
            
            return sw.ToString();
        }
        public GridInstantMessage[] GetOfflineMessages(UUID PrincipalID)
        {
            OSDMap map = new OSDMap();

            map["PrincipalID"] = PrincipalID;
            map["Method"] = "getofflinemessages";

            List<GridInstantMessage> Messages = new List<GridInstantMessage>();
            try
            {
                List<string> urls =
                    m_registry.RequestModuleInterface<IConfigurationService>().FindValueOf(PrincipalID.ToString(),
                                                                                           "RemoteServerURI");
                foreach (string url in urls)
                {
                    OSDMap result = WebUtils.PostToService(url + "osd", map, true, false);
                    OSDArray array = (OSDArray) OSDParser.DeserializeJson(result["_RawResult"]);
                    foreach (OSD o in array)
                    {
                        GridInstantMessage message = new GridInstantMessage();
                        message.FromOSD((OSDMap) o);
                        Messages.Add(message);
                    }
                }
                return Messages.ToArray();
            }
            catch (Exception e)
            {
                MainConsole.Instance.DebugFormat("[AuroraRemoteOfflineMessagesConnector]: Exception when contacting server: {0}", e);
            }
            return Messages.ToArray();
        }
Exemplo n.º 20
0
        public bool CreateProxy(string RequestingAgentID, string AgentID, string accessToken, UUID groupID, string url, string name, out string reason)
        {
            reason = string.Empty;

            Dictionary<string, object> sendData = new Dictionary<string,object>();
            sendData["RequestingAgentID"] = RequestingAgentID;
            sendData["AgentID"] = AgentID.ToString();
            sendData["AccessToken"] = accessToken;
            sendData["GroupID"] = groupID.ToString();
            sendData["Location"] = url;
            sendData["Name"] = name;
            Dictionary<string, object> ret = MakeRequest("POSTGROUP", sendData);

            if (ret == null)
                return false;

            if (!ret.ContainsKey("RESULT"))
                return false;

            if (ret["RESULT"].ToString().ToLower() != "true")
            {
                reason = ret["REASON"].ToString();
                return false;
            }

            return true;

        }
Exemplo n.º 21
0
        public IAgentInfo GetAgent(UUID PrincipalID)
        {
            NameValueCollection requestArgs = new NameValueCollection
                                                  {
                                                      {"RequestMethod", "GetUser"},
                                                      {"UserID", PrincipalID.ToString()}
                                                  };

            OSDMap result = PostData(PrincipalID, requestArgs);

            if (result == null)
                return null;

            if (result.ContainsKey("AgentInfo"))
            {
                OSDMap agentmap = (OSDMap) OSDParser.DeserializeJson(result["AgentInfo"].AsString());

                IAgentInfo agent = new IAgentInfo();
                agent.FromOSD(agentmap);

                return agent;
            }

            return null;
        }
Exemplo n.º 22
0
 public void DeleteMute(UUID muteID, UUID PrincipalID)
 {
     foreach (string m_ServerURI in m_ServerURIs)
     {
         SimianUtils.RemoveGenericEntry(PrincipalID, "MuteList", muteID.ToString(), m_ServerURI);
     }
 }
Exemplo n.º 23
0
        public FriendInfo[] GetFriends(UUID PrincipalID)
        {
            Dictionary<string, object> sendData = new Dictionary<string, object>();

            sendData["PRINCIPALID"] = PrincipalID.ToString();
            sendData["METHOD"] = "getfriends";

            string reqString = WebUtils.BuildQueryString(sendData);

            try
            {
                foreach (string m_ServerURI in m_ServerURIs)
                {
                    string reply = SynchronousRestFormsRequester.MakeRequest("POST",
                        m_ServerURI + "/friends",
                        reqString);
                    if (reply != string.Empty)
                    {
                        Dictionary<string, object> replyData = WebUtils.ParseXmlResponse(reply);

                        if (replyData != null)
                        {
                            if (replyData.ContainsKey("result") && (replyData["result"].ToString().ToLower() == "null"))
                            {
                                return new FriendInfo[0];
                            }

                            List<FriendInfo> finfos = new List<FriendInfo>();
                            Dictionary<string, object>.ValueCollection finfosList = replyData.Values;
                            //m_log.DebugFormat("[FRIENDS CONNECTOR]: get neighbours returned {0} elements", rinfosList.Count);
                            foreach (object f in finfosList)
                            {
                                if (f is Dictionary<string, object>)
                                {
                                    FriendInfo finfo = new FriendInfo((Dictionary<string, object>)f);
                                    finfos.Add(finfo);
                                }
                                else
                                    m_log.DebugFormat("[FRIENDS CONNECTOR]: GetFriends {0} received invalid response type {1}",
                                        PrincipalID, f.GetType());
                            }

                            // Success
                            return finfos.ToArray();
                        }

                        else
                            m_log.DebugFormat("[FRIENDS CONNECTOR]: GetFriends {0} received null response",
                                PrincipalID);
                    }
                }
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[FRIENDS CONNECTOR]: Exception when contacting friends server: {0}", e.Message);
            }

            return new FriendInfo[0];

        }
Exemplo n.º 24
0
        public void SuperInit()
        {
            OpenSim.Tests.Common.TestLogging.LogToConsole();

            folder1 = UUID.Random();
            folder2 = UUID.Random();
            folder3 = UUID.Random();
            owner1 = UUID.Random();
            owner2 = UUID.Random();
            owner3 = UUID.Random();
            item1 = UUID.Random();
            item2 = UUID.Random();
            item3 = UUID.Random();
            asset1 = UUID.Random();
            asset2 = UUID.Random();
            asset3 = UUID.Random();

            name1 = "Root Folder for " + owner1.ToString();
            name2 = "First Level folder";
            name3 = "First Level folder 2";
            niname1 = "My Shirt";
            iname1 = "Shirt";
            iname2 = "Text Board";
            iname3 = "No Pants Barrel";

        }
Exemplo n.º 25
0
        public override string Execute(string[] args, UUID fromAgentID)
        {
            if (args.Length < 1)
            {
                return "Usage: goto_landmark [UUID]";
            }

            UUID landmark = new UUID();
            if (!UUID.TryParse(args[0], out landmark))
            {
                return "Invalid LLUID";
            }
            else
            {
                Console.WriteLine("Teleporting to " + landmark.ToString());
            }
            if (Client.Self.Teleport(landmark))
            {
                return "Teleport Succesful";
            }
            else
            {
                return "Teleport Failed";
            }
        }
Exemplo n.º 26
0
 protected override AssetBase GetAsset(UUID uuid)
 {
     if (string.Empty == m_assetServerURL)
         return m_assetCache.Get(uuid.ToString());
     else
         return m_assetMapper.FetchAsset(m_assetServerURL, uuid);
 }
Exemplo n.º 27
0
 public GridInstantMessage[] GetOfflineMessages (UUID agentID)
 {
     List<string> serverURIs = m_registry.RequestModuleInterface<IConfigurationService> ().FindValueOf (agentID.ToString (), "FriendsServerURI");
     if (serverURIs.Count > 0) //Remote user... or should be
         return m_remoteService.GetOfflineMessages (agentID);
     return m_localService.GetOfflineMessages (agentID);
 }
Exemplo n.º 28
0
        public bool LoginAgent(string userID, UUID sessionID, UUID secureSessionID)
        {
            PresenceData prevUser = GetUser(userID);

            if (!m_allowDuplicatePresences && (prevUser != null))
                m_Database.Delete("UserID", userID.ToString());

            PresenceData data = new PresenceData();

            data.UserID = userID;
            data.RegionID = UUID.Zero;
            data.SessionID = sessionID;
            data.Data = new Dictionary<string, string>();
            data.Data["SecureSessionID"] = secureSessionID.ToString();
            
            m_Database.Store(data);

            string prevUserStr = "";
            if (prevUser != null)
                prevUserStr = string.Format(". This user was already logged-in: session {0}, region {1}", prevUser.SessionID, prevUser.RegionID);

            m_log.DebugFormat("[PRESENCE SERVICE]: LoginAgent: session {0}, user {1}, region {2}, secure session {3}{4}",
                data.SessionID, data.UserID, data.RegionID, secureSessionID, prevUserStr);
            
            return true;
        }
Exemplo n.º 29
0
        public virtual List<InventoryFolderBase> GetInventorySkeleton(UUID principalID)
        {
            Dictionary<string,object> ret = MakeRequest("GETINVENTORYSKELETON",
                    new Dictionary<string,object> {
                        { "PRINCIPAL", principalID.ToString() }
                    });

            if (ret == null)
                return null;
            if (ret.Count == 0)
                return null;

            List<InventoryFolderBase> folders = new List<InventoryFolderBase>();

            try
            {
                foreach (Object o in ret.Values)
                    folders.Add(BuildFolder((Dictionary<string, object>)o));
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[XINVENTORY CONNECTOR STUB]: Exception unwrapping folder list: {0}", e.Message);
            }

            return folders;
        }
Exemplo n.º 30
0
 public void RemoveTelehub(UUID regionID, UUID SessionID)
 {
     foreach (string m_ServerURI in m_ServerURIs)
     {
         SimianUtils.RemoveGenericEntry(regionID, "RegionTelehub", SessionID.ToString(), m_ServerURI);
     }
 }
Exemplo n.º 31
0
        public void _StartScript(uint localID, UUID itemID, string Script,
                                 int startParam, bool postOnRez)
        {
            m_log.DebugFormat(
                "[{0}]: ScriptManager StartScript: localID: {1}, itemID: {2}",
                m_scriptEngine.ScriptEngineName, localID, itemID);

            // We will initialize and start the script.
            // It will be up to the script itself to hook up the correct events.
            string CompiledScriptFile = String.Empty;

            SceneObjectPart m_host = World.GetSceneObjectPart(localID);

            if (null == m_host)
            {
                m_log.ErrorFormat(
                    "[{0}]: Could not find scene object part corresponding " +
                    "to localID {1} to start script",
                    m_scriptEngine.ScriptEngineName, localID);

                return;
            }

            UUID assetID = UUID.Zero;
            TaskInventoryItem taskInventoryItem = new TaskInventoryItem();

            if (m_host.TaskInventory.TryGetValue(itemID, out taskInventoryItem))
            {
                assetID = taskInventoryItem.AssetID;
            }

            ScenePresence presence =
                World.GetScenePresence(taskInventoryItem.OwnerID);

            CultureInfo USCulture = new CultureInfo("en-US");

            Thread.CurrentThread.CurrentCulture = USCulture;

            try
            {
                // Compile (We assume LSL)
                CompiledScriptFile =
                    LSLCompiler.PerformScriptCompile(Script,
                                                     assetID.ToString());

                if (presence != null && (!postOnRez))
                {
                    presence.ControllingClient.SendAgentAlertMessage(
                        "Compile successful", false);
                }

                m_log.InfoFormat("[SCRIPT]: Compiled assetID {0}: {1}",
                                 assetID, CompiledScriptFile);

                InstanceData id = new InstanceData();

                IScript CompiledScript;
                CompiledScript =
                    m_scriptEngine.m_AppDomainManager.LoadScript(
                        CompiledScriptFile, out id.AppDomain);
                //Register the sponsor
//                ISponsor scriptSponsor = new ScriptSponsor();
//                ILease lease = (ILease)RemotingServices.GetLifetimeService(CompiledScript as MarshalByRefObject);
//                lease.Register(scriptSponsor);
//                id.ScriptSponsor = scriptSponsor;

                id.LineMap    = LSLCompiler.LineMap();
                id.Script     = CompiledScript;
                id.Source     = Script;
                id.StartParam = startParam;
                id.State      = "default";
                id.Running    = true;
                id.Disabled   = false;

                // Add it to our script memstruct
                m_scriptEngine.m_ScriptManager.SetScript(localID, itemID, id);

                id.Apis = new Dictionary <string, IScriptApi>();

                ApiManager am = new ApiManager();

                foreach (string api in am.GetApis())
                {
                    id.Apis[api] = am.CreateApi(api);
                    id.Apis[api].Initialize(m_scriptEngine, m_host,
                                            localID, itemID);
                }

                foreach (KeyValuePair <string, IScriptApi> kv in id.Apis)
                {
                    CompiledScript.InitApi(kv.Key, kv.Value);
                }

                // Fire the first start-event
                int eventFlags =
                    m_scriptEngine.m_ScriptManager.GetStateEventFlags(
                        localID, itemID);

                m_host.SetScriptEvents(itemID, eventFlags);

                m_scriptEngine.m_EventQueueManager.AddToScriptQueue(
                    localID, itemID, "state_entry", new DetectParams[0],
                    new object[] { });

                if (postOnRez)
                {
                    m_scriptEngine.m_EventQueueManager.AddToScriptQueue(
                        localID, itemID, "on_rez", new DetectParams[0],
                        new object[] { new LSL_Types.LSLInteger(startParam) });
                }

                string[] warnings = LSLCompiler.GetWarnings();

                if (warnings != null && warnings.Length != 0)
                {
                    if (presence != null && (!postOnRez))
                    {
                        presence.ControllingClient.SendAgentAlertMessage(
                            "Script saved with warnings, check debug window!",
                            false);
                    }

                    foreach (string warning in warnings)
                    {
                        try
                        {
                            // DISPLAY WARNING INWORLD
                            string text = "Warning:\n" + warning;
                            if (text.Length > 1100)
                            {
                                text = text.Substring(0, 1099);
                            }

                            World.SimChat(Utils.StringToBytes(text),
                                          ChatTypeEnum.DebugChannel, 2147483647,
                                          m_host.AbsolutePosition, m_host.Name, m_host.UUID,
                                          false);
                        }
                        catch (Exception e2) // LEGIT: User Scripting
                        {
                            m_log.Error("[" +
                                        m_scriptEngine.ScriptEngineName +
                                        "]: Error displaying warning in-world: " +
                                        e2.ToString());
                            m_log.Error("[" +
                                        m_scriptEngine.ScriptEngineName + "]: " +
                                        "Warning:\r\n" +
                                        warning);
                        }
                    }
                }
            }
            catch (Exception e) // LEGIT: User Scripting
            {
                if (presence != null && (!postOnRez))
                {
                    presence.ControllingClient.SendAgentAlertMessage(
                        "Script saved with errors, check debug window!",
                        false);
                }
                try
                {
                    // DISPLAY ERROR INWORLD
                    string text = "Error compiling script:\n" +
                                  e.Message.ToString();
                    if (text.Length > 1100)
                    {
                        text = text.Substring(0, 1099);
                    }

                    World.SimChat(Utils.StringToBytes(text),
                                  ChatTypeEnum.DebugChannel, 2147483647,
                                  m_host.AbsolutePosition, m_host.Name, m_host.UUID,
                                  false);
                }
                catch (Exception e2) // LEGIT: User Scripting
                {
                    m_log.Error("[" +
                                m_scriptEngine.ScriptEngineName +
                                "]: Error displaying error in-world: " +
                                e2.ToString());
                    m_log.Error("[" +
                                m_scriptEngine.ScriptEngineName + "]: " +
                                "Errormessage: Error compiling script:\r\n" +
                                e2.Message.ToString());
                }
            }
        }
        public virtual InventoryItemBase[] GetMultipleItems(UUID principalID, UUID[] itemIDs)
        {
            //m_log.DebugFormat("[XXX]: In GetMultipleItems {0}", String.Join(",", itemIDs));

            InventoryItemBase[] itemArr = new InventoryItemBase[itemIDs.Length];
            // Try to get them from the cache
            List <UUID>       pending = new List <UUID>();
            InventoryItemBase item    = null;
            int i = 0;

            foreach (UUID id in itemIDs)
            {
                if (m_ItemCache.TryGetValue(id, out item))
                {
                    itemArr[i++] = item;
                }
                else
                {
                    pending.Add(id);
                }
            }

            if (pending.Count == 0) // we're done, everything was in the cache
            {
                return(itemArr);
            }

            try
            {
                Dictionary <string, object> resultSet = MakeRequest(
                    new Dictionary <string, object> {
                    { "METHOD", "GETMULTIPLEITEMS" },
                    { "PRINCIPAL", principalID.ToString() },
                    { "ITEMS", String.Join(",", pending.ToArray()) },
                    { "COUNT", pending.Count.ToString() }
                });

                if (!CheckReturn(resultSet))
                {
                    if (i == 0)
                    {
                        return(null);
                    }
                    else
                    {
                        return(itemArr);
                    }
                }

                // carry over index i where we left above
                foreach (KeyValuePair <string, object> kvp in resultSet)
                {
                    InventoryCollection inventory = new InventoryCollection();
                    if (kvp.Key.StartsWith("item_"))
                    {
                        if (kvp.Value is Dictionary <string, object> )
                        {
                            item = BuildItem((Dictionary <string, object>)kvp.Value);
                            m_ItemCache.AddOrUpdate(item.ID, item, CACHE_EXPIRATION_SECONDS);
                            itemArr[i++] = item;
                        }
                        else
                        {
                            itemArr[i++] = null;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                m_log.WarnFormat("[XINVENTORY SERVICES CONNECTOR]: Exception in GetMultipleItems: {0}", e.Message);
            }

            return(itemArr);
        }
Exemplo n.º 33
0
 protected virtual bool DeleteFriendship(UUID agentID, UUID exfriendID)
 {
     FriendsService.Delete(agentID, exfriendID.ToString());
     FriendsService.Delete(exfriendID, agentID.ToString());
     return(true);
 }
Exemplo n.º 34
0
        public void GrantRights(IClientAPI remoteClient, UUID friendID, int rights)
        {
            UUID requester = remoteClient.AgentId;

            m_log.DebugFormat(
                "[FRIENDS MODULE]: User {0} changing rights to {1} for friend {2}",
                requester, rights, friendID);

            FriendInfo[] friends = GetFriendsFromCache(requester);
            if (friends.Length == 0)
            {
                return;
            }

            // Let's find the friend in this user's friend list
            FriendInfo friend = GetFriend(friends, friendID);

            if (friend != null) // Found it
            {
                // Store it on service
                if (!StoreRights(requester, friendID, rights))
                {
                    remoteClient.SendAlertMessage("Unable to grant rights.");
                    return;
                }

                // Store it in the local cache
                int myFlags = friend.MyFlags;
                friend.MyFlags = rights;

                // Always send this back to the original client
                remoteClient.SendChangeUserRights(requester, friendID, rights);

                //
                // Notify the friend
                //

                // Try local
                if (LocalGrantRights(requester, friendID, myFlags, rights))
                {
                    return;
                }

                PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() });
                if (friendSessions != null && friendSessions.Length > 0)
                {
                    PresenceInfo friendSession = friendSessions[0];
                    if (friendSession != null)
                    {
                        GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
                        // TODO: You might want to send the delta to save the lookup
                        // on the other end!!
                        m_FriendsSimConnector.GrantRights(region, requester, friendID, myFlags, rights);
                    }
                }
            }
            else
            {
                m_log.DebugFormat("[FRIENDS MODULE]: friend {0} not found for {1}", friendID, requester);
            }
        }
Exemplo n.º 35
0
        private void OnGridInstantMessage(GridInstantMessage msg)
        {
            // The instant message module will only deliver messages of dialog types:
            // MessageFromAgent, StartTyping, StopTyping, MessageFromObject
            //
            // Any other message type will not be delivered to a client by the
            // Instant Message Module

            UUID regionID = new UUID(msg.RegionID);

            if (m_log.IsDebugEnabled)
            {
                m_log.DebugFormat("[GroupsMessagingModule]: {0} called, IM from region {1}",
                                  System.Reflection.MethodBase.GetCurrentMethod().Name, regionID);

                DebugGridInstantMessage(msg);
            }

            // Incoming message from a group
            if ((msg.fromGroup == true) && (msg.dialog == (byte)InstantMessageDialog.SessionSend))
            {
                // We have to redistribute the message across all members of the group who are here
                // on this sim

                UUID GroupID = new UUID(msg.imSessionID);

                Scene      aScene         = m_sceneList[0];
                GridRegion regionOfOrigin = aScene.GridService.GetRegionByUUID(aScene.RegionInfo.ScopeID, regionID);

                List <GroupMembersData> groupMembers = m_groupData.GetGroupMembers(UUID.Zero.ToString(), GroupID);

                //if (m_log.IsDebugEnabled)
                //    foreach (GroupMembersData m in groupMembers)
                //        m_log.DebugFormat("[GroupsMessagingModule]: member {0}", m.AgentID);

                foreach (Scene s in m_sceneList)
                {
                    s.ForEachScenePresence(sp =>
                    {
                        // If we got this via grid messaging, it's because the caller thinks
                        // that the root agent is here. We should only send the IM to root agents.
                        if (sp.IsChildAgent)
                        {
                            return;
                        }

                        GroupMembersData m = groupMembers.Find(gmd => { return(gmd.AgentID == sp.UUID); });
                        if (m.AgentID == UUID.Zero)
                        {
                            if (m_log.IsDebugEnabled)
                            {
                                m_log.DebugFormat("[GroupsMessagingModule]: skipping agent {0} because he is not a member of the group", sp.UUID);
                            }
                            return;
                        }

                        // Check if the user has an agent in the region where
                        // the IM came from, and if so, skip it, because the IM
                        // was already sent via that agent
                        if (regionOfOrigin != null)
                        {
                            AgentCircuitData aCircuit = s.AuthenticateHandler.GetAgentCircuitData(sp.UUID);
                            if (aCircuit != null)
                            {
                                if (aCircuit.ChildrenCapSeeds.Keys.Contains(regionOfOrigin.RegionHandle))
                                {
                                    if (m_log.IsDebugEnabled)
                                    {
                                        m_log.DebugFormat("[GroupsMessagingModule]: skipping agent {0} because he has an agent in region of origin", sp.UUID);
                                    }
                                    return;
                                }
                                else
                                {
                                    if (m_log.IsDebugEnabled)
                                    {
                                        m_log.DebugFormat("[GroupsMessagingModule]: not skipping agent {0}", sp.UUID);
                                    }
                                }
                            }
                        }

                        UUID AgentID  = sp.UUID;
                        msg.toAgentID = AgentID.Guid;

                        if (!hasAgentDroppedGroupChatSession(AgentID.ToString(), GroupID))
                        {
                            if (!hasAgentBeenInvitedToGroupChatSession(AgentID.ToString(), GroupID))
                            {
                                AddAgentToSession(AgentID, GroupID, msg);
                            }
                            else
                            {
                                if (m_log.IsDebugEnabled)
                                {
                                    m_log.DebugFormat("[GroupsMessagingModule]: Passing to ProcessMessageFromGroupSession to deliver to {0} locally", sp.Name);
                                }

                                ProcessMessageFromGroupSession(msg);
                            }
                        }
                    });
                }
            }
        }
Exemplo n.º 36
0
 public XInventoryItem[] GetActiveGestures(UUID principalID)
 {
     return(m_Items.GetActiveGestures(principalID.ToString()));
 }
        private List <UserAccount> doGetMultiUserAccounts(UUID scopeID, List <string> IDs, out bool suported)
        {
            suported = true;
            Dictionary <string, object> sendData = new Dictionary <string, object>();

            //sendData["SCOPEID"] = scopeID.ToString();
            sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
            sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
            sendData["METHOD"]     = "getmultiaccounts";

            sendData["ScopeID"] = scopeID.ToString();
            sendData["IDS"]     = new List <string>(IDs);

            string reply     = string.Empty;
            string reqString = ServerUtils.BuildQueryString(sendData);
            string uri       = m_ServerURI + "/accounts";

            // m_log.DebugFormat("[ACCOUNTS CONNECTOR]: queryString = {0}", reqString);
            try
            {
                reply = SynchronousRestFormsRequester.MakeRequest("POST",
                                                                  uri,
                                                                  reqString,
                                                                  m_Auth);
                if (reply == null || (reply != null && reply == string.Empty))
                {
                    m_log.DebugFormat("[ACCOUNT CONNECTOR]: GetMultiUserAccounts received null or empty reply");
                    return(null);
                }
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[ACCOUNT CONNECTOR]: Exception when contacting user accounts server at {0}: {1}", uri, e.Message);
            }

            List <UserAccount> accounts = new List <UserAccount>();

            Dictionary <string, object> replyData = ServerUtils.ParseXmlResponse(reply);

            if (replyData != null)
            {
                if (replyData.ContainsKey("result"))
                {
                    if (replyData["result"].ToString() == "null")
                    {
                        return(accounts);
                    }

                    if (replyData["result"].ToString() == "Failure")
                    {
                        suported = false;
                        return(accounts);
                    }
                }

                Dictionary <string, object> .ValueCollection accountList = replyData.Values;
                //m_log.DebugFormat("[ACCOUNTS CONNECTOR]: GetAgents returned {0} elements", pinfosList.Count);
                foreach (object acc in accountList)
                {
                    if (acc is Dictionary <string, object> )
                    {
                        UserAccount pinfo = new UserAccount((Dictionary <string, object>)acc);
                        accounts.Add(pinfo);
                    }
                    else
                    {
                        m_log.DebugFormat("[ACCOUNT CONNECTOR]: GetMultiUserAccounts received invalid response type {0}",
                                          acc.GetType());
                    }
                }
            }
            else
            {
                m_log.DebugFormat("[ACCOUNTS CONNECTOR]: GetMultiUserAccounts received null response");
            }

            return(accounts);
        }
        public static void logChat(int?channel, string contents, Vector3 location, string sender, string receiver, string region, UUID fromUuid, UUID?toUuid)
        {
            long timestamp = getJavaTimestamp();

            // Log to console
            string rcvStr = receiver;

            if (rcvStr == null)
            {
                rcvStr = "NULL";
            }
            m_log.InfoFormat("[{0}]: <{1}> <{2}>: {3}", LOG_NAME, sender, rcvStr, contents);

            // Log to TCP proxy
            sendTCP(TCP_PROXY_SERVER, TCP_PROXY_PORT,
                    SerializeChat(channel, contents, location, sender, receiver, timestamp, region, fromUuid, toUuid) + '\n');

            // Log to database
            MySqlConnection dbcon = new MySqlConnection(DB_CONNECTION_STRING);

            try
            {
                dbcon.Open();

                string cmdStr = null;
                // This is a local chat
                if (receiver == null)
                {
                    cmdStr = "INSERT INTO `opensim`.`chatLogs` (`time`, `from`, `to`, `message`, `channel`, `location`, `region`, `fromUuid`, `toUuid`) VALUES (@time, @from, NULL, @message, @channel, @location, @region, @fromUuid, NULL);";
                }
                // This is a private chat
                else if (channel == null)
                {
                    cmdStr = "INSERT INTO `opensim`.`chatLogs` (`time`, `from`, `to`, `message`, `channel`, `location`, `region`, `fromUuid`, `toUuid`) VALUES (@time, @from, @to, @message, NULL, @location, @region, @fromUuid, @toUuid);";
                }
                else
                {
                    m_log.ErrorFormat("[{0}]: What kind of message IS this???", LOG_NAME);
                    return;
                }


                MySqlCommand cmd = new MySqlCommand(cmdStr, dbcon);
                cmd.Parameters.AddWithValue("@time", timestamp.ToString());
                cmd.Parameters.AddWithValue("@from", sender);
                if (receiver != null)
                {
                    cmd.Parameters.AddWithValue("@to", receiver);
                }
                cmd.Parameters.AddWithValue("@message", contents);
                if (channel != null)
                {
                    cmd.Parameters.AddWithValue("@channel", channel);
                }
                cmd.Parameters.AddWithValue("@location", location.ToString());
                cmd.Parameters.AddWithValue("@region", region);
                cmd.Parameters.AddWithValue("@fromUuid", fromUuid.ToString());
                if (toUuid != null)
                {
                    cmd.Parameters.AddWithValue("@toUuid", toUuid.ToString());
                }

                cmd.ExecuteNonQuery();

                dbcon.Close();
            }
            catch (MySqlException e)
            {
                handleMySQLError(e);
            }
        }
            /// <summary>
            /// Called once new texture data has been received for this updater.
            /// </summary>
            public void DataReceived(byte[] data, Scene scene)
            {
                SceneObjectPart part = scene.GetSceneObjectPart(PrimID);

                if (part == null || data == null || data.Length <= 1)
                {
                    string msg =
                        String.Format("DynamicTextureModule: Error preparing image using URL {0}", Url);
                    scene.SimChat(Utils.StringToBytes(msg), ChatTypeEnum.Say,
                                  0, part.ParentGroup.RootPart.AbsolutePosition, part.Name, part.UUID, false);
                    return;
                }

                byte[]    assetData = null;
                AssetBase oldAsset  = null;

                if (BlendWithOldTexture)
                {
                    Primitive.TextureEntryFace defaultFace = part.Shape.Textures.DefaultTexture;
                    if (defaultFace != null)
                    {
                        oldAsset = scene.AssetService.Get(defaultFace.TextureID.ToString());

                        if (oldAsset != null)
                        {
                            assetData = BlendTextures(data, oldAsset.Data, SetNewFrontAlpha, FrontAlpha);
                        }
                    }
                }

                if (assetData == null)
                {
                    assetData = new byte[data.Length];
                    Array.Copy(data, assetData, data.Length);
                }

                // Create a new asset for user
                AssetBase asset
                    = new AssetBase(
                          UUID.Random(), "DynamicImage" + Util.RandomClass.Next(1, 10000), (sbyte)AssetType.Texture,
                          scene.RegionInfo.RegionID.ToString());

                asset.Data        = assetData;
                asset.Description = String.Format("URL image : {0}", Url);
                asset.Local       = false;
                asset.Temporary   = ((Disp & DISP_TEMP) != 0);
                scene.AssetService.Store(asset);

                IJ2KDecoder cacheLayerDecode = scene.RequestModuleInterface <IJ2KDecoder>();

                if (cacheLayerDecode != null)
                {
                    cacheLayerDecode.Decode(asset.FullID, asset.Data);
                    cacheLayerDecode = null;
                }

                UUID oldID = UUID.Zero;

                lock (part)
                {
                    // mostly keep the values from before
                    Primitive.TextureEntry tmptex = part.Shape.Textures;

                    // remove the old asset from the cache
                    oldID = tmptex.DefaultTexture.TextureID;

                    if (Face == ALL_SIDES)
                    {
                        tmptex.DefaultTexture.TextureID = asset.FullID;
                    }
                    else
                    {
                        try
                        {
                            Primitive.TextureEntryFace texface = tmptex.CreateFace((uint)Face);
                            texface.TextureID         = asset.FullID;
                            tmptex.FaceTextures[Face] = texface;
                        }
                        catch (Exception)
                        {
                            tmptex.DefaultTexture.TextureID = asset.FullID;
                        }
                    }

                    // I'm pretty sure we always want to force this to true
                    // I'm pretty sure noone whats to set fullbright true if it wasn't true before.
                    // tmptex.DefaultTexture.Fullbright = true;

                    part.UpdateTextureEntry(tmptex.GetBytes());
                }

                if (oldID != UUID.Zero && ((Disp & DISP_EXPIRE) != 0))
                {
                    if (oldAsset == null)
                    {
                        oldAsset = scene.AssetService.Get(oldID.ToString());
                    }
                    if (oldAsset != null)
                    {
                        if (oldAsset.Temporary == true)
                        {
                            scene.AssetService.Delete(oldID.ToString());
                        }
                    }
                }
            }
Exemplo n.º 40
0
        public bool LocalFriendshipApproved(UUID userID, string userName, UUID friendID)
        {
            IClientAPI friendClient = LocateClientObject(friendID);

            if (friendClient != null)
            {
                // the prospective friend in this sim as root agent
                GridInstantMessage im = new GridInstantMessage(Scene, userID, userName, friendID,
                                                               (byte)OpenMetaverse.InstantMessageDialog.FriendshipAccepted, userID.ToString(), false, Vector3.Zero);
                friendClient.SendInstantMessage(im);

                ICallingCardModule ccm = friendClient.Scene.RequestModuleInterface <ICallingCardModule>();
                if (ccm != null)
                {
                    ccm.CreateCallingCard(friendID, userID, UUID.Zero);
                }

                // Update the local cache
                RecacheFriends(friendClient);

                // we're done
                return(true);
            }

            return(false);
        }
Exemplo n.º 41
0
 /// <summary>
 /// Deletes a mute for the given agent
 /// </summary>
 /// <param name="muteID"></param>
 /// <param name="AgentID"></param>
 public void DeleteMute(UUID muteID, UUID AgentID)
 {
     GenericUtils.RemoveGeneric(AgentID, "MuteList", muteID.ToString(), GD);
 }
Exemplo n.º 42
0
        public void FindFriend(IClientAPI remoteClient, UUID HunterID, UUID PreyID)
        {
            UUID requester = remoteClient.AgentId;

            if (requester != HunterID) // only allow client agent to be the hunter (?)
            {
                return;
            }

            FriendInfo[] friends = GetFriendsFromCache(requester);
            if (friends.Length == 0)
            {
                return;
            }

            FriendInfo friend = GetFriend(friends, PreyID);

            if (friend == null)
            {
                return;
            }

            if ((friend.TheirFlags & (int)FriendRights.CanSeeOnMap) == 0)
            {
                return;
            }

            Scene hunterScene = (Scene)remoteClient.Scene;

            if (hunterScene == null)
            {
                return;
            }

            // check local
            ScenePresence sp;
            double        px;
            double        py;

            if (hunterScene.TryGetScenePresence(PreyID, out sp))
            {
                if (sp == null)
                {
                    return;
                }
                px = hunterScene.RegionInfo.WorldLocX + sp.AbsolutePosition.X;
                py = hunterScene.RegionInfo.WorldLocY + sp.AbsolutePosition.Y;

                remoteClient.SendFindAgent(HunterID, PreyID, px, py);
                return;
            }

            PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { PreyID.ToString() });

            if (friendSessions == null || friendSessions.Length == 0)
            {
                return;
            }

            PresenceInfo friendSession = friendSessions[0];

            if (friendSession == null)
            {
                return;
            }

            GridRegion region = GridService.GetRegionByUUID(hunterScene.RegionInfo.ScopeID, friendSession.RegionID);

            if (region == null)
            {
                return;
            }

            // we don't have presence location so point to a standard region center for now
            px = region.RegionLocX + 128.0;
            py = region.RegionLocY + 128.0;

            remoteClient.SendFindAgent(HunterID, PreyID, px, py);
        }
Exemplo n.º 43
0
        public byte[] RenderMaterialsPostCap(string path, Stream request,
                                             OSHttpRequest httpRequest, OSHttpResponse httpResponse)
        {
            MainConsole.Instance.Debug("[MaterialsDemoModule]: POST cap handler");

            OSDMap req  = (OSDMap)OSDParser.DeserializeLLSDXml(request);
            OSDMap resp = new OSDMap();

            OSDMap materialsFromViewer = null;

            OSDArray respArr = new OSDArray();

            if (req.ContainsKey("Zipped"))
            {
                OSD osd = null;

                byte[] inBytes = req["Zipped"].AsBinary();

                try
                {
                    osd = ZDecompressBytesToOsd(inBytes);

                    if (osd != null)
                    {
                        if (osd is OSDArray) // assume array of MaterialIDs designating requested material entries
                        {
                            foreach (OSD elem in (OSDArray)osd)
                            {
                                try
                                {
                                    UUID      id            = new UUID(elem.AsBinary(), 0);
                                    AssetBase materialAsset = null;
                                    if (m_knownMaterials.ContainsKey(id))
                                    {
                                        MainConsole.Instance.Info("[MaterialsDemoModule]: request for known material ID: " + id.ToString());
                                        OSDMap matMap = new OSDMap();
                                        matMap["ID"] = elem.AsBinary();

                                        matMap["Material"] = m_knownMaterials[id];
                                        respArr.Add(matMap);
                                    }
                                    else if ((materialAsset = m_scene.AssetService.Get(id.ToString())) != null)
                                    {
                                        MainConsole.Instance.Info("[MaterialsDemoModule]: request for stored material ID: " + id.ToString());
                                        OSDMap matMap = new OSDMap();
                                        matMap["ID"] = elem.AsBinary();

                                        matMap["Material"] = (OSDMap)OSDParser.DeserializeJson(
                                            Encoding.UTF8.GetString(materialAsset.Data));
                                        respArr.Add(matMap);
                                    }
                                    else
                                    {
                                        MainConsole.Instance.Info("[MaterialsDemoModule]: request for UNKNOWN material ID: " + id.ToString());
                                    }
                                }
                                catch (Exception)
                                {
                                    // report something here?
                                    continue;
                                }
                            }
                        }
                        else if (osd is OSDMap) // request to assign a material
                        {
                            materialsFromViewer = osd as OSDMap;

                            if (materialsFromViewer.ContainsKey("FullMaterialsPerFace"))
                            {
                                OSD matsOsd = materialsFromViewer["FullMaterialsPerFace"];
                                if (matsOsd is OSDArray)
                                {
                                    OSDArray matsArr = matsOsd as OSDArray;

                                    try
                                    {
                                        foreach (OSDMap matsMap in matsArr)
                                        {
                                            MainConsole.Instance.Debug("[MaterialsDemoModule]: processing matsMap: " + OSDParser.SerializeJsonString(matsMap));

                                            uint matLocalID = 0;
                                            try { matLocalID = matsMap["ID"].AsUInteger(); }
                                            catch (Exception e) { MainConsole.Instance.Warn("[MaterialsDemoModule]: cannot decode \"ID\" from matsMap: " + e.Message); }
                                            MainConsole.Instance.Debug("[MaterialsDemoModule]: matLocalId: " + matLocalID.ToString());


                                            OSDMap mat = null;
                                            try { mat = matsMap["Material"] as OSDMap; }
                                            catch (Exception e) { MainConsole.Instance.Warn("[MaterialsDemoModule]: cannot decode \"Material\" from matsMap: " + e.Message); }
                                            MainConsole.Instance.Debug("[MaterialsDemoModule]: mat: " + OSDParser.SerializeJsonString(mat));

                                            UUID id = HashOsd(mat);
                                            m_knownMaterials[id] = mat;


                                            var sop = m_scene.GetSceneObjectPart(matLocalID);
                                            if (sop == null)
                                            {
                                                MainConsole.Instance.Debug("[MaterialsDemoModule]: null SOP for localId: " + matLocalID.ToString());
                                            }
                                            else
                                            {
                                                //var te = sop.Shape.Textures;
                                                var te = new Primitive.TextureEntry(sop.Shape.TextureEntry, 0, sop.Shape.TextureEntry.Length);

                                                if (te == null)
                                                {
                                                    MainConsole.Instance.Debug("[MaterialsDemoModule]: null TextureEntry for localId: " + matLocalID.ToString());
                                                }
                                                else
                                                {
                                                    int face = -1;

                                                    if (matsMap.ContainsKey("Face"))
                                                    {
                                                        face = matsMap["Face"].AsInteger();
                                                        if (te.FaceTextures == null) // && face == 0)
                                                        {
                                                            if (te.DefaultTexture == null)
                                                            {
                                                                MainConsole.Instance.Debug("[MaterialsDemoModule]: te.DefaultTexture is null");
                                                            }
                                                            else
                                                            {
//## FixMe ##
// comparison always results in 'False'                                   if (te.DefaultTexture.MaterialID == null)
//                                                                    MainConsole.Instance.Debug("[MaterialsDemoModule]: te.DefaultTexture.MaterialID is null");
//                                                                else
//                                                                {
                                                                te.DefaultTexture.MaterialID = id;
//                                                                }
                                                            }
                                                        }
                                                        else
                                                        {
                                                            if (te.FaceTextures.Length >= face - 1)
                                                            {
                                                                if (te.FaceTextures[face] == null)
                                                                {
                                                                    te.DefaultTexture.MaterialID = id;
                                                                }
                                                                else
                                                                {
                                                                    te.FaceTextures[face].MaterialID = id;
                                                                }
                                                            }
                                                        }
                                                    }
                                                    else
                                                    {
                                                        if (te.DefaultTexture != null)
                                                        {
                                                            te.DefaultTexture.MaterialID = id;
                                                        }
                                                    }

                                                    MainConsole.Instance.Debug("[MaterialsDemoModule]: setting material ID for face " + face.ToString() + " to " + id.ToString());

                                                    //we cant use sop.UpdateTextureEntry(te); because it filters so do it manually

                                                    if (sop.ParentEntity != null)
                                                    {
                                                        sop.Shape.TextureEntry = te.GetBytes();
                                                        sop.TriggerScriptChangedEvent(Changed.TEXTURE);
                                                        sop.ParentEntity.HasGroupChanged = true;

                                                        sop.ScheduleUpdate(PrimUpdateFlags.FullUpdate);

                                                        AssetBase asset = new AssetBase(id, "RenderMaterial",
                                                                                        AssetType.Texture, sop.OwnerID)
                                                        {
                                                            Data = Encoding.UTF8.GetBytes(
                                                                OSDParser.SerializeJsonString(mat))
                                                        };
                                                        m_scene.AssetService.Store(asset);

                                                        StoreMaterialsForPart(sop);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        MainConsole.Instance.Warn("[MaterialsDemoModule]: exception processing received material: " + e.ToString());
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    MainConsole.Instance.Warn("[MaterialsDemoModule]: exception decoding zipped CAP payload: " + e.ToString());
                    //return "";
                }
                MainConsole.Instance.Debug("[MaterialsDemoModule]: knownMaterials.Count: " + m_knownMaterials.Count.ToString());
            }


            resp["Zipped"] = ZCompressOSD(respArr, false);
            string response = OSDParser.SerializeLLSDXmlString(resp);

            //MainConsole.Instance.Debug("[MaterialsDemoModule]: cap request: " + request);
            MainConsole.Instance.Debug("[MaterialsDemoModule]: cap request (zipped portion): " + ZippedOsdBytesToString(req["Zipped"].AsBinary()));
            MainConsole.Instance.Debug("[MaterialsDemoModule]: cap response: " + response);
            return(OSDParser.SerializeLLSDBinary(resp));
        }
Exemplo n.º 44
0
 protected virtual void StoreBackwards(UUID friendID, UUID agentID)
 {
     FriendsService.StoreFriend(friendID.ToString(), agentID.ToString(), 0);
 }
Exemplo n.º 45
0
        public bool LocalFriendshipDenied(UUID userID, string userName, UUID friendID)
        {
            IClientAPI friendClient = LocateClientObject(friendID);

            if (friendClient != null)
            {
                // the prospective friend in this sim as root agent
                GridInstantMessage im = new GridInstantMessage(Scene, userID, userName, friendID,
                                                               (byte)OpenMetaverse.InstantMessageDialog.FriendshipDeclined, userID.ToString(), false, Vector3.Zero);
                friendClient.SendInstantMessage(im);
                // we're done
                return(true);
            }

            return(false);
        }
Exemplo n.º 46
0
 protected virtual void StoreFriendships(UUID agentID, UUID friendID)
 {
     FriendsService.StoreFriend(agentID.ToString(), friendID.ToString(), (int)FriendRights.CanSeeOnline);
     FriendsService.StoreFriend(friendID.ToString(), agentID.ToString(), (int)FriendRights.CanSeeOnline);
 }
Exemplo n.º 47
0
 public string GetCompilerOutput(UUID assetID)
 {
     return(GetCompilerOutput(assetID.ToString()));
 }
Exemplo n.º 48
0
 protected virtual bool StoreRights(UUID agentID, UUID friendID, int rights)
 {
     FriendsService.StoreFriend(agentID.ToString(), friendID.ToString(), rights);
     return(true);
 }
 private void UserCurrencyCreate(UUID agentId)
 {
     m_gd.Insert(_REALM, new object[] { agentId.ToString(), 0, 0, 0, 0, 0 });
 }
Exemplo n.º 50
0
 //
 // TIMER
 //
 static private string MakeTimerKey(uint localID, UUID itemID)
 {
     return(localID.ToString() + itemID.ToString());
 }
        public bool UserCurrencyTransfer(UUID toID, UUID fromID, UUID toObjectID, string toObjectName, UUID fromObjectID,
                                         string fromObjectName, uint amount, string description, TransactionType type, UUID transactionID)
        {
            object remoteValue = DoRemoteByURL("CurrencyServerURI", toID, fromID, toObjectID, toObjectName, fromObjectID,
                                               fromObjectName, amount, description, type, transactionID);

            if (remoteValue != null || m_doRemoteOnly)
            {
                return((bool)remoteValue);
            }

            UserCurrency toCurrency   = GetUserCurrency(toID);
            UserCurrency fromCurrency = fromID == UUID.Zero ? null : GetUserCurrency(fromID);

            if (toCurrency == null)
            {
                return(false);
            }
            if (fromCurrency != null)
            {
                //Check to see whether they have enough money
                if ((int)fromCurrency.Amount - (int)amount < 0)
                {
                    return(false); //Not enough money
                }
                fromCurrency.Amount -= amount;

                UserCurrencyUpdate(fromCurrency, true);
            }
            if (fromID == toID)
            {
                toCurrency = GetUserCurrency(toID);
            }

            //Update the user whose getting paid
            toCurrency.Amount += amount;
            UserCurrencyUpdate(toCurrency, true);

            //Must send out noficiations to the users involved so that they get the updates
            if (m_syncMessagePoster == null)
            {
                m_syncMessagePoster = m_registry.RequestModuleInterface <ISyncMessagePosterService>();
                m_userInfoService   = m_registry.RequestModuleInterface <IAgentInfoService>();
            }
            if (m_syncMessagePoster != null)
            {
                UserInfo    toUserInfo   = m_userInfoService.GetUserInfo(toID.ToString());
                UserInfo    fromUserInfo = fromID == UUID.Zero ? null : m_userInfoService.GetUserInfo(fromID.ToString());
                UserAccount toAccount    = m_registry.RequestModuleInterface <IUserAccountService>()
                                           .GetUserAccount(null, toID);
                UserAccount fromAccount = m_registry.RequestModuleInterface <IUserAccountService>()
                                          .GetUserAccount(null, fromID);
                if (m_config.SaveTransactionLogs)
                {
                    AddTransactionRecord((transactionID == UUID.Zero ? UUID.Random() : transactionID),
                                         description, toID, fromID, amount, type, (toCurrency == null ? 0 : toCurrency.Amount),
                                         (fromCurrency == null ? 0 : fromCurrency.Amount), (toAccount == null ? "System" : toAccount.Name),
                                         (fromAccount == null ? "System" : fromAccount.Name), toObjectName, fromObjectName, (fromUserInfo == null ?
                                                                                                                             UUID.Zero : fromUserInfo.CurrentRegionID));
                }

                if (fromID == toID)
                {
                    if (toUserInfo != null && toUserInfo.IsOnline)
                    {
                        SendUpdateMoneyBalanceToClient(toID, transactionID, toUserInfo.CurrentRegionURI, toCurrency.Amount,
                                                       toAccount == null ? "" : (toAccount.Name + " paid you $" + amount + (description == "" ? "" : ": " + description)));
                    }
                }
                else
                {
                    if (toUserInfo != null && toUserInfo.IsOnline)
                    {
                        SendUpdateMoneyBalanceToClient(toID, transactionID, toUserInfo.CurrentRegionURI, toCurrency.Amount,
                                                       fromAccount == null ? "" : (fromAccount.Name + " paid you $" + amount + (description == "" ? "" : ": " + description)));
                    }
                    if (fromUserInfo != null && fromUserInfo.IsOnline)
                    {
                        SendUpdateMoneyBalanceToClient(fromID, transactionID, fromUserInfo.CurrentRegionURI, fromCurrency.Amount,
                                                       "You paid " + (toAccount == null ? "" : toAccount.Name) + " $" + amount);
                    }
                }
            }
            return(true);
        }
 private void GroupCurrencyCreate(UUID groupID)
 {
     m_gd.Insert(_REALM, new object[] { groupID.ToString(), 0, 0, 0, 1, 0 });
 }
Exemplo n.º 53
0
        private void AddAvatar(UUID avatarID, Avatar avatar, Vector3 coarsePosition)
        {
            if (!this.IsHandleCreated)
            {
                return;
            }

            if (this.InvokeRequired)
            {
                this.BeginInvoke((MethodInvoker) delegate { AddAvatar(avatar.ID, avatar, coarsePosition); });
            }
            else
            {
                TrackedAvatar trackedAvatar = new TrackedAvatar();
                trackedAvatar.CoarseLocation    = coarsePosition;
                trackedAvatar.ID                = avatarID;
                trackedAvatar.ListViewItem      = this.Items.Add(avatarID.ToString(), trackedAvatar.Name, null);
                trackedAvatar.ListViewItem.Name = avatarID.ToString();

                string strDist = avatarID == _Client.Self.AgentID ? "--" : (int)Vector3.Distance(_Client.Self.SimPosition, coarsePosition) + "m";
                trackedAvatar.ListViewItem.SubItems.Add(strDist);

                if (avatar != null)
                {
                    trackedAvatar.Name = avatar.Name;
                    trackedAvatar.ListViewItem.Text = avatar.Name;

                    lock (_TrackedAvatars)
                    {
                        if (_TrackedAvatars.ContainsKey(avatarID))
                        {
                            _TrackedAvatars.Remove(avatarID);
                        }

                        _TrackedAvatars.Add(avatar.LocalID, avatarID, trackedAvatar);
                    }

                    if (OnAvatarAdded != null)
                    {
                        try { OnAvatarAdded(trackedAvatar); }
                        catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, Client, ex); }
                    }
                }
                else
                {
                    lock (_UntrackedAvatars)
                    {
                        _UntrackedAvatars.Add(avatarID, trackedAvatar);

                        trackedAvatar.ListViewItem.ForeColor = Color.FromKnownColor(KnownColor.GrayText);

                        if (avatarID == _Client.Self.AgentID)
                        {
                            trackedAvatar.Name = _Client.Self.Name;
                            trackedAvatar.ListViewItem.Text = _Client.Self.Name;
                        }

                        else if (_Client.Network.Connected)
                        {
                            Client.Avatars.RequestAvatarName(avatarID);
                        }
                    }
                }
            }
        }
 // Method Added By Alicia Raven
 private void AddTransactionRecord(UUID TransID, string Description, UUID ToID, UUID FromID, uint Amount,
                                   TransactionType TransType, uint ToBalance, uint FromBalance, string ToName, string FromName, string toObjectName, string fromObjectName, UUID regionID)
 {
     if (Amount > m_config.MaxAmountBeforeLogging)
     {
         m_gd.Insert("simple_currency_history", new object[] { TransID, (Description == null ? "" : Description),
                                                               FromID.ToString(), FromName, ToID.ToString(), ToName, Amount, (int)TransType, Util.UnixTimeSinceEpoch(), ToBalance, FromBalance,
                                                               toObjectName == null ? "" : toObjectName, fromObjectName == null ? "" : fromObjectName, regionID });
     }
 }
Exemplo n.º 55
0
 /// <summary>
 /// Checks to see if PossibleMuteID is muted by AgentID
 /// </summary>
 /// <param name="AgentID"></param>
 /// <param name="PossibleMuteID"></param>
 /// <returns></returns>
 public bool IsMuted(UUID AgentID, UUID PossibleMuteID)
 {
     return(GenericUtils.GetGeneric <MuteList>(AgentID, "MuteList", PossibleMuteID.ToString(), GD, new MuteList()) != null);
 }
        protected bool TrySendInstantMessage(GridInstantMessage im, object previousLocation, bool firstTime, bool foreigner)
        {
            UUID toAgentID = new UUID(im.toAgentID);

            PresenceInfo upd = null;
            string       url = string.Empty;

            bool lookupAgent = false;

            lock (m_UserLocationMap)
            {
                if (m_UserLocationMap.ContainsKey(toAgentID))
                {
                    object o = m_UserLocationMap[toAgentID];
                    if (o is PresenceInfo)
                    {
                        upd = (PresenceInfo)o;
                    }
                    else if (o is string)
                    {
                        url = (string)o;
                    }

                    // We need to compare the current location with the previous
                    // or the recursive loop will never end because it will never try to lookup the agent again
                    if (!firstTime)
                    {
                        lookupAgent = true;
                        upd         = null;
                    }
                }
                else
                {
                    lookupAgent = true;
                }
            }

            //m_log.DebugFormat("[XXX] Neeed lookup ? {0}", (lookupAgent ? "yes" : "no"));

            // Are we needing to look-up an agent?
            if (lookupAgent)
            {
                // Non-cached user agent lookup.
                PresenceInfo[] presences = m_PresenceService.GetAgents(new string[] { toAgentID.ToString() });
                if (presences != null && presences.Length > 0)
                {
                    foreach (PresenceInfo p in presences)
                    {
                        if (p.RegionID != UUID.Zero)
                        {
                            //m_log.DebugFormat("[XXX]: Found presence in {0}", p.RegionID);
                            upd = p;
                            break;
                        }
                    }
                }

                if (upd == null && !foreigner)
                {
                    // Let's check with the UAS if the user is elsewhere
                    m_log.DebugFormat("[HG IM SERVICE]: User is not present. Checking location with User Agent service");
                    try
                    {
                        url = m_UserAgentService.LocateUser(toAgentID);
                    }
                    catch (Exception e)
                    {
                        m_log.Warn("[HG IM SERVICE]: LocateUser call failed ", e);
                        url = string.Empty;
                    }
                }

                // check if we've tried this before..
                // This is one way to end the recursive loop
                //
                if (!firstTime && ((previousLocation is PresenceInfo && upd != null && upd.RegionID == ((PresenceInfo)previousLocation).RegionID) ||
                                   (previousLocation is string && upd == null && previousLocation.Equals(url))))
                {
                    // m_log.Error("[GRID INSTANT MESSAGE]: Unable to deliver an instant message");
                    m_log.DebugFormat("[HG IM SERVICE]: Fail 2 {0} {1}", previousLocation, url);

                    return(false);
                }
            }

            if (upd != null)
            {
                // ok, the user is around somewhere. Let's send back the reply with "success"
                // even though the IM may still fail. Just don't keep the caller waiting for
                // the entire time we're trying to deliver the IM
                return(SendIMToRegion(upd, im, toAgentID, foreigner));
            }
            else if (url != string.Empty)
            {
                // ok, the user is around somewhere. Let's send back the reply with "success"
                // even though the IM may still fail. Just don't keep the caller waiting for
                // the entire time we're trying to deliver the IM
                return(ForwardIMToGrid(url, im, toAgentID, foreigner));
            }
            else if (firstTime && previousLocation is string && (string)previousLocation != string.Empty)
            {
                return(ForwardIMToGrid((string)previousLocation, im, toAgentID, foreigner));
            }
            else
            {
                m_log.DebugFormat("[HG IM SERVICE]: Unable to locate user {0}", toAgentID);
            }
            return(false);
        }
Exemplo n.º 57
0
        public void AddRegion(Scene scene)
        {
            IConfig cnf;

            m_log.InfoFormat("[{0}]: Adding region {1} to this module", m_name, scene.RegionInfo.RegionName);

            cnf = m_config.Configs["Startup"];
            m_regionConfigDir = cnf.GetString("regionload_regionsdir", Path.Combine(Util.configDir(), "bin/Regions/"));

            cnf = m_config.Configs[scene.RegionInfo.RegionName];

            if (cnf == null)
            {
                m_log.InfoFormat("[{0}]: No region section [{1}] found in {2} configuration file.", m_name, scene.RegionInfo.RegionName, m_regionConfigDir);
                //string moduleConfigFile = Path.Combine(Util.configDir(),m_name + ".ini");
                string moduleConfigFile = Path.Combine(m_regionConfigDir, "Regions.ini");
                try
                {
                    m_log.InfoFormat("[{0}]: Checking {1} for [{2}] section", m_name, moduleConfigFile, scene.RegionInfo.RegionName);
                    m_config = new IniConfigSource(moduleConfigFile);
                    cnf      = m_config.Configs[scene.RegionInfo.RegionName];
                }
                catch (Exception)
                {
                    cnf = null;
                }

                if (cnf == null)
                {
                    m_log.InfoFormat("[{0}]: No region section [{1}] found in configuration {2}.", m_name, scene.RegionInfo.RegionName, moduleConfigFile);

                    cnf = m_config.Configs[scene.RegionInfo.RegionName];
                    if (cnf == null)
                    {
                        m_log.InfoFormat("[{0}]: No region section [{1}] found in main configuration. Module is disabled.", m_name, scene.RegionInfo.RegionName);
                        return;
                    }
                }
            }

            m_enabled = cnf.GetBoolean("BirdsModuleEnabled", false);

            if (m_enabled)
            {
                m_scene             = scene;
                m_startup           = cnf.GetBoolean("BirdsShowOnStartup", false);
                m_chatChannel       = cnf.GetInt("BirdsChatChannel", 118);
                m_birdPrim          = cnf.GetString("BirdsPrim", "birdPrim");
                m_flockSize         = cnf.GetInt("BirdsFlockSize", 20);
                m_maxFlockSize      = cnf.GetInt("BirdsMaxFlockSize", 100);
                m_maxSpeed          = cnf.GetFloat("BirdsMaxSpeed", 1.5f);
                m_maxForce          = cnf.GetFloat("BirdsMaxForce", 0.2f);
                m_neighbourDistance = cnf.GetFloat("BirdsNeighbourDistance", 25f);
                m_desiredSeparation = cnf.GetFloat("BirdsDesiredSeparation", 10f);
                m_tolerance         = cnf.GetFloat("BirdsTolerance", 5f);
                m_borderSize        = cnf.GetFloat("BirdsRegionBorderSize", 5f);
                m_maxHeight         = cnf.GetInt("BirdsMaxHeight", 75);
                m_frameUpdateRate   = cnf.GetInt("BirdsUpdateEveryNFrames", 1);

                string allowedControllers = cnf.GetString("BirdsAllowedControllers", UUID.Zero.ToString());
                if (allowedControllers != UUID.Zero.ToString())
                {
                    string[] ac = allowedControllers.Split(new char[] { ',' });
                    UUID     acUUID;
                    for (int i = 0; i < ac.Length; i++)
                    {
                        string value = ac[i].Trim();
                        if (value == "ESTATE_OWNER")
                        {
                            UUID eoUUID = m_scene.RegionInfo.EstateSettings.EstateOwner;
                            m_allowedControllers.Add(eoUUID);
                            m_log.InfoFormat("[{0}] Added Estate Owner UUID: {1} to list of allowed users", m_name, eoUUID.ToString());
                            continue;
                        }
                        if (value == "ESTATE_MANAGER")
                        {
                            foreach (UUID emUUID in m_scene.RegionInfo.EstateSettings.EstateManagers)
                            {
                                m_allowedControllers.Add(emUUID);
                                m_log.InfoFormat("[{0}] Added Estate Manager UUID: {1} to list of allowed users", m_name, emUUID.ToString());
                            }
                            continue;
                        }
                        if (UUID.TryParse(ac[i].Trim(), out acUUID))
                        {
                            m_allowedControllers.Add(acUUID);
                            m_log.InfoFormat("[{0}] Added UUID: {1} to list of allowed users", m_name, acUUID.ToString());
                        }
                    }
                }
                else
                {
                    m_log.InfoFormat("[{0}] No command security was defined in the config. Any user may possibly configure this module from a script!", m_name);
                }

                m_log.InfoFormat("[{0}] Module is {1} listening for commands on channel {2} with Flock Size {3}", m_name, m_startup ? "enabled and" : "disabled, but still", m_chatChannel, m_flockSize);

                m_console = MainConsole.Instance;
                //register commands with the scene
                RegisterCommands();

                //register handlers
                m_scene.EventManager.OnFrame          += FlockUpdate;
                m_scene.EventManager.OnChatFromClient += SimChatSent; //listen for commands sent from the client
                m_scene.EventManager.OnChatFromWorld  += SimChatSent;
                m_scene.EventManager.OnPrimsLoaded    += PrimsLoaded;

                // init module
                m_model         = new FlockingModel(m_name, m_maxSpeed, m_maxForce, m_neighbourDistance, m_desiredSeparation, m_tolerance, m_borderSize);
                m_view          = new FlockingView(m_name, m_scene);
                m_view.BirdPrim = m_birdPrim;
                m_frame         = 0;
                m_shoutPos      = new Vector3(scene.RegionInfo.RegionSizeX / 2f, scene.RegionInfo.RegionSizeY / 2f, 30f);

                FlockInitialise();
            }
            else
            {
                m_log.InfoFormat("[{0}] Module is disabled in region {1}", m_name, scene.RegionInfo.RegionName);
            }
        }
Exemplo n.º 58
0
        private bool CreateInventoryFile()
        {
//            m_log.DebugFormat(
//                "[PRIM INVENTORY]: Creating inventory file for {0} {1} {2}, serial {3}",
//                m_part.Name, m_part.UUID, m_part.LocalId, m_inventorySerial);

            if (m_inventoryFileName == String.Empty ||
                m_inventoryFileNameSerial < m_inventorySerial)
            {
                // Something changed, we need to create a new file
                m_inventoryFileName       = "inventory_" + UUID.Random().ToString() + ".tmp";
                m_inventoryFileNameSerial = m_inventorySerial;

                InventoryStringBuilder invString = new InventoryStringBuilder(m_part.UUID, UUID.Zero);

                lock (m_items)
                {
                    foreach (TaskInventoryItem item in m_items.Values)
                    {
//                        m_log.DebugFormat(
//                            "[PRIM INVENTORY]: Adding item {0} {1} for serial {2} on prim {3} {4} {5}",
//                            item.Name, item.ItemID, m_inventorySerial, m_part.Name, m_part.UUID, m_part.LocalId);

                        UUID ownerID      = item.OwnerID;
                        uint everyoneMask = 0;
                        uint baseMask     = item.BasePermissions;
                        uint ownerMask    = item.CurrentPermissions;
                        uint groupMask    = item.GroupPermissions;

                        invString.AddItemStart();
                        invString.AddNameValueLine("item_id", item.ItemID.ToString());
                        invString.AddNameValueLine("parent_id", m_part.UUID.ToString());

                        invString.AddPermissionsStart();

                        invString.AddNameValueLine("base_mask", Utils.UIntToHexString(baseMask));
                        invString.AddNameValueLine("owner_mask", Utils.UIntToHexString(ownerMask));
                        invString.AddNameValueLine("group_mask", Utils.UIntToHexString(groupMask));
                        invString.AddNameValueLine("everyone_mask", Utils.UIntToHexString(everyoneMask));
                        invString.AddNameValueLine("next_owner_mask", Utils.UIntToHexString(item.NextPermissions));

                        invString.AddNameValueLine("creator_id", item.CreatorID.ToString());
                        invString.AddNameValueLine("owner_id", ownerID.ToString());

                        invString.AddNameValueLine("last_owner_id", item.LastOwnerID.ToString());

                        invString.AddNameValueLine("group_id", item.GroupID.ToString());
                        invString.AddSectionEnd();

                        invString.AddNameValueLine("asset_id", item.AssetID.ToString());
                        invString.AddNameValueLine("type", Utils.AssetTypeToString((AssetType)item.Type));
                        invString.AddNameValueLine("inv_type", Utils.InventoryTypeToString((InventoryType)item.InvType));
                        invString.AddNameValueLine("flags", Utils.UIntToHexString(item.Flags));

                        invString.AddSaleStart();
                        invString.AddNameValueLine("sale_type", "not");
                        invString.AddNameValueLine("sale_price", "0");
                        invString.AddSectionEnd();

                        invString.AddNameValueLine("name", item.Name + "|");
                        invString.AddNameValueLine("desc", item.Description + "|");

                        invString.AddNameValueLine("creation_date", item.CreationDate.ToString());
                        invString.AddSectionEnd();
                    }
                }

                m_inventoryFileData = Utils.StringToBytes(invString.BuildString);

                return(true);
            }

            // No need to recreate, the existing file is fine
            return(false);
        }
Exemplo n.º 59
0
 protected bool IncrementFolderVersion(UUID folderID)
 {
     return(IncrementFolderVersion(folderID.ToString()));
 }
        public virtual InventoryCollection[] GetMultipleFoldersContent(UUID principalID, UUID[] folderIDs)
        {
            InventoryCollection[] inventoryArr = new InventoryCollection[folderIDs.Length];
            // m_log.DebugFormat("[XXX]: In GetMultipleFoldersContent {0}", String.Join(",", folderIDs));
            try
            {
                Dictionary <string, object> resultSet = MakeRequest(
                    new Dictionary <string, object> {
                    { "METHOD", "GETMULTIPLEFOLDERSCONTENT" },
                    { "PRINCIPAL", principalID.ToString() },
                    { "FOLDERS", String.Join(",", folderIDs) },
                    { "COUNT", folderIDs.Length.ToString() }
                });

                if (!CheckReturn(resultSet))
                {
                    return(null);
                }

                int i = 0;
                foreach (KeyValuePair <string, object> kvp in resultSet)
                {
                    InventoryCollection inventory = new InventoryCollection();
                    if (kvp.Key.StartsWith("F_"))
                    {
                        UUID fid = UUID.Zero;
                        if (UUID.TryParse(kvp.Key.Substring(2), out fid) && fid == folderIDs[i])
                        {
                            inventory.Folders = new List <InventoryFolderBase>();
                            inventory.Items   = new List <InventoryItemBase>();

                            Dictionary <string, object> ret = (Dictionary <string, object>)kvp.Value;

                            if (ret.ContainsKey("FID"))
                            {
                                if (!UUID.TryParse(ret["FID"].ToString(), out inventory.FolderID))
                                {
                                    m_log.WarnFormat("[XINVENTORY SERVICES CONNECTOR]: Could not parse folder id {0}", ret["FID"].ToString());
                                }
                            }
                            else
                            {
                                m_log.WarnFormat("[XINVENTORY SERVICES CONNECTOR]: FID key not present in response");
                            }

                            inventory.Version = -1;
                            if (ret.ContainsKey("VERSION"))
                            {
                                Int32.TryParse(ret["VERSION"].ToString(), out inventory.Version);
                            }
                            if (ret.ContainsKey("OWNER"))
                            {
                                UUID.TryParse(ret["OWNER"].ToString(), out inventory.OwnerID);
                            }

                            //m_log.DebugFormat("[XXX]: Received {0} ({1}) {2} {3}", inventory.FolderID, fid, inventory.Version, inventory.OwnerID);

                            if (ret.TryGetValue("FOLDERS", out object ofolders) && ofolders is Dictionary <string, object> )
                            {
                                var folders = ofolders as Dictionary <string, object>;
                                foreach (Object o in folders.Values) // getting the values directly, we don't care about the keys folder_i
                                {
                                    inventory.Folders.Add(BuildFolder((Dictionary <string, object>)o));
                                }
                            }

                            if (ret.TryGetValue("ITEMS", out object oitems) && oitems is Dictionary <string, object> )
                            {
                                var items = oitems as Dictionary <string, object>;
                                foreach (Object o in items.Values) // getting the values directly, we don't care about the keys item_i
                                {
                                    inventory.Items.Add(BuildItem((Dictionary <string, object>)o));
                                }
                            }
                            inventoryArr[i] = inventory;
                        }
                        else
                        {
                            m_log.WarnFormat("[XINVENTORY SERVICES CONNECTOR]: Folder id does not match. Expected {0} got {1}",
                                             folderIDs[i], fid);
                            m_log.WarnFormat("[XINVENTORY SERVICES CONNECTOR]: {0} {1}", String.Join(",", folderIDs), String.Join(",", resultSet.Keys));
                        }

                        i += 1;
                    }
                }
            }
            catch (Exception e)
            {
                m_log.WarnFormat("[XINVENTORY SERVICES CONNECTOR]: Exception in GetMultipleFoldersContent: {0}", e.Message);
            }

            return(inventoryArr);
        }