Ejemplo n.º 1
0
 public override void FromKVP(Dictionary <string, object> values)
 {
     RoleID   = UUID.Parse(values["RoleID"].ToString());
     MemberID = UUID.Parse(values["MemberID"].ToString());
 }
Ejemplo n.º 2
0
        private string OnChatSessionRequest(UUID Agent, OSDMap rm)
        {
            string method = rm["method"].AsString();

            UUID sessionid = UUID.Parse(rm["session-id"].AsString());

            IScenePresence     SP = findScenePresence(Agent);
            IEventQueueService eq = SP.Scene.RequestModuleInterface <IEventQueueService>();

            if (method == "start conference")
            {
                //Create the session.
                CreateSession(new ChatSession
                {
                    Members   = new List <ChatSessionMember>(),
                    SessionID = sessionid,
                    Name      = SP.Name + " Conference"
                });

                OSDArray parameters = (OSDArray)rm["params"];
                //Add other invited members.
                foreach (OSD param in parameters)
                {
                    AddDefaultPermsMemberToSession(param.AsUUID(), sessionid);
                }

                //Add us to the session!
                AddMemberToGroup(new ChatSessionMember
                {
                    AvatarKey    = Agent,
                    CanVoiceChat = true,
                    IsModerator  = true,
                    MuteText     = false,
                    MuteVoice    = false,
                    HasBeenAdded = true
                }, sessionid);


                //Inform us about our room
                ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock block =
                    new ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock
                {
                    AgentID      = Agent,
                    CanVoiceChat = true,
                    IsModerator  = true,
                    MuteText     = false,
                    MuteVoice    = false,
                    Transition   = "ENTER"
                };
                eq.ChatterBoxSessionAgentListUpdates(sessionid, new[] { block }, Agent, "ENTER",
                                                     findScene(Agent).RegionInfo.RegionHandle);

                ChatterBoxSessionStartReplyMessage cs = new ChatterBoxSessionStartReplyMessage
                {
                    VoiceEnabled   = true,
                    TempSessionID  = UUID.Random(),
                    Type           = 1,
                    Success        = true,
                    SessionID      = sessionid,
                    SessionName    = SP.Name + " Conference",
                    ModeratedVoice = true
                };

                return(cs.Serialize().ToString());
            }
            else if (method == "accept invitation")
            {
                //They would like added to the group conversation
                List <ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock> Us =
                    new List <ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock>();
                List <ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock> NotUsAgents =
                    new List <ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock>();

                ChatSession session = GetSession(sessionid);
                if (session != null)
                {
                    ChatSessionMember thismember = FindMember(sessionid, Agent);
                    //Tell all the other members about the incoming member
                    foreach (ChatSessionMember sessionMember in session.Members)
                    {
                        ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock block =
                            new ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock
                        {
                            AgentID      = sessionMember.AvatarKey,
                            CanVoiceChat = sessionMember.CanVoiceChat,
                            IsModerator  = sessionMember.IsModerator,
                            MuteText     = sessionMember.MuteText,
                            MuteVoice    = sessionMember.MuteVoice,
                            Transition   = "ENTER"
                        };
                        if (sessionMember.AvatarKey == thismember.AvatarKey)
                        {
                            Us.Add(block);
                        }
                        else
                        {
                            if (sessionMember.HasBeenAdded)
                            {
                                // Don't add not joined yet agents. They don't want to be here.
                                NotUsAgents.Add(block);
                            }
                        }
                    }
                    thismember.HasBeenAdded = true;
                    foreach (ChatSessionMember member in session.Members)
                    {
                        eq.ChatterBoxSessionAgentListUpdates(session.SessionID,
                                                             member.AvatarKey == thismember.AvatarKey
                                                                 ? NotUsAgents.ToArray()
                                                                 : Us.ToArray(),
                                                             member.AvatarKey, "ENTER",
                                                             findScene(Agent).RegionInfo.RegionHandle);
                    }
                    return("Accepted");
                }
                else
                {
                    return(""); //not this type of session
                }
            }
            else if (method == "mute update")
            {
                //Check if the user is a moderator
                Hashtable responsedata = new Hashtable();
                if (!CheckModeratorPermission(Agent, sessionid))
                {
                    return("");
                }

                OSDMap parameters  = (OSDMap)rm["params"];
                UUID   AgentID     = parameters["agent_id"].AsUUID();
                OSDMap muteInfoMap = (OSDMap)parameters["mute_info"];

                ChatSessionMember thismember = FindMember(sessionid, AgentID);
                if (muteInfoMap.ContainsKey("text"))
                {
                    thismember.MuteText = muteInfoMap["text"].AsBoolean();
                }
                if (muteInfoMap.ContainsKey("voice"))
                {
                    thismember.MuteVoice = muteInfoMap["voice"].AsBoolean();
                }

                ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock block =
                    new ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock
                {
                    AgentID      = thismember.AvatarKey,
                    CanVoiceChat = thismember.CanVoiceChat,
                    IsModerator  = thismember.IsModerator,
                    MuteText     = thismember.MuteText,
                    MuteVoice    = thismember.MuteVoice,
                    Transition   = "ENTER"
                };

                // Send an update to the affected user
                eq.ChatterBoxSessionAgentListUpdates(sessionid, new[] { block }, AgentID, "",
                                                     findScene(Agent).RegionInfo.RegionHandle);

                return("Accepted");
            }
            else
            {
                MainConsole.Instance.Warn("ChatSessionRequest : " + method);
                return("");
            }
        }
Ejemplo n.º 3
0
        public EstateSettings(Dictionary <string, object> map)
        {
            foreach (KeyValuePair <string, object> kvp in map)
            {
                PropertyInfo p = this.GetType().GetProperty(kvp.Key, BindingFlags.Public | BindingFlags.Instance);
                if (p == null)
                {
                    continue;
                }

                // EstateBans is a complex type, let's treat it as special
                if (p.Name == "EstateBans")
                {
                    continue;
                }

                if (p.PropertyType.IsArray)
                {
                    string[] elements = ((string)map[p.Name]).Split(new char[] { ',' });
                    UUID[]   uuids    = new UUID[elements.Length];
                    int      i        = 0;
                    foreach (string e in elements)
                    {
                        uuids[i++] = new UUID(e);
                    }
                    p.SetValue(this, uuids, null);
                }
                else
                {
                    object value = p.GetValue(this, null);
                    if (value is String)
                    {
                        p.SetValue(this, map[p.Name], null);
                    }
                    else if (value is UInt32)
                    {
                        p.SetValue(this, UInt32.Parse((string)map[p.Name]), null);
                    }
                    else if (value is Boolean)
                    {
                        p.SetValue(this, Boolean.Parse((string)map[p.Name]), null);
                    }
                    else if (value is UUID)
                    {
                        p.SetValue(this, UUID.Parse((string)map[p.Name]), null);
                    }
                }
            }

            // EstateBans are special
            if (map.ContainsKey("EstateBans"))
            {
                if (map["EstateBans"] is string)
                {
                    // JSON encoded bans map
                    Dictionary <string, EstateBan> bdata = new Dictionary <string, EstateBan>();
                    try
                    {
                        // bypass libovm, we dont need even more useless high level maps
                        // this should only be called once.. but no problem, i hope
                        // (other uses may need more..)
                        LitJson.JsonMapper.RegisterImporter <string, UUID>((input) => new UUID(input));
                        bdata = LitJson.JsonMapper.ToObject <Dictionary <string, EstateBan> >((string)map["EstateBans"]);
                    }
                    //                   catch(Exception e)
                    catch
                    {
                        return;
                    }
                    EstateBan[] jbans = new EstateBan[bdata.Count];
                    bdata.Values.CopyTo(jbans, 0);

                    PropertyInfo jbansProperty = this.GetType().GetProperty("EstateBans", BindingFlags.Public | BindingFlags.Instance);
                    jbansProperty.SetValue(this, jbans, null);
                }
                else
                {
                    var         banData = ((Dictionary <string, object>)map["EstateBans"]).Values;
                    EstateBan[] bans    = new EstateBan[banData.Count];

                    int b = 0;
                    foreach (Dictionary <string, object> ban in banData)
                    {
                        bans[b++] = new EstateBan(ban);
                    }
                    PropertyInfo bansProperty = this.GetType().GetProperty("EstateBans", BindingFlags.Public | BindingFlags.Instance);
                    bansProperty.SetValue(this, bans, null);
                }
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Parse a UUID tail section into a full UUID.
        /// </summary>
        /// <remarks>
        /// The fragment will come at the end of the UUID.  The rest will be 0s
        /// </remarks>
        /// <returns></returns>
        /// <param name='frag'>
        /// A UUID fragment that will be parsed into a full UUID.  Therefore, it can only contain
        /// cahracters which are valid in a UUID, except for "-" which is currently only allowed if a full UUID is
        /// given as the 'fragment'.
        /// </param>
        public static UUID ParseTail(string stem)
        {
            string rawUuid = stem.PadLeft(32, '0');

            return(UUID.Parse(rawUuid));
        }
Ejemplo n.º 5
0
 protected object OnGenericEvent(string FunctionName, object parameters)
 {
     if (FunctionName == "NewUserConnection")
     {
         ICapsService service = m_scene.RequestModuleInterface <ICapsService>();
         if (service != null)
         {
             object[]         obj     = (object[])parameters;
             OSDMap           param   = (OSDMap)obj[0];
             AgentCircuitData circuit = (AgentCircuitData)obj[1];
             if (circuit.reallyischild)//If Aurora is sending this, it'll show that it really is a child agent
             {
                 return(null);
             }
             AvatarAppearance appearance = m_scene.AvatarService.GetAppearance(circuit.AgentID);
             if (appearance != null)
             {
                 circuit.Appearance = appearance;
             }
             else
             {
                 m_scene.AvatarService.SetAppearance(circuit.AgentID, circuit.Appearance);
             }
             //circuit.Appearance.Texture = new Primitive.TextureEntry(UUID.Zero);
             circuit.child = false;//ONLY USE ROOT AGENTS, SINCE OPENSIM SENDS CHILD == TRUE ALL THE TIME
             if (circuit.ServiceURLs != null && circuit.ServiceURLs.ContainsKey("IncomingCAPSHandler"))
             {
                 AddCapsHandler(circuit);
             }
             else
             {
                 IClientCapsService clientService = service.GetOrCreateClientCapsService(circuit.AgentID);
                 clientService.RemoveCAPS(m_scene.RegionInfo.RegionHandle);
                 service.CreateCAPS(circuit.AgentID, CapsUtil.GetCapsSeedPath(circuit.CapsPath),
                                    m_scene.RegionInfo.RegionHandle, true, circuit, MainServer.Instance.Port); //We ONLY use root agents because of OpenSim's inability to send the correct data
                 MainConsole.Instance.Output("setting up on " + clientService.HostUri + CapsUtil.GetCapsSeedPath(circuit.CapsPath));
                 IClientCapsService clientCaps = service.GetClientCapsService(circuit.AgentID);
                 if (clientCaps != null)
                 {
                     IRegionClientCapsService regionCaps = clientCaps.GetCapsService(m_scene.RegionInfo.RegionHandle);
                     if (regionCaps != null)
                     {
                         regionCaps.AddCAPS((OSDMap)param["CapsUrls"]);
                     }
                 }
             }
         }
     }
     else if (FunctionName == "UserStatusChange")
     {
         object[] info = (object[])parameters;
         if (!bool.Parse(info[1].ToString())) //Logging out
         {
             ICapsService service = m_scene.RequestModuleInterface <ICapsService>();
             if (service != null)
             {
                 service.RemoveCAPS(UUID.Parse(info[0].ToString()));
             }
         }
     }
     return(null);
 }
        public void TestLoadMultiRegionOar()
        {
            TestHelpers.InMethod();

            // Create an ArchiveScenesGroup with the regions in the OAR. This is needed to generate the control file.

            int WIDTH  = 2;
            int HEIGHT = 2;

            for (uint y = 0; y < HEIGHT; y++)
            {
                for (uint x = 0; x < WIDTH; x++)
                {
                    Scene scene;
                    if (x == 0 && y == 0)
                    {
                        scene = m_scene;   // this scene was already created in SetUp()
                    }
                    else
                    {
                        scene = m_sceneHelpers.SetupScene(string.Format("Unit test region {0}", (y * WIDTH) + x + 1), UUID.Random(), 1000 + x, 1000 + y);
                        SceneHelpers.SetupSceneModules(scene, new ArchiverModule(), m_serialiserModule, new TerrainModule());
                    }
                }
            }

            ArchiveScenesGroup scenesGroup = new ArchiveScenesGroup();

            m_sceneHelpers.SceneManager.ForEachScene(delegate(Scene scene)
            {
                scenesGroup.AddScene(scene);
            });
            scenesGroup.CalcSceneLocations();

            // Generate the OAR file

            MemoryStream     archiveWriteStream = new MemoryStream();
            TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream);

            ArchiveWriteRequest writeRequest = new ArchiveWriteRequest(m_scene, (Stream)null, Guid.Empty);

            writeRequest.MultiRegionFormat = true;
            tar.WriteFile(
                ArchiveConstants.CONTROL_FILE_PATH, writeRequest.CreateControlFile(scenesGroup));

            SceneObjectPart part1 = CreateSceneObjectPart1();

            part1.SitTargetOrientation = new Quaternion(0.2f, 0.3f, 0.4f, 0.5f);
            part1.SitTargetPosition    = new Vector3(1, 2, 3);

            SceneObjectGroup object1 = new SceneObjectGroup(part1);

            // Let's put some inventory items into our object
            string   soundItemName         = "sound-item1";
            UUID     soundItemUuid         = UUID.Parse("00000000-0000-0000-0000-000000000002");
            Type     type                  = GetType();
            Assembly assembly              = type.Assembly;
            string   soundDataResourceName = null;

            string[] names = assembly.GetManifestResourceNames();
            foreach (string name in names)
            {
                if (name.EndsWith(".Resources.test-sound.wav"))
                {
                    soundDataResourceName = name;
                }
            }
            Assert.That(soundDataResourceName, Is.Not.Null);

            byte[] soundData;
            UUID   soundUuid;

            CreateSoundAsset(tar, assembly, soundDataResourceName, out soundData, out soundUuid);

            TaskInventoryItem item1
                = new TaskInventoryItem {
                AssetID = soundUuid, ItemID = soundItemUuid, Name = soundItemName
                };

            part1.Inventory.AddInventoryItem(item1, true);
            m_scene.AddNewSceneObject(object1, false);

            string object1FileName = string.Format(
                "{0}_{1:000}-{2:000}-{3:000}__{4}.xml",
                part1.Name,
                Math.Round(part1.GroupPosition.X), Math.Round(part1.GroupPosition.Y), Math.Round(part1.GroupPosition.Z),
                part1.UUID);
            string path = "regions/1_1_Unit_test_region/" + ArchiveConstants.OBJECTS_PATH + object1FileName;

            tar.WriteFile(path, SceneObjectSerializer.ToXml2Format(object1));

            tar.Close();

            // Delete the current objects, to test that they're loaded from the OAR and didn't
            // just remain in the scene.
            m_sceneHelpers.SceneManager.ForEachScene(delegate(Scene scene)
            {
                scene.DeleteAllSceneObjects();
            });

            // Create a "hole", to test that that the corresponding region isn't loaded from the OAR
            m_sceneHelpers.SceneManager.CloseScene(SceneManager.Instance.Scenes[1]);

            // Check thay the OAR file contains the expected data

            MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray());

            lock (this)
            {
                m_scene.EventManager.OnOarFileLoaded += LoadCompleted;
                m_archiverModule.DearchiveRegion(archiveReadStream);
            }

            Assert.That(m_lastErrorMessage, Is.Null);

            Assert.AreEqual(3, m_sceneHelpers.SceneManager.Scenes.Count);

            TestLoadedRegion(part1, soundItemName, soundData);
        }
Ejemplo n.º 7
0
        public Dictionary <string, object> Fill(WebInterface webInterface, string filename, OSHttpRequest httpRequest,
                                                OSHttpResponse httpResponse, Dictionary <string, object> requestParameters,
                                                ITranslator translator, out string response)
        {
            response = null;
            var vars = new Dictionary <string, object>();

            string error  = "";
            UUID   userID = httpRequest.Query.ContainsKey("userid")
                            ? UUID.Parse(httpRequest.Query["userid"].ToString())
                            : UUID.Parse(requestParameters["userid"].ToString());

            IUserAccountService userService = webInterface.Registry.RequestModuleInterface <IUserAccountService>();
            var         agentService        = Framework.Utilities.DataManager.RequestPlugin <IAgentConnector>();
            UserAccount account             = userService.GetUserAccount(null, userID);
            IAgentInfo  agent = agentService.GetAgent(userID);

            if (agent == null)
            {
                error = "No agent information is available";
            }

            // Set user type
            if (requestParameters.ContainsKey("Submit") &&
                requestParameters["Submit"].ToString() == "SubmitSetUserType")
            {
                string UserType  = requestParameters ["UserType"].ToString();
                int    UserFlags = webInterface.UserTypeToUserFlags(UserType);

                // set the user account type
                account.UserFlags = UserFlags;
                userService.StoreUserAccount(account);

                if (agent != null)
                {
                    agent.OtherAgentInformation ["UserFlags"] = UserFlags;
                    agentService.UpdateAgent(agent);
                    response = "User has been updated.";
                }
                else
                {
                    response = "Agent information is not available! Has the user logged in yet?";
                }

                IProfileConnector profileData =
                    Framework.Utilities.DataManager.RequestPlugin <IProfileConnector>();
                if (profileData != null)
                {
                    IUserProfileInfo profile = profileData.GetUserProfile(userID);
                    if (profile == null)
                    {
                        profileData.CreateNewProfile(userID);
                        profile = profileData.GetUserProfile(userID);
                    }

                    profile.MembershipGroup = webInterface.UserFlagToType(UserFlags, webInterface.EnglishTranslator);     // membership is english
                    profileData.UpdateUserProfile(profile);
                }

                response = "User has been updated.";
                return(null);
            }

            // Password change
            if (requestParameters.ContainsKey("Submit") &&
                requestParameters["Submit"].ToString() == "SubmitPasswordChange")
            {
                string password     = requestParameters["password"].ToString();
                string passwordconf = requestParameters["passwordconf"].ToString();

                if (password != passwordconf)
                {
                    response = "Passwords do not match";
                }
                else
                {
                    IAuthenticationService authService =
                        webInterface.Registry.RequestModuleInterface <IAuthenticationService>();
                    if (authService != null)
                    {
                        response = authService.SetPassword(userID, "UserAccount", password)
                                       ? "Successfully set password"
                                       : "Failed to set your password, try again later";
                    }
                    else
                    {
                        response = "No authentication service was available to change your password";
                    }
                }
                return(null);
            }

            // Email change
            if (requestParameters.ContainsKey("Submit") &&
                requestParameters["Submit"].ToString() == "SubmitEmailChange")
            {
                string email = requestParameters["email"].ToString();

                if (userService != null)
                {
                    account.Email = email;
                    userService.StoreUserAccount(account);
                    response = "Successfully updated email";
                }
                else
                {
                    response = "No authentication service was available to change your password";
                }
                return(null);
            }

            // Delete user
            if (requestParameters.ContainsKey("Submit") &&
                requestParameters["Submit"].ToString() == "SubmitDeleteUser")
            {
                string username = requestParameters["username"].ToString();
                response = "Deleted user successfully";
                if (username == account.Name)
                {
                    userService.DeleteUser(account.PrincipalID, account.Name, "", false, false);
                }
                else
                {
                    response = "The user name did not match";
                }
                return(null);
            }

            // Temp Ban user
            if (requestParameters.ContainsKey("Submit") &&
                requestParameters["Submit"].ToString() == "SubmitTempBanUser")
            {
                int timeDays    = int.Parse(requestParameters["TimeDays"].ToString());
                int timeHours   = int.Parse(requestParameters["TimeHours"].ToString());
                int timeMinutes = int.Parse(requestParameters["TimeMinutes"].ToString());

                if (agent != null)
                {
                    agent.Flags |= IAgentFlags.TempBan;
                    DateTime until = DateTime.Now.AddDays(timeDays).AddHours(timeHours).AddMinutes(timeMinutes);
                    agent.OtherAgentInformation ["TemperaryBanInfo"] = until;
                    agentService.UpdateAgent(agent);
                    response = "User has been banned.";
                }
                else
                {
                    response = "Agent information is not available! Has the user logged in yet?";
                }

                return(null);
            }

            // Ban user
            if (requestParameters.ContainsKey("Submit") &&
                requestParameters["Submit"].ToString() == "SubmitBanUser")
            {
                if (agent != null)
                {
                    agent.Flags |= IAgentFlags.PermBan;
                    agentService.UpdateAgent(agent);
                    response = "User has been banned.";
                }
                else
                {
                    response = "Agent information is not available! Has the user logged in yet?";
                }

                return(null);
            }

            //UnBan user
            if (requestParameters.ContainsKey("Submit") &&
                requestParameters["Submit"].ToString() == "SubmitUnbanUser")
            {
                if (agent != null)
                {
                    agent.Flags &= ~IAgentFlags.TempBan;
                    agent.Flags &= ~IAgentFlags.PermBan;
                    agent.OtherAgentInformation.Remove("TemperaryBanInfo");
                    agentService.UpdateAgent(agent);
                    response = "User has been unbanned.";
                }
                else
                {
                    response = "Agent information is not available! Has the user logged in yet?";
                }

                return(null);
            }

            // Login as user
            if (requestParameters.ContainsKey("Submit") &&
                requestParameters["Submit"].ToString() == "SubmitLoginAsUser")
            {
                Authenticator.ChangeAuthentication(httpRequest, account);
                webInterface.Redirect(httpResponse, "/");
                return(vars);
            }

            // Kick user
            if (requestParameters.ContainsKey("Submit") &&
                requestParameters["Submit"].ToString() == "SubmitKickUser")
            {
                string message = requestParameters["KickMessage"].ToString();
                IGridWideMessageModule messageModule =
                    webInterface.Registry.RequestModuleInterface <IGridWideMessageModule>();
                if (messageModule != null)
                {
                    messageModule.KickUser(account.PrincipalID, message);
                }
                response = "User has been kicked.";
                return(null);
            }

            // Message user
            if (requestParameters.ContainsKey("Submit") &&
                requestParameters["Submit"].ToString() == "SubmitMessageUser")
            {
                string message = requestParameters["Message"].ToString();
                IGridWideMessageModule messageModule =
                    webInterface.Registry.RequestModuleInterface <IGridWideMessageModule>();
                if (messageModule != null)
                {
                    messageModule.MessageUser(account.PrincipalID, message);
                }
                response = "User has been sent the message.";
                return(null);
            }

            // page variables
            string bannedUntil = "";
            bool   userBanned  = agent == null
                                  ? false
                                  : ((agent.Flags & IAgentFlags.PermBan) == IAgentFlags.PermBan ||
                                     (agent.Flags & IAgentFlags.TempBan) == IAgentFlags.TempBan);
            bool TempUserBanned = false;

            if (userBanned)
            {
                if ((agent.Flags & IAgentFlags.TempBan) == IAgentFlags.TempBan &&
                    agent.OtherAgentInformation["TemperaryBanInfo"].AsDate() < DateTime.Now.ToUniversalTime())
                {
                    userBanned   = false;
                    agent.Flags &= ~IAgentFlags.TempBan;
                    agent.Flags &= ~IAgentFlags.PermBan;
                    agent.OtherAgentInformation.Remove("TemperaryBanInfo");
                    agentService.UpdateAgent(agent);
                }
                else
                {
                    DateTime bannedTime = agent.OtherAgentInformation["TemperaryBanInfo"].AsDate();
                    TempUserBanned = bannedTime != Util.UnixEpoch;
                    bannedUntil    = string.Format("{0} {1}", bannedTime.ToShortDateString(), bannedTime.ToLongTimeString());
                }
            }
            bool userOnline = false;
            IAgentInfoService agentInfoService = webInterface.Registry.RequestModuleInterface <IAgentInfoService>();

            if (agentInfoService != null)
            {
                UserInfo info = agentInfoService.GetUserInfo(account.PrincipalID.ToString());
                userOnline = info != null ? info.IsOnline : false;
            }
            vars.Add("UserOnline", userOnline);
            vars.Add("NotUserBanned", !userBanned);
            vars.Add("UserBanned", userBanned);
            vars.Add("TempUserBanned", TempUserBanned);
            vars.Add("BannedUntil", bannedUntil);
            vars.Add("EmailValue", account.Email);
            vars.Add("UserID", account.PrincipalID);
            vars.Add("UserName", account.Name);
            vars.Add("ErrorMessage", error);
            vars.Add("ChangeUserInformationText", translator.GetTranslatedString("ChangeUserInformationText"));
            vars.Add("ChangePasswordText", translator.GetTranslatedString("ChangePasswordText"));
            vars.Add("NewPasswordText", translator.GetTranslatedString("NewPasswordText"));
            vars.Add("NewPasswordConfirmationText", translator.GetTranslatedString("NewPasswordConfirmationText"));
            vars.Add("ChangeEmailText", translator.GetTranslatedString("ChangeEmailText"));
            vars.Add("NewEmailText", translator.GetTranslatedString("NewEmailText"));
            vars.Add("UserNameText", translator.GetTranslatedString("UserNameText"));
            vars.Add("PasswordText", translator.GetTranslatedString("PasswordText"));
            vars.Add("DeleteUserText", translator.GetTranslatedString("DeleteUserText"));
            vars.Add("DeleteText", translator.GetTranslatedString("DeleteText"));
            vars.Add("DeleteUserInfoText", translator.GetTranslatedString("DeleteUserInfoText"));
            vars.Add("Submit", translator.GetTranslatedString("Submit"));
            vars.Add("Login", translator.GetTranslatedString("Login"));
            vars.Add("TypeUserNameToConfirm", translator.GetTranslatedString("TypeUserNameToConfirm"));

            vars.Add("AdminUserTypeInfoText", translator.GetTranslatedString("AdminUserTypeInfoText"));
            vars.Add("AdminSetUserTypeText", translator.GetTranslatedString("UserTypeText"));

            vars.Add("AdminLoginInAsUserText", translator.GetTranslatedString("AdminLoginInAsUserText"));
            vars.Add("AdminLoginInAsUserInfoText", translator.GetTranslatedString("AdminLoginInAsUserInfoText"));
            vars.Add("AdminDeleteUserText", translator.GetTranslatedString("AdminDeleteUserText"));
            vars.Add("AdminDeleteUserInfoText", translator.GetTranslatedString("AdminDeleteUserInfoText"));
            vars.Add("AdminUnbanUserText", translator.GetTranslatedString("AdminUnbanUserText"));
            vars.Add("AdminTempBanUserText", translator.GetTranslatedString("AdminTempBanUserText"));
            vars.Add("AdminTempBanUserInfoText", translator.GetTranslatedString("AdminTempBanUserInfoText"));
            vars.Add("AdminBanUserText", translator.GetTranslatedString("AdminBanUserText"));
            vars.Add("AdminBanUserInfoText", translator.GetTranslatedString("AdminBanUserInfoText"));
            vars.Add("BanText", translator.GetTranslatedString("BanText"));
            vars.Add("UnbanText", translator.GetTranslatedString("UnbanText"));
            vars.Add("TimeUntilUnbannedText", translator.GetTranslatedString("TimeUntilUnbannedText"));
            vars.Add("EdittingText", translator.GetTranslatedString("EdittingText"));
            vars.Add("BannedUntilText", translator.GetTranslatedString("BannedUntilText"));

            vars.Add("KickAUserInfoText", translator.GetTranslatedString("KickAUserInfoText"));
            vars.Add("KickAUserText", translator.GetTranslatedString("KickAUserText"));
            vars.Add("KickMessageText", translator.GetTranslatedString("KickMessageText"));
            vars.Add("KickUserText", translator.GetTranslatedString("KickUserText"));

            vars.Add("MessageAUserText", translator.GetTranslatedString("MessageAUserText"));
            vars.Add("MessageAUserInfoText", translator.GetTranslatedString("MessageAUserInfoText"));
            vars.Add("MessageUserText", translator.GetTranslatedString("MessageUserText"));

            List <Dictionary <string, object> > daysArgs = new List <Dictionary <string, object> >();

            for (int i = 0; i <= 100; i++)
            {
                daysArgs.Add(new Dictionary <string, object> {
                    { "Value", i }
                });
            }

            List <Dictionary <string, object> > hoursArgs = new List <Dictionary <string, object> >();

            for (int i = 0; i <= 23; i++)
            {
                hoursArgs.Add(new Dictionary <string, object> {
                    { "Value", i }
                });
            }

            List <Dictionary <string, object> > minutesArgs = new List <Dictionary <string, object> >();

            for (int i = 0; i <= 59; i++)
            {
                minutesArgs.Add(new Dictionary <string, object> {
                    { "Value", i }
                });
            }

            vars.Add("Days", daysArgs);
            vars.Add("Hours", hoursArgs);
            vars.Add("Minutes", minutesArgs);
            vars.Add("DaysText", translator.GetTranslatedString("DaysText"));
            vars.Add("HoursText", translator.GetTranslatedString("HoursText"));
            vars.Add("MinutesText", translator.GetTranslatedString("MinutesText"));

            vars.Add("UserType", webInterface.UserTypeArgs(translator));

            return(vars);
        }
Ejemplo n.º 8
0
        public void TestSaveItemToIarNoAssets()
        {
            TestHelpers.InMethod();
//            log4net.Config.XmlConfigurator.Configure();

            // Create user
            string userFirstName = "Jock";
            string userLastName  = "Stirrup";
            string userPassword  = "******";
            UUID   userId        = UUID.Parse("00000000-0000-0000-0000-000000000020");

            UserAccountHelpers.CreateUserWithInventory(m_scene, userFirstName, userLastName, userId, userPassword);

            // Create asset
            UUID             ownerId = UUID.Parse("00000000-0000-0000-0000-000000000040");
            SceneObjectGroup object1 = SceneHelpers.CreateSceneObject(1, ownerId, "My Little Dog Object", 0x50);

            UUID      asset1Id = UUID.Parse("00000000-0000-0000-0000-000000000060");
            AssetBase asset1   = AssetHelpers.CreateAsset(asset1Id, object1);

            m_scene.AssetService.Store(asset1);

            // Create item
            UUID              item1Id   = UUID.Parse("00000000-0000-0000-0000-000000000080");
            string            item1Name = "My Little Dog";
            InventoryItemBase item1     = new InventoryItemBase();

            item1.Name    = item1Name;
            item1.AssetID = asset1.FullID;
            item1.ID      = item1Id;
            InventoryFolderBase objsFolder
                = InventoryArchiveUtils.FindFolderByPath(m_scene.InventoryService, userId, "Objects")[0];

            item1.Folder = objsFolder.ID;
            m_scene.AddInventoryItem(item1);

            MemoryStream archiveWriteStream = new MemoryStream();

            Dictionary <string, Object> options = new Dictionary <string, Object>();

            options.Add("noassets", true);

            // When we're not saving assets, archiving is being done synchronously.
            m_archiverModule.ArchiveInventory(
                Guid.NewGuid(), userFirstName, userLastName, "Objects/" + item1Name, userPassword, archiveWriteStream, options);

            byte[]           archive           = archiveWriteStream.ToArray();
            MemoryStream     archiveReadStream = new MemoryStream(archive);
            TarArchiveReader tar = new TarArchiveReader(archiveReadStream);

            //bool gotControlFile = false;
            bool gotObject1File = false;
            //bool gotObject2File = false;
            string expectedObject1FileName = InventoryArchiveWriteRequest.CreateArchiveItemName(item1);
            string expectedObject1FilePath = string.Format(
                "{0}{1}",
                ArchiveConstants.INVENTORY_PATH,
                expectedObject1FileName);

            string filePath;

            TarArchiveReader.TarEntryType tarEntryType;

//            Console.WriteLine("Reading archive");

            while (tar.ReadEntry(out filePath, out tarEntryType) != null)
            {
                Console.WriteLine("Got {0}", filePath);

//                if (ArchiveConstants.CONTROL_FILE_PATH == filePath)
//                {
//                    gotControlFile = true;
//                }

                if (filePath.StartsWith(ArchiveConstants.INVENTORY_PATH) && filePath.EndsWith(".xml"))
                {
//                    string fileName = filePath.Remove(0, "Objects/".Length);
//
//                    if (fileName.StartsWith(part1.Name))
//                    {
                    Assert.That(expectedObject1FilePath, Is.EqualTo(filePath));
                    gotObject1File = true;
//                    }
//                    else if (fileName.StartsWith(part2.Name))
//                    {
//                        Assert.That(fileName, Is.EqualTo(expectedObject2FileName));
//                        gotObject2File = true;
//                    }
                }
                else if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH))
                {
                    Assert.Fail("Found asset path in TestSaveItemToIarNoAssets()");
                }
            }

//            Assert.That(gotControlFile, Is.True, "No control file in archive");
            Assert.That(gotObject1File, Is.True, "No item1 file in archive");
//            Assert.That(gotObject2File, Is.True, "No object2 file in archive");

            // TODO: Test presence of more files and contents of files.
        }
Ejemplo n.º 9
0
        public static RegionSettings FromStream(Stream stream)
        {
            RegionSettings settings = new RegionSettings();

            System.Globalization.NumberFormatInfo nfi = Utils.EnUsCulture.NumberFormat;

            using (XmlTextReader xtr = new XmlTextReader(stream))
            {
                xtr.ReadStartElement("RegionSettings");
                xtr.ReadStartElement("General");

                while (xtr.Read() && xtr.NodeType != XmlNodeType.EndElement)
                {
                    switch (xtr.Name)
                    {
                    case "AllowDamage":
                        settings.AllowDamage = Boolean.Parse(xtr.ReadElementContentAsString());
                        break;

                    case "AllowLandResell":
                        settings.AllowLandResell = Boolean.Parse(xtr.ReadElementContentAsString());
                        break;

                    case "AllowLandJoinDivide":
                        settings.AllowLandJoinDivide = Boolean.Parse(xtr.ReadElementContentAsString());
                        break;

                    case "BlockFly":
                        settings.BlockFly = Boolean.Parse(xtr.ReadElementContentAsString());
                        break;

                    case "BlockLandShowInSearch":
                        settings.BlockLandShowInSearch = Boolean.Parse(xtr.ReadElementContentAsString());
                        break;

                    case "BlockTerraform":
                        settings.BlockTerraform = Boolean.Parse(xtr.ReadElementContentAsString());
                        break;

                    case "DisableCollisions":
                        settings.DisableCollisions = Boolean.Parse(xtr.ReadElementContentAsString());
                        break;

                    case "DisablePhysics":
                        settings.DisablePhysics = Boolean.Parse(xtr.ReadElementContentAsString());
                        break;

                    case "DisableScripts":
                        settings.DisableScripts = Boolean.Parse(xtr.ReadElementContentAsString());
                        break;

                    case "MaturityRating":
                        settings.MaturityRating = Int32.Parse(xtr.ReadElementContentAsString());
                        break;

                    case "RestrictPushing":
                        settings.RestrictPushing = Boolean.Parse(xtr.ReadElementContentAsString());
                        break;

                    case "AgentLimit":
                        settings.AgentLimit = Int32.Parse(xtr.ReadElementContentAsString());
                        break;

                    case "ObjectBonus":
                        settings.ObjectBonus = Single.Parse(xtr.ReadElementContentAsString(), nfi);
                        break;
                    }
                }

                xtr.ReadEndElement();
                xtr.ReadStartElement("GroundTextures");

                while (xtr.Read() && xtr.NodeType != XmlNodeType.EndElement)
                {
                    switch (xtr.Name)
                    {
                    case "Texture1":
                        settings.TerrainDetail0 = UUID.Parse(xtr.ReadElementContentAsString());
                        break;

                    case "Texture2":
                        settings.TerrainDetail1 = UUID.Parse(xtr.ReadElementContentAsString());
                        break;

                    case "Texture3":
                        settings.TerrainDetail2 = UUID.Parse(xtr.ReadElementContentAsString());
                        break;

                    case "Texture4":
                        settings.TerrainDetail3 = UUID.Parse(xtr.ReadElementContentAsString());
                        break;

                    case "ElevationLowSW":
                        settings.TerrainStartHeight00 = Single.Parse(xtr.ReadElementContentAsString(), nfi);
                        break;

                    case "ElevationLowNW":
                        settings.TerrainStartHeight01 = Single.Parse(xtr.ReadElementContentAsString(), nfi);
                        break;

                    case "ElevationLowSE":
                        settings.TerrainStartHeight10 = Single.Parse(xtr.ReadElementContentAsString(), nfi);
                        break;

                    case "ElevationLowNE":
                        settings.TerrainStartHeight11 = Single.Parse(xtr.ReadElementContentAsString(), nfi);
                        break;

                    case "ElevationHighSW":
                        settings.TerrainHeightRange00 = Single.Parse(xtr.ReadElementContentAsString(), nfi);
                        break;

                    case "ElevationHighNW":
                        settings.TerrainHeightRange01 = Single.Parse(xtr.ReadElementContentAsString(), nfi);
                        break;

                    case "ElevationHighSE":
                        settings.TerrainHeightRange10 = Single.Parse(xtr.ReadElementContentAsString(), nfi);
                        break;

                    case "ElevationHighNE":
                        settings.TerrainHeightRange11 = Single.Parse(xtr.ReadElementContentAsString(), nfi);
                        break;
                    }
                }

                xtr.ReadEndElement();
                xtr.ReadStartElement("Terrain");

                while (xtr.Read() && xtr.NodeType != XmlNodeType.EndElement)
                {
                    switch (xtr.Name)
                    {
                    case "WaterHeight":
                        settings.WaterHeight = Single.Parse(xtr.ReadElementContentAsString(), nfi);
                        break;

                    case "TerrainRaiseLimit":
                        settings.TerrainRaiseLimit = Single.Parse(xtr.ReadElementContentAsString(), nfi);
                        break;

                    case "TerrainLowerLimit":
                        settings.TerrainLowerLimit = Single.Parse(xtr.ReadElementContentAsString(), nfi);
                        break;

                    case "UseEstateSun":
                        settings.UseEstateSun = Boolean.Parse(xtr.ReadElementContentAsString());
                        break;

                    case "FixedSun":
                        settings.FixedSun = Boolean.Parse(xtr.ReadElementContentAsString());
                        break;
                    }
                }
            }

            return(settings);
        }
Ejemplo n.º 10
0
        public Dictionary <string, object> Fill(WebInterface webInterface, string filename, OSHttpRequest httpRequest,
                                                OSHttpResponse httpResponse, Dictionary <string, object> requestParameters,
                                                ITranslator translator, out string response)
        {
            // under development
            //response = "<h3>Sorry! This feature is not available yet<</h3><br /> Redirecting to main page" +
            //    "<script language=\"javascript\">" +
            //    "setTimeout(function() {window.location.href = \"index.html\";}, 3000);" +
            //    "</script>";
            //return null;

            response = null;
            var vars = new Dictionary <string, object> ();

            if (httpRequest.Query.ContainsKey("regionid"))
            {
                var regionService = webInterface.Registry.RequestModuleInterface <IGridService> ();
                var region        = regionService.GetRegionByUUID(null, UUID.Parse(httpRequest.Query ["regionid"].ToString()));

                IEstateConnector estateConnector = Framework.Utilities.DataManager.RequestPlugin <IEstateConnector> ();
                var    ownerUUID = UUID.Zero;
                string ownerName = "Unknown";
                if (estateConnector != null)
                {
                    EstateSettings estate = estateConnector.GetRegionEstateSettings(region.RegionID);
                    if (estate != null)
                    {
                        ownerUUID = estate.EstateOwner;
                        UserAccount estateOwnerAccount = new UserAccount();
                        var         accountService     = webInterface.Registry.RequestModuleInterface <IUserAccountService> ();
                        if (accountService != null)
                        {
                            estateOwnerAccount = accountService.GetUserAccount(null, estate.EstateOwner);
                        }
                        ownerName = estateOwnerAccount.Valid ? estateOwnerAccount.Name : "No account found";
                    }
                }

                vars.Add("OwnerUUID", ownerUUID);
                vars.Add("OwnerName", ownerName);
                vars.Add("RegionName", region.RegionName);
                vars.Add("RegionLocX", region.RegionLocX / Constants.RegionSize);
                vars.Add("RegionLocY", region.RegionLocY / Constants.RegionSize);
                vars.Add("RegionSizeX", region.RegionSizeX);
                vars.Add("RegionSizeY", region.RegionSizeY);
                vars.Add("RegionType", region.RegionType);
                vars.Add("RegionTerrain", region.RegionTerrain);
                vars.Add("RegionOnline",
                         (region.Flags & (int)RegionFlags.RegionOnline) ==
                         (int)RegionFlags.RegionOnline
                    ? translator.GetTranslatedString("Online")
                    : translator.GetTranslatedString("Offline"));

                IDirectoryServiceConnector directoryConnector =
                    Framework.Utilities.DataManager.RequestPlugin <IDirectoryServiceConnector> ();
                if (directoryConnector != null)
                {
                    IUserAccountService accountService =
                        webInterface.Registry.RequestModuleInterface <IUserAccountService> ();
                    List <LandData> data = directoryConnector.GetParcelsByRegion(0, 10, region.RegionID, UUID.Zero,
                                                                                 ParcelFlags.None, ParcelCategory.Any);
                    List <Dictionary <string, object> > parcels = new List <Dictionary <string, object> > ();
                    string url = "../images/icons/no_parcel.jpg";

                    if (data != null)
                    {
                        foreach (var p in data)
                        {
                            Dictionary <string, object> parcel = new Dictionary <string, object> ();
                            parcel.Add("ParcelNameText", translator.GetTranslatedString("ParcelNameText"));
                            parcel.Add("ParcelOwnerText", translator.GetTranslatedString("ParcelOwnerText"));
                            parcel.Add("ParcelUUID", p.GlobalID);
                            parcel.Add("ParcelName", p.Name);
                            parcel.Add("ParcelOwnerUUID", p.OwnerID);
                            parcel.Add("ParcelSnapshotURL", url);
                            if (accountService != null)
                            {
                                var parcelownerAcct = accountService.GetUserAccount(null, p.OwnerID);
                                if (parcelownerAcct.Valid)
                                {
                                    parcel.Add("ParcelOwnerName", parcelownerAcct.Name);
                                }
                                else
                                {
                                    parcel.Add("ParcelOwnerName", translator.GetTranslatedString("NoAccountFound"));
                                }
                            }
                            parcels.Add(parcel);
                        }
                    }
                    vars.Add("ParcelInRegion", parcels);
                    vars.Add("NumberOfParcelsInRegion", parcels.Count);
                }
                IWebHttpTextureService webTextureService = webInterface.Registry.
                                                           RequestModuleInterface <IWebHttpTextureService> ();
                if (webTextureService != null && region.TerrainMapImage != UUID.Zero)
                {
                    vars.Add("RegionImageURL", webTextureService.GetTextureURL(region.TerrainMapImage));
                }
                else
                {
                    vars.Add("RegionImageURL", "../images/icons/no_terrain.jpg");
                }

                /*   // Regionprofile Menus
                 * vars.Add("MenuRegionTitle", translator.GetTranslatedString("MenuRegionTitle"));
                 * vars.Add("TooltipsMenuRegion", translator.GetTranslatedString("TooltipsMenuRegion"));
                 * vars.Add("MenuParcelTitle", translator.GetTranslatedString("MenuParcelTitle"));
                 * vars.Add("TooltipsMenuParcel", translator.GetTranslatedString("TooltipsMenuParcel"));
                 * vars.Add("MenuOwnerTitle", translator.GetTranslatedString("MenuOwnerTitle"));
                 * vars.Add("TooltipsMenuOwner", translator.GetTranslatedString("TooltipsMenuOwner"));
                 */
                vars.Add("RegionInformationText", translator.GetTranslatedString("RegionInformationText"));
                vars.Add("OwnerNameText", translator.GetTranslatedString("OwnerNameText"));
                vars.Add("RegionLocationText", translator.GetTranslatedString("RegionLocationText"));
                vars.Add("RegionSizeText", translator.GetTranslatedString("RegionSizeText"));
                vars.Add("RegionNameText", translator.GetTranslatedString("RegionNameText"));
                vars.Add("RegionTypeText", translator.GetTranslatedString("RegionTypeText"));
                vars.Add("RegionTerrainText", translator.GetTranslatedString("RegionTerrainText"));
                vars.Add("RegionInfoText", translator.GetTranslatedString("RegionInfoText"));
                vars.Add("RegionOnlineText", translator.GetTranslatedString("RegionOnlineText"));
                vars.Add("NumberOfUsersInRegionText", translator.GetTranslatedString("NumberOfUsersInRegionText"));
                vars.Add("ParcelsInRegionText", translator.GetTranslatedString("ParcelsInRegionText"));
                vars.Add("MainServerURL", webInterface.GridURL);
            }

            return(vars);
        }
        private static InventoryItem LoadInventoryItemData(
            XmlTextReader reader,
            UGUI principal,
            List <AvatarNameServiceInterface> nameServices)
        {
            var item = new InventoryItem
            {
                Owner = principal
            };

            for (;;)
            {
                if (!reader.Read())
                {
                    throw new IARFormatException();
                }

                switch (reader.NodeType)
                {
                case XmlNodeType.Element:
                    switch (reader.Name)
                    {
                    case "Name":
                        item.Name = reader.ReadElementValueAsString();
                        break;

                    case "InvType":
                        item.InventoryType = (InventoryType)reader.ReadElementValueAsInt();
                        break;

                    case "CreatorUUID":
                    {
                        string text = reader.ReadElementValueAsString();
                        UUID   uuid;
                        if (text.StartsWith("ospa:n="))
                        {
                            string[] name = text.Substring(7).Split(' ');
                            /* OpenSim tag version */
                            item.Creator.ID = UUID.Zero;
                            string firstName = name[0];
                            string lastName  = (name.Length > 1) ? name[1] : string.Empty;

                            /* hope that name service knows that avatar */
                            try
                            {
                                item.Creator = nameServices.FindUUIByName(firstName, lastName);
                            }
                            catch
                            {
                                item.Creator = principal;
                            }
                        }
                        else if (UUID.TryParse(text, out uuid))
                        {
                            try
                            {
                                item.Creator = nameServices.FindUUIById(uuid);
                            }
                            catch
                            {
                                item.Creator.ID = uuid;
                            }
                        }
                        else
                        {
                            item.Creator = principal;
                        }
                    }
                    break;

                    case "CreatorData":
                    {
                        string creatorData = reader.ReadElementValueAsString();
                        try
                        {
                            item.Creator.CreatorData = creatorData;
                        }
                        catch
                        {
                            /* ignore misformatted creator data */
                        }
                    }
                    break;

                    case "CreationDate":
                        item.CreationDate = Date.UnixTimeToDateTime(reader.ReadElementValueAsULong());
                        break;

                    case "Description":
                        item.Description = reader.ReadElementValueAsString();
                        break;

                    case "AssetType":
                        item.AssetType = (AssetType)reader.ReadElementValueAsInt();
                        break;

                    case "AssetID":
                        item.AssetID = UUID.Parse(reader.ReadElementValueAsString());
                        break;

                    case "SalePrice":
                        item.SaleInfo.Price = reader.ReadElementValueAsInt();
                        break;

                    case "SaleType":
                        item.SaleInfo.Type = (InventoryItem.SaleInfoData.SaleType)reader.ReadElementValueAsUInt();
                        break;

                    case "BasePermissions":
                        item.Permissions.Base = (InventoryPermissionsMask)reader.ReadElementValueAsUInt();
                        break;

                    case "CurrentPermissions":
                        item.Permissions.Current = (InventoryPermissionsMask)reader.ReadElementValueAsUInt();
                        break;

                    case "EveryOnePermissions":
                        item.Permissions.EveryOne = (InventoryPermissionsMask)reader.ReadElementValueAsUInt();
                        break;

                    case "NextPermissions":
                        item.Permissions.NextOwner = (InventoryPermissionsMask)reader.ReadElementValueAsUInt();
                        break;

                    case "Flags":
                        item.Flags = (InventoryFlags)reader.ReadElementValueAsUInt();
                        break;

                    case "GroupID":
                        item.Group.ID = reader.ReadElementValueAsString();
                        break;

                    case "GroupOwned":
                        item.IsGroupOwned = reader.ReadElementValueAsBoolean();
                        break;

                    case "ID":
                        item.SetNewID(UUID.Parse(reader.ReadElementValueAsString()));
                        break;

                    case "Owner":
                    default:
                        if (!reader.IsEmptyElement)
                        {
                            reader.Skip();
                        }
                        break;
                    }
                    break;

                case XmlNodeType.EndElement:
                    if (reader.Name != "InventoryItem")
                    {
                        throw new IARFormatException();
                    }
                    return(item);

                default:
                    break;
                }
            }
        }
Ejemplo n.º 12
0
        public void ImportTaskObjects(ImportSettings importSettings)
        {
            DateTime lastProgressNotice    = DateTime.Now;
            int      incomplete            = 0;
            var      agentSyncFolderHolder = Exporting.FolderCalled("TaskInvHolder");
            int      created = 0;
            var      tos     = LocalScene.TaskObjects;

            foreach (var file in Directory.GetFiles(ExportCommand.dumpDir, "*.taskobj"))
            {
                string[]     c  = File.ReadAllText(file).Split(',');
                TaskFileInfo to = new TaskFileInfo()
                {
                    OldLid        = uint.Parse(c[0]),
                    RezzedID      = UUID.Parse(c[2]),
                    OldTaskHolder = UUID.Parse(c[3]),
                    AssetUUID     = UUID.Parse(c[4]),
                    TaskItemID    = UUID.Parse(c[5])
                };
                tos.Add(to);
                created++;
            }
            foreach (TaskFileInfo o in tos)
            {
                var r = o.Rezzed;
                if (r != null)
                {
                    r.SetIsAsset();
                }
            }

            foreach (TaskFileInfo o in tos)
            {
                PrimToCreate oInsideOf = o.InsideOf;
                if (oInsideOf == null)
                {
                    continue;
                }
                List <InventoryBase> taskInv = oInsideOf.SourceTaskInventory(true);
                if (taskInv == null)
                {
                    continue;
                }
                foreach (var b in taskInv)
                {
                    InventoryItem i = b as InventoryItem;
                    if (i == null)
                    {
                        continue;
                    }
                    if (CogbotHelpers.IsNullOrZero(i.AssetUUID))
                    {
                        if (i.UUID == o.TaskItemID)
                        {
                            i.RezzID   = o.RezzedID;
                            o.IsPlaced = true;
                            break;
                        }
                    }
                }
            }
            foreach (TaskFileInfo o in tos)
            {
                if (!o.IsPlaced)
                {
                    Failure("UNPLACED: " + o);
                }
            }
            // this makes sure we know that late found childs are assets
            foreach (PrimToCreate parent in LockInfo.CopyOf(parents))
            {
                if (parent.IsAsset)
                {
                    parent.SetIsAsset();
                }
            }
        }
Ejemplo n.º 13
0
        private void CheckTasks(ImportSettings settings)
        {
            foreach (PrimToCreate parent in LockInfo.CopyOf(parents))
            {
                var ls = new Linkset()
                {
                    Parent = parent
                };
                parent.Link = ls;
                LocalScene.Links.Add(ls);
            }
            foreach (PrimToCreate ch in childs)
            {
                var pp = ch.ParentPrim;
                if (pp == null)
                {
                    continue;
                }
                pp.Link.ChildAdd(ch);
            }
            foreach (var ls in LockInfo.CopyOf(LocalScene.Links))
            {
                ls.Children.Sort(compareLocalIDs);
                if (ls.Parent.IsAsset)
                {
                    LocalScene.AssetLinks.Add(ls);
                    LocalScene.Links.Remove(ls);
                }
            }

            int found = 0;
            Dictionary <UUID, TaskFileInfo> item2TO  = new Dictionary <UUID, TaskFileInfo>();
            List <TaskFileInfo>             mssingTO = new List <TaskFileInfo>();
            List <TaskFileInfo>             duped    = new List <TaskFileInfo>();

            foreach (var file in Directory.GetFiles(ExportCommand.dumpDir, "*.objectAsset"))
            {
                break;
                found++;
                string   fileString = File.ReadAllText(file);
                string[] c          = fileString.Split(',');
                try
                {
                    TaskFileInfo to = new TaskFileInfo()
                    {
                        OldLid        = uint.Parse(c[0]),
                        RezzedID      = UUID.Parse(c[2]),
                        OldTaskHolder = UUID.Parse(c[3]),
                        AssetUUID     = UUID.Parse(c[4]),
                        TaskItemID    = UUID.Parse(c[5])
                    };
                    bool missing = false;
                    if (MissingLLSD(to.RezzedID))
                    {
                        Failure("Need LLSD: " + fileString);
                        to.missingLLSD = true;
                        mssingTO.Add(to);
                    }
                    TaskFileInfo old;
                    if (item2TO.TryGetValue(to.TaskItemID, out old))
                    {
                        if (old.missingLLSD)
                        {
                            item2TO[to.TaskItemID] = to;
                            duped.Add(old);
                        }
                        else
                        {
                            duped.Add(to);
                        }
                    }
                    else
                    {
                        if (to.missingLLSD)
                        {
                            continue;
                        }
                        item2TO[to.TaskItemID] = to;
                    }
                }
                catch (Exception ee)
                {
                    Failure("fileIssue: " + file + " = " + fileString);
                }
            }
            Success("t=" + found + " m=" + mssingTO.Count + " td=" + item2TO.Count + " duped=" + duped.Count);
        }
Ejemplo n.º 14
0
        /// <summary>
        ///     Reify/deserialize landData
        /// </summary>
        /// <param name="serializedLandData"></param>
        /// <returns></returns>
        /// <exception cref="System.Xml.XmlException"></exception>
        public static LandData Deserialize(string serializedLandData)
        {
            LandData landData = new LandData();

            StringReader  sr  = new StringReader(serializedLandData);
            XmlTextReader xtr = new XmlTextReader(sr);

            xtr.ReadStartElement("LandData");

            landData.Area           = Convert.ToInt32(xtr.ReadElementString("Area"));
            landData.AuctionID      = Convert.ToUInt32(xtr.ReadElementString("AuctionID"));
            landData.AuthBuyerID    = UUID.Parse(xtr.ReadElementString("AuthBuyerID"));
            landData.Category       = (ParcelCategory)Convert.ToSByte(xtr.ReadElementString("Category"));
            landData.ClaimDate      = Convert.ToInt32(xtr.ReadElementString("ClaimDate"));
            landData.ClaimPrice     = Convert.ToInt32(xtr.ReadElementString("ClaimPrice"));
            landData.GlobalID       = UUID.Parse(xtr.ReadElementString("GlobalID"));
            landData.GroupID        = UUID.Parse(xtr.ReadElementString("GroupID"));
            landData.IsGroupOwned   = Convert.ToBoolean(xtr.ReadElementString("IsGroupOwned"));
            landData.Bitmap         = Convert.FromBase64String(xtr.ReadElementString("Bitmap"));
            landData.Description    = xtr.ReadElementString("Description");
            landData.Flags          = Convert.ToUInt32(xtr.ReadElementString("Flags"));
            landData.LandingType    = Convert.ToByte(xtr.ReadElementString("LandingType"));
            landData.Name           = xtr.ReadElementString("Name");
            landData.Status         = (ParcelStatus)Convert.ToSByte(xtr.ReadElementString("Status"));
            landData.LocalID        = Convert.ToInt32(xtr.ReadElementString("LocalID"));
            landData.MediaAutoScale = Convert.ToByte(xtr.ReadElementString("MediaAutoScale"));
            landData.MediaID        = UUID.Parse(xtr.ReadElementString("MediaID"));
            landData.MediaURL       = xtr.ReadElementString("MediaURL");
            landData.MusicURL       = xtr.ReadElementString("MusicURL");
            landData.OwnerID        = UUID.Parse(xtr.ReadElementString("OwnerID"));

            landData.ParcelAccessList = new List <ParcelManager.ParcelAccessEntry>();
            xtr.Read();
            if (xtr.Name != "ParcelAccessList")
            {
                throw new XmlException(String.Format("Expected \"ParcelAccessList\" element but got \"{0}\"", xtr.Name));
            }

            if (!xtr.IsEmptyElement)
            {
                while (xtr.Read() && xtr.NodeType != XmlNodeType.EndElement)
                {
                    ParcelManager.ParcelAccessEntry pae = new ParcelManager.ParcelAccessEntry();

                    xtr.ReadStartElement("ParcelAccessEntry");
                    pae.AgentID = UUID.Parse(xtr.ReadElementString("AgentID"));
                    xtr.ReadElementString("Time");
                    pae.Flags = (AccessList)Convert.ToUInt32(xtr.ReadElementString("AccessList"));
                    pae.Time  = DateTime.UtcNow;
                    xtr.ReadEndElement();

                    landData.ParcelAccessList.Add(pae);
                }
            }
            xtr.Read();

            landData.PassHours    = Convert.ToSingle(xtr.ReadElementString("PassHours"));
            landData.PassPrice    = Convert.ToInt32(xtr.ReadElementString("PassPrice"));
            landData.SalePrice    = Convert.ToInt32(xtr.ReadElementString("SalePrice"));
            landData.SnapshotID   = UUID.Parse(xtr.ReadElementString("SnapshotID"));
            landData.UserLocation = Vector3.Parse(xtr.ReadElementString("UserLocation"));
            landData.UserLookAt   = Vector3.Parse(xtr.ReadElementString("UserLookAt"));
            // No longer used here
            xtr.ReadElementString("Dwell");
            landData.OtherCleanTime = Convert.ToInt32(xtr.ReadElementString("OtherCleanTime"));

            xtr.ReadEndElement();

            xtr.Close();
            sr.Close();

            return(landData);
        }
        public void TestLoadOarRegionSettings()
        {
            TestHelpers.InMethod();
            //log4net.Config.XmlConfigurator.Configure();

            MemoryStream     archiveWriteStream = new MemoryStream();
            TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream);

            tar.WriteDir(ArchiveConstants.TERRAINS_PATH);
            tar.WriteFile(
                ArchiveConstants.CONTROL_FILE_PATH,
                new ArchiveWriteRequest(m_scene, (Stream)null, Guid.Empty).CreateControlFile(new ArchiveScenesGroup()));

            RegionSettings rs = new RegionSettings();

            rs.AgentLimit          = 17;
            rs.AllowDamage         = true;
            rs.AllowLandJoinDivide = true;
            rs.AllowLandResell     = true;
            rs.BlockFly            = true;
            rs.BlockShowInSearch   = true;
            rs.BlockTerraform      = true;
            rs.DisableCollisions   = true;
            rs.DisablePhysics      = true;
            rs.DisableScripts      = true;
            rs.Elevation1NW        = 15.9;
            rs.Elevation1NE        = 45.3;
            rs.Elevation1SE        = 49;
            rs.Elevation1SW        = 1.9;
            rs.Elevation2NW        = 4.5;
            rs.Elevation2NE        = 19.2;
            rs.Elevation2SE        = 9.2;
            rs.Elevation2SW        = 2.1;
            rs.FixedSun            = true;
            rs.SunPosition         = 12.0;
            rs.ObjectBonus         = 1.4;
            rs.RestrictPushing     = true;
            rs.TerrainLowerLimit   = 0.4;
            rs.TerrainRaiseLimit   = 17.9;
            rs.TerrainTexture1     = UUID.Parse("00000000-0000-0000-0000-000000000020");
            rs.TerrainTexture2     = UUID.Parse("00000000-0000-0000-0000-000000000040");
            rs.TerrainTexture3     = UUID.Parse("00000000-0000-0000-0000-000000000060");
            rs.TerrainTexture4     = UUID.Parse("00000000-0000-0000-0000-000000000080");
            rs.UseEstateSun        = true;
            rs.WaterHeight         = 23;
            rs.TelehubObject       = UUID.Parse("00000000-0000-0000-0000-111111111111");
            rs.AddSpawnPoint(SpawnPoint.Parse("1,-2,0.33"));

            tar.WriteFile(ArchiveConstants.SETTINGS_PATH + "region1.xml", RegionSettingsSerializer.Serialize(rs));

            tar.Close();

            MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray());

            lock (this)
            {
                m_scene.EventManager.OnOarFileLoaded += LoadCompleted;
                m_archiverModule.DearchiveRegion(archiveReadStream);
            }

            Assert.That(m_lastErrorMessage, Is.Null);
            RegionSettings loadedRs = m_scene.RegionInfo.RegionSettings;

            Assert.That(loadedRs.AgentLimit, Is.EqualTo(17));
            Assert.That(loadedRs.AllowDamage, Is.True);
            Assert.That(loadedRs.AllowLandJoinDivide, Is.True);
            Assert.That(loadedRs.AllowLandResell, Is.True);
            Assert.That(loadedRs.BlockFly, Is.True);
            Assert.That(loadedRs.BlockShowInSearch, Is.True);
            Assert.That(loadedRs.BlockTerraform, Is.True);
            Assert.That(loadedRs.DisableCollisions, Is.True);
            Assert.That(loadedRs.DisablePhysics, Is.True);
            Assert.That(loadedRs.DisableScripts, Is.True);
            Assert.That(loadedRs.Elevation1NW, Is.EqualTo(15.9));
            Assert.That(loadedRs.Elevation1NE, Is.EqualTo(45.3));
            Assert.That(loadedRs.Elevation1SE, Is.EqualTo(49));
            Assert.That(loadedRs.Elevation1SW, Is.EqualTo(1.9));
            Assert.That(loadedRs.Elevation2NW, Is.EqualTo(4.5));
            Assert.That(loadedRs.Elevation2NE, Is.EqualTo(19.2));
            Assert.That(loadedRs.Elevation2SE, Is.EqualTo(9.2));
            Assert.That(loadedRs.Elevation2SW, Is.EqualTo(2.1));
            Assert.That(loadedRs.FixedSun, Is.True);
            Assert.AreEqual(12.0, loadedRs.SunPosition);
            Assert.That(loadedRs.ObjectBonus, Is.EqualTo(1.4));
            Assert.That(loadedRs.RestrictPushing, Is.True);
            Assert.That(loadedRs.TerrainLowerLimit, Is.EqualTo(0.4));
            Assert.That(loadedRs.TerrainRaiseLimit, Is.EqualTo(17.9));
            Assert.That(loadedRs.TerrainTexture1, Is.EqualTo(UUID.Parse("00000000-0000-0000-0000-000000000020")));
            Assert.That(loadedRs.TerrainTexture2, Is.EqualTo(UUID.Parse("00000000-0000-0000-0000-000000000040")));
            Assert.That(loadedRs.TerrainTexture3, Is.EqualTo(UUID.Parse("00000000-0000-0000-0000-000000000060")));
            Assert.That(loadedRs.TerrainTexture4, Is.EqualTo(UUID.Parse("00000000-0000-0000-0000-000000000080")));
            Assert.That(loadedRs.UseEstateSun, Is.True);
            Assert.That(loadedRs.WaterHeight, Is.EqualTo(23));
            Assert.AreEqual(UUID.Zero, loadedRs.TelehubObject); // because no object was found with the original UUID
            Assert.AreEqual(0, loadedRs.SpawnPoints().Count);
        }
Ejemplo n.º 16
0
        /**
         * @brief Load script state from the given XML doc into the script memory
         *  <ScriptState Engine="YEngine" Asset=...>
         *      <Running>...</Running>
         *      <DoGblInit>...</DoGblInit>
         *      <Permissions granted=... mask=... />
         *      RestoreDetectParams()
         *      <Plugins>
         *          ExtractXMLObjectArray("plugin")
         *      </Plugins>
         *      <Snapshot>
         *          MigrateInEventHandler()
         *      </Snapshot>
         *  </ScriptState>
         */
        private void LoadScriptState(XmlDocument doc)
        {
            // Everything we know is enclosed in <ScriptState>...</ScriptState>
            XmlElement scriptStateN = (XmlElement)doc.SelectSingleNode("ScriptState");

            if (scriptStateN == null)
            {
                throw new Exception("no <ScriptState> tag");
            }

            XmlElement XvariablesN = null;
            string     sen         = scriptStateN.GetAttribute("Engine");

            if ((sen == null) || (sen != m_Engine.ScriptEngineName))
            {
                XvariablesN = (XmlElement)scriptStateN.SelectSingleNode("Variables");
                if (XvariablesN == null)
                {
                    throw new Exception("<ScriptState> missing Engine=\"YEngine\" attribute");
                }
                processXstate(doc);
                return;
            }

            // AssetID is unique for the script source text so make sure the
            // state file was written for that source file
            string assetID = scriptStateN.GetAttribute("Asset");

            if (assetID != m_Item.AssetID.ToString())
            {
                throw new Exception("<ScriptState> assetID mismatch");
            }

            // Also match the sourceHash in case script was
            // loaded via 'xmroption fetchsource' and has changed
            string sourceHash = scriptStateN.GetAttribute("SourceHash");

            if ((sourceHash == null) || (sourceHash != m_ObjCode.sourceHash))
            {
                throw new Exception("<ScriptState> SourceHash mismatch");
            }

            // Get various attributes
            XmlElement runningN = (XmlElement)scriptStateN.SelectSingleNode("Running");

            m_Running = bool.Parse(runningN.InnerText);

            XmlElement doGblInitN = (XmlElement)scriptStateN.SelectSingleNode("DoGblInit");

            doGblInit = bool.Parse(doGblInitN.InnerText);

            if (m_XMRLSLApi != null)
            {
                XmlElement scpttimeN = (XmlElement)scriptStateN.SelectSingleNode("scrpTime");
                if (scpttimeN != null && Double.TryParse(scpttimeN.InnerText, out double t))
                {
                    m_XMRLSLApi.SetLSLTimer(Util.GetTimeStampMS() - t);
                }
            }

            double     minEventDelay  = 0.0;
            XmlElement minEventDelayN = (XmlElement)scriptStateN.SelectSingleNode("mEvtDly");

            if (minEventDelayN != null)
            {
                minEventDelay = Double.Parse(minEventDelayN.InnerText);
            }

            // get values used by stuff like llDetectedGrab, etc.
            DetectParams[] detParams = RestoreDetectParams(scriptStateN.SelectSingleNode("DetectArray"));

            // Restore queued events
            LinkedList <EventParams> eventQueue = RestoreEventQueue(scriptStateN.SelectSingleNode("EventQueue"));

            // Restore timers and listeners
            XmlElement pluginN = (XmlElement)scriptStateN.SelectSingleNode("Plugins");

            Object[] pluginData = ExtractXMLObjectArray(pluginN, "plugin");

            // Script's global variables and stack contents
            XmlElement snapshotN = (XmlElement)scriptStateN.SelectSingleNode("Snapshot");

            Byte[] data = Convert.FromBase64String(snapshotN.InnerText);
            using (MemoryStream ms = new MemoryStream())
            {
                ms.Write(data, 0, data.Length);
                ms.Seek(0, SeekOrigin.Begin);
                MigrateInEventHandler(ms);
            }

            XmlElement experienceKey = (XmlElement)scriptStateN.SelectSingleNode("ExperienceKey");

            m_Item.ExperienceID = UUID.Parse(experienceKey.InnerText);

            XmlElement permissionsN = (XmlElement)scriptStateN.SelectSingleNode("Permissions");

            m_Item.PermsGranter = new UUID(permissionsN.GetAttribute("granter"));
            m_Item.PermsMask    = Convert.ToInt32(permissionsN.GetAttribute("mask"));
            m_Part.Inventory.UpdateInventoryItem(m_Item, false, false);

            // Restore event queues, preserving any events that queued
            // whilst we were restoring the state
            lock (m_QueueLock)
            {
                m_DetectParams = detParams;
                foreach (EventParams evt in m_EventQueue)
                {
                    eventQueue.AddLast(evt);
                }

                m_EventQueue = eventQueue;
                for (int i = m_EventCounts.Length; --i >= 0;)
                {
                    m_EventCounts[i] = 0;
                }
                foreach (EventParams evt in m_EventQueue)
                {
                    ScriptEventCode eventCode = (ScriptEventCode)Enum.Parse(typeof(ScriptEventCode),
                                                                            evt.EventName);
                    m_EventCounts[(int)eventCode]++;
                }
            }

            // Requeue timer and listeners (possibly queuing new events)
            AsyncCommandManager.CreateFromData(m_Engine,
                                               m_LocalID, m_ItemID, m_Part.UUID,
                                               pluginData);

            MinEventDelay = minEventDelay;
        }
        public void TestSaveMultiRegionOar()
        {
            TestHelpers.InMethod();

            // Create test regions

            int WIDTH  = 2;
            int HEIGHT = 2;

            List <Scene> scenes = new List <Scene>();

            // Maps (Directory in OAR file -> scene)
            Dictionary <string, Scene> regionPaths = new Dictionary <string, Scene>();

            // Maps (Scene -> expected object paths)
            Dictionary <UUID, List <string> > expectedPaths = new Dictionary <UUID, List <string> >();

            // List of expected assets
            List <UUID> expectedAssets = new List <UUID>();

            for (uint y = 0; y < HEIGHT; y++)
            {
                for (uint x = 0; x < WIDTH; x++)
                {
                    Scene scene;
                    if (x == 0 && y == 0)
                    {
                        scene = m_scene;   // this scene was already created in SetUp()
                    }
                    else
                    {
                        scene = m_sceneHelpers.SetupScene(string.Format("Unit test region {0}", (y * WIDTH) + x + 1), UUID.Random(), 1000 + x, 1000 + y);
                        SceneHelpers.SetupSceneModules(scene, new ArchiverModule(), m_serialiserModule, new TerrainModule());
                    }
                    scenes.Add(scene);

                    string dir = String.Format("{0}_{1}_{2}", x + 1, y + 1, scene.RegionInfo.RegionName.Replace(" ", "_"));
                    regionPaths[dir] = scene;

                    SceneObjectGroup sog1;
                    SceneObjectGroup sog2;
                    UUID             ncAssetUuid;

                    CreateTestObjects(scene, out sog1, out sog2, out ncAssetUuid);

                    expectedPaths[scene.RegionInfo.RegionID] = new List <string>();
                    expectedPaths[scene.RegionInfo.RegionID].Add(ArchiveHelpers.CreateObjectPath(sog1));
                    expectedPaths[scene.RegionInfo.RegionID].Add(ArchiveHelpers.CreateObjectPath(sog2));

                    expectedAssets.Add(ncAssetUuid);
                }
            }

            // Save OAR
            MemoryStream archiveWriteStream = new MemoryStream();

            m_scene.EventManager.OnOarFileSaved += SaveCompleted;

            Guid requestId = new Guid("00000000-0000-0000-0000-808080808080");

            Dictionary <string, Object> options = new Dictionary <string, Object>();

            options.Add("all", true);

            lock (this)
            {
                m_archiverModule.ArchiveRegion(archiveWriteStream, requestId, options);
                Monitor.Wait(this, 60000);
            }

            // Check that the OAR contains the expected data
            Assert.That(m_lastRequestId, Is.EqualTo(requestId));

            byte[]           archive           = archiveWriteStream.ToArray();
            MemoryStream     archiveReadStream = new MemoryStream(archive);
            TarArchiveReader tar = new TarArchiveReader(archiveReadStream);

            Dictionary <UUID, List <string> > foundPaths = new Dictionary <UUID, List <string> >();
            List <UUID> foundAssets = new List <UUID>();

            foreach (Scene scene in scenes)
            {
                foundPaths[scene.RegionInfo.RegionID] = new List <string>();
            }

            string filePath;

            TarArchiveReader.TarEntryType tarEntryType;

            byte[] data = tar.ReadEntry(out filePath, out tarEntryType);
            Assert.That(filePath, Is.EqualTo(ArchiveConstants.CONTROL_FILE_PATH));

            Dictionary <string, object> archiveOptions = new Dictionary <string, object>();
            ArchiveReadRequest          arr            = new ArchiveReadRequest(m_scene, (Stream)null, Guid.Empty, archiveOptions);

            arr.LoadControlFile(filePath, data, new DearchiveScenesInfo());

            Assert.That(arr.ControlFileLoaded, Is.True);

            while (tar.ReadEntry(out filePath, out tarEntryType) != null)
            {
                if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH))
                {
                    // Assets are shared, so this file doesn't belong to any specific region.
                    string fileName = filePath.Remove(0, ArchiveConstants.ASSETS_PATH.Length);
                    if (fileName.EndsWith("_notecard.txt"))
                    {
                        foundAssets.Add(UUID.Parse(fileName.Substring(0, fileName.Length - "_notecard.txt".Length)));
                    }
                }
                else
                {
                    // This file belongs to one of the regions. Find out which one.
                    Assert.IsTrue(filePath.StartsWith(ArchiveConstants.REGIONS_PATH));
                    string[] parts = filePath.Split(new Char[] { '/' }, 3);
                    Assert.AreEqual(3, parts.Length);
                    string regionDirectory = parts[1];
                    string relativePath    = parts[2];
                    Scene  scene           = regionPaths[regionDirectory];

                    if (relativePath.StartsWith(ArchiveConstants.OBJECTS_PATH))
                    {
                        foundPaths[scene.RegionInfo.RegionID].Add(relativePath);
                    }
                }
            }

            Assert.AreEqual(scenes.Count, foundPaths.Count);
            foreach (Scene scene in scenes)
            {
                Assert.That(foundPaths[scene.RegionInfo.RegionID], Is.EquivalentTo(expectedPaths[scene.RegionInfo.RegionID]));
            }

            Assert.That(foundAssets, Is.EquivalentTo(expectedAssets));
        }
Ejemplo n.º 18
0
        private void processXstate(XmlDocument doc)
        {
            XmlNodeList rootL = doc.GetElementsByTagName("ScriptState");

            if (rootL.Count != 1)
            {
                throw new Exception("Xstate <ScriptState> missing");
            }

            XmlNode rootNode = rootL[0];

            if (rootNode == null)
            {
                throw new Exception("Xstate root missing");
            }

            string stateName = "";
            bool   running   = false;

            UUID   permsGranter  = UUID.Zero;
            int    permsMask     = 0;
            double minEventDelay = 0.0;

            Object[] pluginData    = new Object[0];
            UUID     experienceKey = UUID.Zero;

            LinkedList <EventParams> eventQueue = new LinkedList <EventParams>();

            Dictionary <string, int> intNames      = new Dictionary <string, int>();
            Dictionary <string, int> doubleNames   = new Dictionary <string, int>();
            Dictionary <string, int> stringNames   = new Dictionary <string, int>();
            Dictionary <string, int> vectorNames   = new Dictionary <string, int>();
            Dictionary <string, int> rotationNames = new Dictionary <string, int>();
            Dictionary <string, int> listNames     = new Dictionary <string, int>();

            int nn = m_ObjCode.globalVarNames.Count;

            int[]          ints      = null;
            double[]       doubles   = null;
            string[]       strings   = null;
            LSL_Vector[]   vectors   = null;
            LSL_Rotation[] rotations = null;
            LSL_List[]     lists     = null;

            if (nn > 0)
            {
                if (m_ObjCode.globalVarNames.ContainsKey("iarIntegers"))
                {
                    getvarNames(m_ObjCode.globalVarNames["iarIntegers"], intNames);
                    ints = new int[m_ObjCode.globalVarNames["iarIntegers"].Count];
                }
                if (m_ObjCode.globalVarNames.ContainsKey("iarFloats"))
                {
                    getvarNames(m_ObjCode.globalVarNames["iarFloats"], doubleNames);
                    doubles = new double[m_ObjCode.globalVarNames["iarFloats"].Count];
                }
                if (m_ObjCode.globalVarNames.ContainsKey("iarVectors"))
                {
                    getvarNames(m_ObjCode.globalVarNames["iarVectors"], vectorNames);
                    vectors = new LSL_Vector[m_ObjCode.globalVarNames["iarVectors"].Count];
                }
                if (m_ObjCode.globalVarNames.ContainsKey("iarRotations"))
                {
                    getvarNames(m_ObjCode.globalVarNames["iarRotations"], rotationNames);
                    rotations = new LSL_Rotation[m_ObjCode.globalVarNames["iarRotations"].Count];
                }
                if (m_ObjCode.globalVarNames.ContainsKey("iarStrings"))
                {
                    getvarNames(m_ObjCode.globalVarNames["iarStrings"], stringNames);
                    strings = new string[m_ObjCode.globalVarNames["iarStrings"].Count];
                }
                if (m_ObjCode.globalVarNames.ContainsKey("iarLists"))
                {
                    getvarNames(m_ObjCode.globalVarNames["iarLists"], listNames);
                    lists = new LSL_List[m_ObjCode.globalVarNames["iarLists"].Count];
                }
            }

            int heapsz = 0;

            try
            {
                XmlNodeList partL = rootNode.ChildNodes;
                foreach (XmlNode part in partL)
                {
                    switch (part.Name)
                    {
                    case "State":
                        stateName = part.InnerText;
                        break;

                    case "Running":
                        running = bool.Parse(part.InnerText);
                        break;

                    case "ExperienceKey":
                        experienceKey = UUID.Parse(part.InnerText);
                        break;

                    case "Variables":
                        int         indx;
                        XmlNodeList varL = part.ChildNodes;
                        foreach (XmlNode var in varL)
                        {
                            string varName;
                            object o     = ReadXTypedValue(var, out varName);
                            Type   otype = o.GetType();
                            if (otype == typeof(LSL_Integer))
                            {
                                if (intNames.TryGetValue(varName, out indx))
                                {
                                    ints[indx] = ((LSL_Integer)o);
                                }
                                continue;
                            }
                            if (otype == typeof(LSL_Float))
                            {
                                if (doubleNames.TryGetValue(varName, out indx))
                                {
                                    doubles[indx] = ((LSL_Float)o);
                                }
                                continue;
                            }
                            if (otype == typeof(LSL_String))
                            {
                                if (stringNames.TryGetValue(varName, out indx))
                                {
                                    strings[indx] = ((LSL_String)o);
                                    heapsz       += ((LSL_String)o).Length;
                                }
                                continue;
                            }
                            if (otype == typeof(LSL_Rotation))
                            {
                                if (rotationNames.TryGetValue(varName, out indx))
                                {
                                    rotations[indx] = ((LSL_Rotation)o);
                                }
                                continue;
                            }
                            if (otype == typeof(LSL_Vector))
                            {
                                if (vectorNames.TryGetValue(varName, out indx))
                                {
                                    vectors[indx] = ((LSL_Vector)o);
                                }
                                continue;
                            }
                            if (otype == typeof(LSL_Key))
                            {
                                if (stringNames.TryGetValue(varName, out indx))
                                {
                                    strings[indx] = ((LSL_Key)o);
                                    heapsz       += ((LSL_String)o).Length;
                                }
                                continue;
                            }
                            if (otype == typeof(UUID))
                            {
                                if (stringNames.TryGetValue(varName, out indx))
                                {
                                    LSL_String id = ((UUID)o).ToString();
                                    strings[indx] = (id);
                                    heapsz       += id.Length;
                                }
                                continue;
                            }
                            if (otype == typeof(LSL_List))
                            {
                                if (listNames.TryGetValue(varName, out indx))
                                {
                                    LSL_List lo = (LSL_List)o;
                                    lists[indx] = (lo);
                                    heapsz     += lo.Size;
                                }
                                continue;
                            }
                        }
                        break;

                    case "Queue":
                        XmlNodeList itemL = part.ChildNodes;
                        foreach (XmlNode item in itemL)
                        {
                            List <Object>       parms    = new List <Object>();
                            List <DetectParams> detected = new List <DetectParams>();

                            string      eventName = item.Attributes.GetNamedItem("event").Value;
                            XmlNodeList eventL    = item.ChildNodes;
                            foreach (XmlNode evt in eventL)
                            {
                                switch (evt.Name)
                                {
                                case "Params":
                                    XmlNodeList prms = evt.ChildNodes;
                                    foreach (XmlNode pm in prms)
                                    {
                                        parms.Add(ReadXTypedValue(pm));
                                    }

                                    break;

                                case "Detected":
                                    XmlNodeList detL = evt.ChildNodes;
                                    foreach (XmlNode det in detL)
                                    {
                                        string     vect = det.Attributes.GetNamedItem("pos").Value;
                                        LSL_Vector v    = new LSL_Vector(vect);

                                        int          d_linkNum  = 0;
                                        UUID         d_group    = UUID.Zero;
                                        string       d_name     = String.Empty;
                                        UUID         d_owner    = UUID.Zero;
                                        LSL_Vector   d_position = new LSL_Vector();
                                        LSL_Rotation d_rotation = new LSL_Rotation();
                                        int          d_type     = 0;
                                        LSL_Vector   d_velocity = new LSL_Vector();

                                        try
                                        {
                                            string tmp;

                                            tmp = det.Attributes.GetNamedItem("linkNum").Value;
                                            int.TryParse(tmp, out d_linkNum);

                                            tmp = det.Attributes.GetNamedItem("group").Value;
                                            UUID.TryParse(tmp, out d_group);

                                            d_name = det.Attributes.GetNamedItem("name").Value;

                                            tmp = det.Attributes.GetNamedItem("owner").Value;
                                            UUID.TryParse(tmp, out d_owner);

                                            tmp        = det.Attributes.GetNamedItem("position").Value;
                                            d_position = new LSL_Types.Vector3(tmp);

                                            tmp        = det.Attributes.GetNamedItem("rotation").Value;
                                            d_rotation = new LSL_Rotation(tmp);

                                            tmp = det.Attributes.GetNamedItem("type").Value;
                                            int.TryParse(tmp, out d_type);

                                            tmp        = det.Attributes.GetNamedItem("velocity").Value;
                                            d_velocity = new LSL_Vector(tmp);
                                        }
                                        catch (Exception)         // Old version XML
                                        {
                                        }

                                        UUID uuid = new UUID();
                                        UUID.TryParse(det.InnerText, out uuid);

                                        DetectParams d = new DetectParams();
                                        d.Key       = uuid;
                                        d.OffsetPos = v;
                                        d.LinkNum   = d_linkNum;
                                        d.Group     = d_group;
                                        d.Name      = d_name;
                                        d.Owner     = d_owner;
                                        d.Position  = d_position;
                                        d.Rotation  = d_rotation;
                                        d.Type      = d_type;
                                        d.Velocity  = d_velocity;

                                        detected.Add(d);
                                    }
                                    break;
                                }
                            }
                            EventParams ep = new EventParams(
                                eventName, parms.ToArray(),
                                detected.ToArray());
                            eventQueue.AddLast(ep);
                        }
                        break;

                    case "Plugins":
                        List <Object> olist  = new List <Object>();
                        XmlNodeList   itemLP = part.ChildNodes;
                        foreach (XmlNode item in itemLP)
                        {
                            olist.Add(ReadXTypedValue(item));
                        }
                        pluginData = olist.ToArray();
                        break;

                    case "Permissions":
                        string tmpPerm;
                        int    mask = 0;
                        tmpPerm = part.Attributes.GetNamedItem("mask").Value;
                        if (tmpPerm != null)
                        {
                            int.TryParse(tmpPerm, out mask);
                            if (mask != 0)
                            {
                                tmpPerm = part.Attributes.GetNamedItem("granter").Value;
                                if (tmpPerm != null)
                                {
                                    UUID granter = new UUID();
                                    UUID.TryParse(tmpPerm, out granter);
                                    if (granter != UUID.Zero)
                                    {
                                        permsMask    = mask;
                                        permsGranter = granter;
                                    }
                                }
                            }
                        }
                        break;

                    case "MinEventDelay":
                        double.TryParse(part.InnerText, out minEventDelay);
                        break;
                    }
                }
            }
            catch
            {
                throw new Exception("Xstate fail decode");
            }

            int k = 0;

            stateCode = 0;
            foreach (string sn in m_ObjCode.stateNames)
            {
                if (stateName == sn)
                {
                    stateCode = k;
                    break;
                }
                k++;
            }
            eventCode = ScriptEventCode.None;
            m_Running = running;
            doGblInit = false;

            m_Item.PermsGranter = permsGranter;
            m_Item.PermsMask    = permsMask;
            m_Item.ExperienceID = experienceKey;
            m_Part.Inventory.UpdateInventoryItem(m_Item, false, false);

            lock (m_RunLock)
            {
                glblVars.iarIntegers  = ints;
                glblVars.iarFloats    = doubles;
                glblVars.iarVectors   = vectors;
                glblVars.iarRotations = rotations;
                glblVars.iarStrings   = strings;
                glblVars.iarLists     = lists;

                AddArraysHeapUse(heapsz);
                CheckRunLockInvariants(true);
            }

            lock (m_QueueLock)
            {
                m_DetectParams = null;
                foreach (EventParams evt in m_EventQueue)
                {
                    eventQueue.AddLast(evt);
                }

                m_EventQueue = eventQueue;
                for (int i = m_EventCounts.Length; --i >= 0;)
                {
                    m_EventCounts[i] = 0;
                }
                foreach (EventParams evt in m_EventQueue)
                {
                    ScriptEventCode evtCode = (ScriptEventCode)Enum.Parse(typeof(ScriptEventCode),
                                                                          evt.EventName);
                    m_EventCounts[(int)evtCode]++;
                }
            }

            AsyncCommandManager.CreateFromData(m_Engine,
                                               m_LocalID, m_ItemID, m_Part.UUID, pluginData);

            MinEventDelay = minEventDelay;
        }
Ejemplo n.º 19
0
        protected object OnGenericEvent(string FunctionName, object parameters)
        {
            if (FunctionName == "UserStatusChange")
            {
                //A user has logged in or out... we need to update friends lists across the grid

                IAsyncMessagePostService asyncPoster    = m_registry.RequestModuleInterface <IAsyncMessagePostService>();
                IFriendsService          friendsService = m_registry.RequestModuleInterface <IFriendsService>();
                ICapsService             capsService    = m_registry.RequestModuleInterface <ICapsService>();
                IGridService             gridService    = m_registry.RequestModuleInterface <IGridService>();
                if (asyncPoster != null && friendsService != null && capsService != null && gridService != null)
                {
                    //Get all friends
                    object[] info     = (object[])parameters;
                    UUID     us       = UUID.Parse(info[0].ToString());
                    bool     isOnline = bool.Parse(info[1].ToString());

                    FriendInfo[]  friends                 = friendsService.GetFriends(us);
                    List <UUID>   OnlineFriends           = new List <UUID>();
                    List <string> previouslyContactedURLs = new List <string>();
                    foreach (FriendInfo friend in friends)
                    {
                        if (friend.TheirFlags == -1 || friend.MyFlags == -1)
                        {
                            continue; //Not validiated yet!
                        }
                        UUID   FriendToInform = UUID.Zero;
                        string url, first, last, secret;
                        if (!UUID.TryParse(friend.Friend, out FriendToInform))
                        {
                            HGUtil.ParseUniversalUserIdentifier(friend.Friend, out FriendToInform, out url, out first,
                                                                out last, out secret);
                        }
                        //Now find their caps service so that we can find where they are root (and if they are logged in)
                        IClientCapsService clientCaps = capsService.GetClientCapsService(FriendToInform);
                        if (clientCaps != null)
                        {
                            //Find the root agent
                            IRegionClientCapsService regionClientCaps = clientCaps.GetRootCapsService();
                            if (regionClientCaps != null)
                            {
                                OnlineFriends.Add(FriendToInform);
                                //Post!
                                asyncPoster.Post(regionClientCaps.RegionHandle,
                                                 SyncMessageHelper.AgentStatusChange(us, FriendToInform, isOnline));
                            }
                            else
                            {
                                //If they don't have a root agent, wtf happened?
                                capsService.RemoveCAPS(clientCaps.AgentID);
                            }
                        }
                        else
                        {
                            IAgentInfoService agentInfoService = m_registry.RequestModuleInterface <IAgentInfoService>();
                            if (agentInfoService != null)
                            {
                                UserInfo friendinfo = agentInfoService.GetUserInfo(FriendToInform.ToString());
                                if (friendinfo != null && friendinfo.IsOnline)
                                {
                                    OnlineFriends.Add(FriendToInform);
                                    //Post!
                                    GridRegion r = gridService.GetRegionByUUID(UUID.Zero, friendinfo.CurrentRegionID);
                                    if (r != null)
                                    {
                                        asyncPoster.Post(r.RegionHandle,
                                                         SyncMessageHelper.AgentStatusChange(us, FriendToInform,
                                                                                             isOnline));
                                    }
                                }
                                else
                                {
                                    IUserAgentService uas = m_registry.RequestModuleInterface <IUserAgentService>();
                                    if (uas != null)
                                    {
                                        bool online = uas.RemoteStatusNotification(friend, us, isOnline);
                                        if (online)
                                        {
                                            OnlineFriends.Add(FriendToInform);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    //If the user is coming online, send all their friends online statuses to them
                    if (isOnline)
                    {
                        GridRegion ourRegion = gridService.GetRegionByUUID(UUID.Zero, UUID.Parse(info[2].ToString()));
                        if (ourRegion != null)
                        {
                            foreach (UUID onlineFriend in OnlineFriends)
                            {
                                asyncPoster.Post(ourRegion.RegionHandle,
                                                 SyncMessageHelper.AgentStatusChange(onlineFriend, us, isOnline));
                            }
                        }
                    }
                }
            }
            return(null);
        }
        public void TestLoadIarPathWithEscapedChars()
        {
            TestHelpers.InMethod();
//            log4net.Config.XmlConfigurator.Configure();

            string itemName             = "You & you are a mean/man/";
            string humanEscapedItemName = @"You & you are a mean\/man\/";
            string userPassword         = "******";

            InventoryArchiverModule archiverModule = new InventoryArchiverModule();

            Scene scene = new SceneHelpers().SetupScene();

            SceneHelpers.SetupSceneModules(scene, archiverModule);

            // Create user
            string userFirstName = "Jock";
            string userLastName  = "Stirrup";
            UUID   userId        = UUID.Parse("00000000-0000-0000-0000-000000000020");

            UserAccountHelpers.CreateUserWithInventory(scene, userFirstName, userLastName, userId, "meowfood");

            // Create asset
            SceneObjectGroup object1;
            SceneObjectPart  part1;
            {
                string             partName       = "part name";
                UUID               ownerId        = UUID.Parse("00000000-0000-0000-0000-000000000040");
                PrimitiveBaseShape shape          = PrimitiveBaseShape.CreateSphere();
                Vector3            groupPosition  = new Vector3(10, 20, 30);
                Quaternion         rotationOffset = new Quaternion(20, 30, 40, 50);
                Vector3            offsetPosition = new Vector3(5, 10, 15);

                part1
                    = new SceneObjectPart(
                          ownerId, shape, groupPosition, rotationOffset, offsetPosition);
                part1.Name = partName;

                object1 = new SceneObjectGroup(part1);
                scene.AddNewSceneObject(object1, false);
            }

            UUID      asset1Id = UUID.Parse("00000000-0000-0000-0000-000000000060");
            AssetBase asset1   = AssetHelpers.CreateAsset(asset1Id, object1);

            scene.AssetService.Store(asset1);

            // Create item
            UUID item1Id            = UUID.Parse("00000000-0000-0000-0000-000000000080");
            InventoryItemBase item1 = new InventoryItemBase();

            item1.Name    = itemName;
            item1.AssetID = asset1.FullID;
            item1.ID      = item1Id;
            InventoryFolderBase objsFolder
                = InventoryArchiveUtils.FindFoldersByPath(scene.InventoryService, userId, "Objects")[0];

            item1.Folder = objsFolder.ID;
            scene.AddInventoryItem(item1);

            MemoryStream archiveWriteStream = new MemoryStream();

            archiverModule.OnInventoryArchiveSaved += SaveCompleted;

            mre.Reset();
            archiverModule.ArchiveInventory(
                UUID.Random(), userFirstName, userLastName, "Objects", userPassword, archiveWriteStream);
            mre.WaitOne(60000, false);

            // LOAD ITEM
            MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray());

            archiverModule.DearchiveInventory(UUID.Random(), userFirstName, userLastName, "Scripts", userPassword, archiveReadStream);

            InventoryItemBase foundItem1
                = InventoryArchiveUtils.FindItemByPath(
                      scene.InventoryService, userId, "Scripts/Objects/" + humanEscapedItemName);

            Assert.That(foundItem1, Is.Not.Null, "Didn't find loaded item 1");
//            Assert.That(
//                foundItem1.CreatorId, Is.EqualTo(userUuid),
//                "Loaded item non-uuid creator doesn't match that of the loading user");
            Assert.That(
                foundItem1.Name, Is.EqualTo(itemName),
                "Loaded item name doesn't match saved name");
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Parse a UUID stem into a full UUID.
        /// </summary>
        /// <remarks>
        /// The fragment will come at the start of the UUID.  The rest will be 0s
        /// </remarks>
        /// <returns></returns>
        /// <param name='frag'>
        /// A UUID fragment that will be parsed into a full UUID.  Therefore, it can only contain
        /// cahracters which are valid in a UUID, except for "-" which is currently only allowed if a full UUID is
        /// given as the 'fragment'.
        /// </param>
        public static UUID ParseStem(string stem)
        {
            string rawUuid = stem.PadRight(32, '0');

            return(UUID.Parse(rawUuid));
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Parses add request
        /// </summary>
        /// <param name="request"></param>
        /// <param name="AgentId"></param>
        /// <param name="cap"></param>
        /// <returns></returns>
        public Hashtable ProcessAdd(Hashtable request, UUID AgentId, Caps cap)
        {
            Hashtable responsedata = new Hashtable();

            responsedata["int_response_code"]   = 400; //501; //410; //404;
            responsedata["content_type"]        = "text/plain";
            responsedata["keepalive"]           = false;
            responsedata["str_response_string"] = "Request wasn't what was expected";
            ScenePresence avatar;

            if (!m_scene.TryGetScenePresence(AgentId, out avatar))
            {
                return(responsedata);
            }

            OSDMap r = (OSDMap)OSDParser.Deserialize((string)request["requestbody"]);
            UploadObjectAssetMessage message = new UploadObjectAssetMessage();

            try
            {
                message.Deserialize(r);
            }
            catch (Exception ex)
            {
                m_log.Error("[UPLOAD OBJECT ASSET MODULE]: Error deserializing message " + ex.ToString());
                message = null;
            }

            if (message == null)
            {
                responsedata["int_response_code"]   = 400; //501; //410; //404;
                responsedata["content_type"]        = "text/plain";
                responsedata["keepalive"]           = false;
                responsedata["str_response_string"] =
                    "<llsd><map><key>error</key><string>Error parsing Object</string></map></llsd>";

                return(responsedata);
            }

            Vector3    pos     = avatar.AbsolutePosition + (Vector3.UnitX * avatar.Rotation);
            Quaternion rot     = Quaternion.Identity;
            Vector3    rootpos = Vector3.Zero;
//            Quaternion rootrot = Quaternion.Identity;

            SceneObjectGroup rootGroup = null;

            SceneObjectGroup[] allparts = new SceneObjectGroup[message.Objects.Length];
            for (int i = 0; i < message.Objects.Length; i++)
            {
                UploadObjectAssetMessage.Object obj = message.Objects[i];
                PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox();

                if (i == 0)
                {
                    rootpos = obj.Position;
//                    rootrot = obj.Rotation;
                }

                // Combine the extraparams data into it's ugly blob again....
                //int bytelength = 0;
                //for (int extparams = 0; extparams < obj.ExtraParams.Length; extparams++)
                //{
                //    bytelength += obj.ExtraParams[extparams].ExtraParamData.Length;
                //}
                //byte[] extraparams = new byte[bytelength];
                //int position = 0;



                //for (int extparams = 0; extparams < obj.ExtraParams.Length; extparams++)
                //{
                //    Buffer.BlockCopy(obj.ExtraParams[extparams].ExtraParamData, 0, extraparams, position,
                //                     obj.ExtraParams[extparams].ExtraParamData.Length);
                //
                //    position += obj.ExtraParams[extparams].ExtraParamData.Length;
                // }

                //pbs.ExtraParams = extraparams;
                for (int extparams = 0; extparams < obj.ExtraParams.Length; extparams++)
                {
                    UploadObjectAssetMessage.Object.ExtraParam extraParam = obj.ExtraParams[extparams];
                    switch ((ushort)extraParam.Type)
                    {
                    case (ushort)ExtraParamType.Sculpt:
                        Primitive.SculptData sculpt = new Primitive.SculptData(extraParam.ExtraParamData, 0);

                        pbs.SculptEntry = true;

                        pbs.SculptTexture = obj.SculptID;
                        pbs.SculptType    = (byte)sculpt.Type;

                        break;

                    case (ushort)ExtraParamType.Flexible:
                        Primitive.FlexibleData flex = new Primitive.FlexibleData(extraParam.ExtraParamData, 0);
                        pbs.FlexiEntry    = true;
                        pbs.FlexiDrag     = flex.Drag;
                        pbs.FlexiForceX   = flex.Force.X;
                        pbs.FlexiForceY   = flex.Force.Y;
                        pbs.FlexiForceZ   = flex.Force.Z;
                        pbs.FlexiGravity  = flex.Gravity;
                        pbs.FlexiSoftness = flex.Softness;
                        pbs.FlexiTension  = flex.Tension;
                        pbs.FlexiWind     = flex.Wind;
                        break;

                    case (ushort)ExtraParamType.Light:
                        Primitive.LightData light = new Primitive.LightData(extraParam.ExtraParamData, 0);
                        pbs.LightColorA    = light.Color.A;
                        pbs.LightColorB    = light.Color.B;
                        pbs.LightColorG    = light.Color.G;
                        pbs.LightColorR    = light.Color.R;
                        pbs.LightCutoff    = light.Cutoff;
                        pbs.LightEntry     = true;
                        pbs.LightFalloff   = light.Falloff;
                        pbs.LightIntensity = light.Intensity;
                        pbs.LightRadius    = light.Radius;
                        break;

                    case 0x40:
                        pbs.ReadProjectionData(extraParam.ExtraParamData, 0);
                        break;
                    }
                }

                pbs.PathBegin        = (ushort)obj.PathBegin;
                pbs.PathCurve        = (byte)obj.PathCurve;
                pbs.PathEnd          = (ushort)obj.PathEnd;
                pbs.PathRadiusOffset = (sbyte)obj.RadiusOffset;
                pbs.PathRevolutions  = (byte)obj.Revolutions;
                pbs.PathScaleX       = (byte)obj.ScaleX;
                pbs.PathScaleY       = (byte)obj.ScaleY;
                pbs.PathShearX       = (byte)obj.ShearX;
                pbs.PathShearY       = (byte)obj.ShearY;
                pbs.PathSkew         = (sbyte)obj.Skew;
                pbs.PathTaperX       = (sbyte)obj.TaperX;
                pbs.PathTaperY       = (sbyte)obj.TaperY;
                pbs.PathTwist        = (sbyte)obj.Twist;
                pbs.PathTwistBegin   = (sbyte)obj.TwistBegin;
                pbs.HollowShape      = (HollowShape)obj.ProfileHollow;
                pbs.PCode            = (byte)PCode.Prim;
                pbs.ProfileBegin     = (ushort)obj.ProfileBegin;
                pbs.ProfileCurve     = (byte)obj.ProfileCurve;
                pbs.ProfileEnd       = (ushort)obj.ProfileEnd;
                pbs.Scale            = obj.Scale;
                pbs.State            = (byte)0;
                pbs.LastAttachPoint  = (byte)0;
                SceneObjectPart prim = new SceneObjectPart();
                prim.UUID         = UUID.Random();
                prim.CreatorID    = AgentId;
                prim.OwnerID      = AgentId;
                prim.GroupID      = obj.GroupID;
                prim.LastOwnerID  = prim.OwnerID;
                prim.RezzerID     = AgentId;
                prim.CreationDate = Util.UnixTimeSinceEpoch();
                prim.Name         = obj.Name;
                prim.Description  = "";

                prim.PayPrice[0] = -2;
                prim.PayPrice[1] = -2;
                prim.PayPrice[2] = -2;
                prim.PayPrice[3] = -2;
                prim.PayPrice[4] = -2;
                Primitive.TextureEntry tmp =
                    new Primitive.TextureEntry(UUID.Parse("89556747-24cb-43ed-920b-47caed15465f"));

                for (int j = 0; j < obj.Faces.Length; j++)
                {
                    UploadObjectAssetMessage.Object.Face face = obj.Faces[j];

                    Primitive.TextureEntryFace primFace = tmp.CreateFace((uint)j);

                    primFace.Bump       = face.Bump;
                    primFace.RGBA       = face.Color;
                    primFace.Fullbright = face.Fullbright;
                    primFace.Glow       = face.Glow;
                    primFace.TextureID  = face.ImageID;
                    primFace.Rotation   = face.ImageRot;
                    primFace.MediaFlags = ((face.MediaFlags & 1) != 0);

                    primFace.OffsetU    = face.OffsetS;
                    primFace.OffsetV    = face.OffsetT;
                    primFace.RepeatU    = face.ScaleS;
                    primFace.RepeatV    = face.ScaleT;
                    primFace.TexMapType = (MappingType)(face.MediaFlags & 6);
                }

                pbs.TextureEntry = tmp.GetBytes();
                prim.Shape       = pbs;
                prim.Scale       = obj.Scale;

                SceneObjectGroup grp = new SceneObjectGroup();

                grp.SetRootPart(prim);
                prim.ParentID = 0;
                if (i == 0)
                {
                    rootGroup = grp;
                }
                grp.AttachToScene(m_scene);
                grp.AbsolutePosition = obj.Position;
                prim.RotationOffset  = obj.Rotation;

                // Required for linking
                grp.RootPart.ClearUpdateSchedule();

                if (m_scene.Permissions.CanRezObject(1, avatar.UUID, pos))
                {
                    m_scene.AddSceneObject(grp);
                    grp.AbsolutePosition = obj.Position;
                }

                allparts[i] = grp;
            }

            for (int j = 1; j < allparts.Length; j++)
            {
                // Required for linking
                rootGroup.RootPart.ClearUpdateSchedule();
                allparts[j].RootPart.ClearUpdateSchedule();
                rootGroup.LinkToGroup(allparts[j]);
            }

            rootGroup.ScheduleGroupForFullUpdate();
            pos
                = m_scene.GetNewRezLocation(
                      Vector3.Zero, rootpos, UUID.Zero, rot, (byte)1, 1, true, allparts[0].GroupScale, false);

            responsedata["int_response_code"]   = 200; //501; //410; //404;
            responsedata["content_type"]        = "text/plain";
            responsedata["keepalive"]           = false;
            responsedata["str_response_string"] = String.Format("<llsd><map><key>local_id</key>{0}</map></llsd>", ConvertUintToBytes(allparts[0].LocalId));

            return(responsedata);
        }
Ejemplo n.º 23
0
        private bool IsLocal(UserInfo u, IScenePresence presence)
        {
#if (!ISWIN)
            foreach (IScene scene in presence.Scene.RequestModuleInterface <SceneManager>().Scenes)
            {
                if (scene.GetScenePresence(UUID.Parse(u.UserID)) != null)
                {
                    return(true);
                }
            }
            return(false);
#else
            return(presence.Scene.RequestModuleInterface <SceneManager>().Scenes.Any(scene => scene.GetScenePresence(UUID.Parse(u.UserID)) != null));
#endif
        }
        /// <summary>
        /// Create a Group, including Everyone and Owners Role, place FounderID in both groups, select Owner as selected role, and newly created group as agent's active role.
        /// </summary>
        public UUID CreateGroup(UUID requestingAgentID, string name, string charter, bool showInList, UUID insigniaID,
                                int membershipFee, bool openEnrollment, bool allowPublish,
                                bool maturePublish, UUID founderID)
        {
            UUID GroupID     = UUID.Random();
            UUID OwnerRoleID = UUID.Random();

            Hashtable param = new Hashtable();

            param["GroupID"]        = GroupID.ToString();
            param["Name"]           = name;
            param["Charter"]        = charter;
            param["ShowInList"]     = showInList == true ? 1 : 0;
            param["InsigniaID"]     = insigniaID.ToString();
            param["MembershipFee"]  = 0;
            param["OpenEnrollment"] = openEnrollment == true ? 1 : 0;
            param["AllowPublish"]   = allowPublish == true ? 1 : 0;
            param["MaturePublish"]  = maturePublish == true ? 1 : 0;
            param["FounderID"]      = founderID.ToString();
            param["EveryonePowers"] = ((ulong)m_DefaultEveryonePowers).ToString();
            param["OwnerRoleID"]    = OwnerRoleID.ToString();

            // Would this be cleaner as (GroupPowers)ulong.MaxValue;
            GroupPowers OwnerPowers = GroupPowers.Accountable
                                      | GroupPowers.AllowEditLand
                                      | GroupPowers.AllowFly
                                      | GroupPowers.AllowLandmark
                                      | GroupPowers.AllowRez
                                      | GroupPowers.AllowSetHome
                                      | GroupPowers.AllowVoiceChat
                                      | GroupPowers.AssignMember
                                      | GroupPowers.AssignMemberLimited
                                      | GroupPowers.ChangeActions
                                      | GroupPowers.ChangeIdentity
                                      | GroupPowers.ChangeMedia
                                      | GroupPowers.ChangeOptions
                                      | GroupPowers.CreateRole
                                      | GroupPowers.DeedObject
                                      | GroupPowers.DeleteRole
                                      | GroupPowers.Eject
                                      | GroupPowers.FindPlaces
                                      | GroupPowers.Invite
                                      | GroupPowers.JoinChat
                                      | GroupPowers.LandChangeIdentity
                                      | GroupPowers.LandDeed
                                      | GroupPowers.LandDivideJoin
                                      | GroupPowers.LandEdit
                                      | GroupPowers.LandEjectAndFreeze
                                      | GroupPowers.LandGardening
                                      | GroupPowers.LandManageAllowed
                                      | GroupPowers.LandManageBanned
                                      | GroupPowers.LandManagePasses
                                      | GroupPowers.LandOptions
                                      | GroupPowers.LandRelease
                                      | GroupPowers.LandSetSale
                                      | GroupPowers.ModerateChat
                                      | GroupPowers.ObjectManipulate
                                      | GroupPowers.ObjectSetForSale
                                      | GroupPowers.ReceiveNotices
                                      | GroupPowers.RemoveMember
                                      | GroupPowers.ReturnGroupOwned
                                      | GroupPowers.ReturnGroupSet
                                      | GroupPowers.ReturnNonGroup
                                      | GroupPowers.RoleProperties
                                      | GroupPowers.SendNotices
                                      | GroupPowers.SetLandingPoint
                                      | GroupPowers.StartProposal
                                      | GroupPowers.VoteOnProposal;

            param["OwnersPowers"] = ((ulong)OwnerPowers).ToString();



            Hashtable respData = XmlRpcCall(requestingAgentID, "groups.createGroup", param);

            if (respData.Contains("error"))
            {
                // UUID is not nullable

                return(UUID.Zero);
            }

            return(UUID.Parse((string)respData["GroupID"]));
        }
Ejemplo n.º 25
0
        public void TestDeleteSceneObjectAsyncToUserInventory()
        {
            TestHelpers.InMethod();
//            TestHelpers.EnableLogging();

            UUID   agentId      = UUID.Parse("00000000-0000-0000-0000-000000000001");
            string myObjectName = "Fred";

            TestScene scene = new SceneHelpers().SetupScene();

            IConfigSource configSource = new IniConfigSource();
            IConfig       config       = configSource.AddConfig("Modules");

            config.Set("InventoryAccessModule", "BasicInventoryAccessModule");
            SceneHelpers.SetupSceneModules(
                scene, configSource, new object[] { new BasicInventoryAccessModule() });

            SceneHelpers.SetupSceneModules(scene, new object[] { });

            // Turn off the timer on the async sog deleter - we'll crank it by hand for this test.
            AsyncSceneObjectGroupDeleter sogd = scene.SceneObjectGroupDeleter;

            sogd.Enabled = false;

            SceneObjectGroup so = SceneHelpers.AddSceneObject(scene, myObjectName, agentId);

            UserAccount         ua = UserAccountHelpers.CreateUserWithInventory(scene, agentId);
            InventoryFolderBase folder1
                = UserInventoryHelpers.CreateInventoryFolder(scene.InventoryService, ua.PrincipalID, "folder1", false);

            IClientAPI client = SceneHelpers.AddScenePresence(scene, agentId).ControllingClient;

            scene.DeRezObjects(client, new List <uint>()
            {
                so.LocalId
            }, UUID.Zero, DeRezAction.Take, folder1.ID);

            SceneObjectPart retrievedPart = scene.GetSceneObjectPart(so.LocalId);

            Assert.That(retrievedPart, Is.Not.Null);
            Assert.That(so.IsDeleted, Is.False);

            sogd.InventoryDeQueueAndDelete();

            Assert.That(so.IsDeleted, Is.True);

            SceneObjectPart retrievedPart2 = scene.GetSceneObjectPart(so.LocalId);

            Assert.That(retrievedPart2, Is.Null);

//            SceneSetupHelpers.DeleteSceneObjectAsync(scene, part, DeRezAction.Take, userInfo.RootFolder.ID, client);

            InventoryItemBase retrievedItem
                = UserInventoryHelpers.GetInventoryItem(
                      scene.InventoryService, ua.PrincipalID, "folder1/" + myObjectName);

            // Check that we now have the taken part in our inventory
            Assert.That(retrievedItem, Is.Not.Null);

            // Check that the taken part has actually disappeared
//            SceneObjectPart retrievedPart = scene.GetSceneObjectPart(part.LocalId);
//            Assert.That(retrievedPart, Is.Null);
        }
Ejemplo n.º 26
0
        protected void DoAgentPost(Hashtable request, Hashtable responsedata, UUID id)
        {
            OSDMap args = Utils.GetOSDMap((string)request["body"]);

            if (args == null)
            {
                responsedata["int_response_code"]   = HttpStatusCode.BadRequest;
                responsedata["str_response_string"] = "Bad request";
                return;
            }

            AgentDestinationData data = CreateAgentDestinationData();

            UnpackData(args, data, request);

            GridRegion destination = new GridRegion();

            destination.RegionID   = data.uuid;
            destination.RegionLocX = data.x;
            destination.RegionLocY = data.y;
            destination.RegionName = data.name;

            GridRegion gatekeeper = ExtractGatekeeper(data);

            AgentCircuitData aCircuit = new AgentCircuitData();

            try
            {
                aCircuit.UnpackAgentCircuitData(args);
            }
            catch (Exception ex)
            {
                m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildCreate message {0}", ex.Message);
                responsedata["int_response_code"]   = HttpStatusCode.BadRequest;
                responsedata["str_response_string"] = "Bad request";
                return;
            }

            GridRegion source = null;

            if (args.ContainsKey("source_uuid"))
            {
                source            = new GridRegion();
                source.RegionLocX = Int32.Parse(args["source_x"].AsString());
                source.RegionLocY = Int32.Parse(args["source_y"].AsString());
                source.RegionName = args["source_name"].AsString();
                source.RegionID   = UUID.Parse(args["source_uuid"].AsString());

                if (args.ContainsKey("source_server_uri"))
                {
                    source.RawServerURI = args["source_server_uri"].AsString();
                }
                else
                {
                    source.RawServerURI = null;
                }
            }

            OSDMap resp   = new OSDMap(2);
            string reason = String.Empty;

            // This is the meaning of POST agent
            //m_regionClient.AdjustUserInformation(aCircuit);
            //bool result = m_SimulationService.CreateAgent(destination, aCircuit, teleportFlags, out reason);
            bool result = CreateAgent(source, gatekeeper, destination, aCircuit, data.flags, data.fromLogin, out reason);

            resp["reason"]  = OSD.FromString(reason);
            resp["success"] = OSD.FromBoolean(result);
            // Let's also send out the IP address of the caller back to the caller (HG 1.5)
            resp["your_ip"] = OSD.FromString(GetCallerIP(request));

            // TODO: add reason if not String.Empty?
            responsedata["int_response_code"]   = HttpStatusCode.OK;
            responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp);
        }
Ejemplo n.º 27
0
        OSDMap GetFriends(OSDMap map)
        {
            OSDMap resp = new OSDMap();

            if (map.ContainsKey("UserID") == false)
            {
                resp ["Failed"] = OSD.FromString("User ID not specified.");
                return(resp);
            }

            IFriendsService friendService = m_registry.RequestModuleInterface <IFriendsService> ();

            if (friendService == null)
            {
                resp ["Failed"] = OSD.FromString("No friend service found.");
                return(resp);
            }

            List <FriendInfo> friendsList = friendService.GetFriends(map ["UserID"].AsUUID());
            OSDArray          friends     = new OSDArray(friendsList.Count);

            foreach (FriendInfo friendInfo in friendsList)
            {
                UserAccount userAcct = m_registry.RequestModuleInterface <IUserAccountService> ().GetUserAccount(null, UUID.Parse(friendInfo.Friend));
                OSDMap      friend   = new OSDMap(4);
                friend ["PrincipalID"] = friendInfo.Friend;
                friend ["Name"]        = userAcct.Name;
                friend ["MyFlags"]     = friendInfo.MyFlags;
                friend ["TheirFlags"]  = friendInfo.TheirFlags;
                friends.Add(friend);
            }

            resp ["Friends"] = friends;
            friendsList.Clear();

            return(resp);
        }
        public void TestLoadOar()
        {
            TestHelpers.InMethod();
            //            log4net.Config.XmlConfigurator.Configure();

            MemoryStream     archiveWriteStream = new MemoryStream();
            TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream);

            // Put in a random blank directory to check that this doesn't upset the load process
            tar.WriteDir("ignoreme");

            // Also check that direct entries which will also have a file entry containing that directory doesn't
            // upset load
            tar.WriteDir(ArchiveConstants.TERRAINS_PATH);

            tar.WriteFile(
                ArchiveConstants.CONTROL_FILE_PATH,
                new ArchiveWriteRequest(m_scene, (Stream)null, Guid.Empty).CreateControlFile(new ArchiveScenesGroup()));
            SceneObjectPart part1 = CreateSceneObjectPart1();

            part1.SitTargetOrientation = new Quaternion(0.2f, 0.3f, 0.4f, 0.5f);
            part1.SitTargetPosition    = new Vector3(1, 2, 3);

            SceneObjectGroup object1 = new SceneObjectGroup(part1);

            // Let's put some inventory items into our object
            string   soundItemName         = "sound-item1";
            UUID     soundItemUuid         = UUID.Parse("00000000-0000-0000-0000-000000000002");
            Type     type                  = GetType();
            Assembly assembly              = type.Assembly;
            string   soundDataResourceName = null;

            string[] names = assembly.GetManifestResourceNames();
            foreach (string name in names)
            {
                if (name.EndsWith(".Resources.test-sound.wav"))
                {
                    soundDataResourceName = name;
                }
            }
            Assert.That(soundDataResourceName, Is.Not.Null);

            byte[] soundData;
            UUID   soundUuid;

            CreateSoundAsset(tar, assembly, soundDataResourceName, out soundData, out soundUuid);

            TaskInventoryItem item1
                = new TaskInventoryItem {
                AssetID = soundUuid, ItemID = soundItemUuid, Name = soundItemName
                };

            part1.Inventory.AddInventoryItem(item1, true);
            m_scene.AddNewSceneObject(object1, false);

            string object1FileName = string.Format(
                "{0}_{1:000}-{2:000}-{3:000}__{4}.xml",
                part1.Name,
                Math.Round(part1.GroupPosition.X), Math.Round(part1.GroupPosition.Y), Math.Round(part1.GroupPosition.Z),
                part1.UUID);

            tar.WriteFile(ArchiveConstants.OBJECTS_PATH + object1FileName, SceneObjectSerializer.ToXml2Format(object1));

            tar.Close();

            MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray());

            lock (this)
            {
                m_scene.EventManager.OnOarFileLoaded += LoadCompleted;
                m_archiverModule.DearchiveRegion(archiveReadStream);
            }

            Assert.That(m_lastErrorMessage, Is.Null);

            TestLoadedRegion(part1, soundItemName, soundData);
        }
Ejemplo n.º 29
0
        public Dictionary <string, object> Fill(WebInterface webInterface, string filename, OSHttpRequest httpRequest,
                                                OSHttpResponse httpResponse, Dictionary <string, object> requestParameters,
                                                ITranslator translator, out string response)
        {
            response = null;
            var vars            = new Dictionary <string, object> ();
            var estateConnector = Framework.Utilities.DataManager.RequestPlugin <IEstateConnector> ();
            var user            = Authenticator.GetAuthentication(httpRequest);

            string estate;

            if (httpRequest.Query.ContainsKey("EstateID"))
            {
                estate = httpRequest.Query ["EstateID"].ToString();
            }
            else
            {
                if (requestParameters.ContainsKey("EstateID"))
                {
                    estate = requestParameters ["EstateID"].ToString();
                }
                else
                {
                    response = "<h3>Estate details not supplied, redirecting to main page</h3>" +
                               "<script>" +
                               "setTimeout(function() {window.location.href = \"/?page=user_estatemanager\";}, 5000);" +
                               "</script>";
                    return(null);
                }
            }

            var estateid = -1;

            int.TryParse(estate, out estateid);

            if (requestParameters.ContainsKey("Delete"))
            {
                response = "<h3>This estate would have been deleted... but not yet</h3>";
                return(null);
            }

            var estateSettings = estateConnector.GetEstateIDSettings(estateid);

            if (estateSettings != null)
            {
                if (requestParameters.ContainsKey("Submit"))
                {
                    var estateOwner = requestParameters ["EstateOwner"].ToString();

                    estateSettings.EstateName          = requestParameters ["EstateName"].ToString();
                    estateSettings.EstateOwner         = UUID.Parse(estateOwner);
                    estateSettings.PricePerMeter       = int.Parse(requestParameters ["PricePerMeter"].ToString());
                    estateSettings.PublicAccess        = requestParameters ["PublicAccess"].ToString() == "1";
                    estateSettings.TaxFree             = requestParameters ["TaxFree"].ToString() == "1";
                    estateSettings.AllowVoice          = requestParameters ["AllowVoice"].ToString() == "1";
                    estateSettings.AllowDirectTeleport = requestParameters ["AllowDirectTeleport"].ToString() == "1";

                    estateConnector.SaveEstateSettings(estateSettings);

                    response = "Estate details have been updated." +
                               "<script>" +
                               "setTimeout(function() {window.location.href = \"/?page=user_estatemanager\";}, 5000);" +
                               "</script>";

                    return(null);
                }

                // get selected estate details
                if (estateSettings != null)
                {
                    vars.Add("EstateID", estateSettings.EstateID.ToString());
                    vars.Add("EstateName", estateSettings.EstateName);
                    vars.Add("PricePerMeter", estateSettings.PricePerMeter.ToString());
                    vars.Add("PublicAccess", WebHelpers.YesNoSelection(translator, estateSettings.PublicAccess));
                    vars.Add("AllowVoice", WebHelpers.YesNoSelection(translator, estateSettings.AllowVoice));
                    vars.Add("TaxFree", WebHelpers.YesNoSelection(translator, estateSettings.TaxFree));
                    vars.Add("AllowDirectTeleport", WebHelpers.YesNoSelection(translator, estateSettings.AllowDirectTeleport));

                    vars.Add("Submit", translator.GetTranslatedString("SaveUpdates"));
                }
            }

            // labels
            vars.Add("UserName", user.Name);
            vars.Add("EstateManagerText", translator.GetTranslatedString("MenuEstateManager"));
            vars.Add("EstateNameText", translator.GetTranslatedString("EstateText"));
            vars.Add("EstateOwnerText", translator.GetTranslatedString("MenuOwnerTitle"));
            vars.Add("PricePerMeterText", translator.GetTranslatedString("PricePerMeterText"));
            vars.Add("PublicAccessText", translator.GetTranslatedString("PublicAccessText"));
            vars.Add("AllowVoiceText", translator.GetTranslatedString("AllowVoiceText"));
            vars.Add("TaxFreeText", translator.GetTranslatedString("TaxFreeText"));
            vars.Add("AllowDirectTeleportText", translator.GetTranslatedString("AllowDirectTeleportText"));
            vars.Add("Cancel", translator.GetTranslatedString("Cancel"));
            vars.Add("InfoMessage", "");

            return(vars);
        }
Ejemplo n.º 30
0
 public override void FromKVP(Dictionary <string, object> values)
 {
     UUID     = UUID.Parse(values["UUID"].ToString());
     Name     = values["Name"].ToString();
     Selected = bool.Parse(values["Selected"].ToString());
 }