public bool Charge(UUID agentID, int amount, string text, int daysUntilNextCharge)
        {
            IMoneyModule moneyModule = m_registry.RequestModuleInterface<IMoneyModule>();
            if (moneyModule != null)
            {
                bool success = moneyModule.Charge(agentID, amount, text);
                if (!success)
                    return false;
                IScheduleService scheduler = m_registry.RequestModuleInterface<IScheduleService>();
                if (scheduler != null)
                {
                    OSDMap itemInfo = new OSDMap();
                    itemInfo.Add("AgentID", agentID);
                    itemInfo.Add("Amount", amount);
                    itemInfo.Add("Text", text);
                    SchedulerItem item = new SchedulerItem("ScheduledPayment",
                        OSDParser.SerializeJsonString(itemInfo), false,
                        DateTime.Now.AddDays(daysUntilNextCharge) - DateTime.Now);
                    itemInfo.Add("SchedulerID", item.id);
                    scheduler.Save(item);

                }
            }
            return true;
        }
 public bool Charge(UUID agentID, int amount, string text, int daysUntilNextCharge, TransactionType type, string identifer, bool chargeImmediately)
 {
     IMoneyModule moneyModule = m_registry.RequestModuleInterface<IMoneyModule>();
     if (moneyModule != null)
     {
         if (chargeImmediately)
         {
             bool success = moneyModule.Charge(agentID, amount, text, type);
             if (!success)
                 return false;
         }
         IScheduleService scheduler = m_registry.RequestModuleInterface<IScheduleService>();
         if (scheduler != null)
         {
             OSDMap itemInfo = new OSDMap();
             itemInfo.Add("AgentID", agentID);
             itemInfo.Add("Amount", amount);
             itemInfo.Add("Text", text);
             itemInfo.Add("Type", (int)type);
             SchedulerItem item = new SchedulerItem("ScheduledPayment " + identifer,
                                                    OSDParser.SerializeJsonString(itemInfo), false,
                                                    DateTime.UtcNow, daysUntilNextCharge, RepeatType.days, agentID);
             itemInfo.Add("SchedulerID", item.id);
             scheduler.Save(item);
         }
     }
     return true;
 }
示例#3
1
 public static OSD DeserializeJson(JsonData json)
 {
     switch (json.GetJsonType())
     {
         case JsonType.Boolean:
             return OSD.FromBoolean((bool)json);
         case JsonType.Int:
             return OSD.FromInteger((int)json);
         case JsonType.Long:
             return OSD.FromLong((long)json);
         case JsonType.Double:
             return OSD.FromReal((double)json);
         case JsonType.String:
             string str = (string)json;
             if (String.IsNullOrEmpty(str))
                 return new OSD();
             else
                 return OSD.FromString(str);
         case JsonType.Array:
             OSDArray array = new OSDArray(json.Count);
             for (int i = 0; i < json.Count; i++)
                 array.Add(DeserializeJson(json[i]));
             return array;
         case JsonType.Object:
             OSDMap map = new OSDMap(json.Count);
             foreach (KeyValuePair<string, JsonData> kvp in json)
                 map.Add(kvp.Key, DeserializeJson(kvp.Value));
             return map;
         case JsonType.None:
         default:
             return new OSD();
     }
 }
        /// <summary>
        /// Sends json-rpc request with a serializable type.
        /// </summary>
        /// <returns>
        /// OSD Map.
        /// </returns>
        /// <param name='parameters'>
        /// Serializable type .
        /// </param>
        /// <param name='method'>
        /// Json-rpc method to call.
        /// </param>
        /// <param name='uri'>
        /// URI of json-rpc service.
        /// </param>
        /// <param name='jsonId'>
        /// Id for our call.
        /// </param>
        public bool JsonRpcRequest(ref object parameters, string method, string uri, string jsonId)
        {
            if (jsonId == null)
                throw new ArgumentNullException ("jsonId");
            if (uri == null)
                throw new ArgumentNullException ("uri");
            if (method == null)
                throw new ArgumentNullException ("method");
            if (parameters == null)
                throw new ArgumentNullException ("parameters");
            
            // Prep our payload
            OSDMap json = new OSDMap();
            
            json.Add("jsonrpc", OSD.FromString("2.0"));
            json.Add("id", OSD.FromString(jsonId));
            json.Add("method", OSD.FromString(method));
            
            json.Add("params", OSD.SerializeMembers(parameters));
            
            string jsonRequestData = OSDParser.SerializeJsonString(json);
            byte[] content = Encoding.UTF8.GetBytes(jsonRequestData);
            
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
            
            webRequest.ContentType = "application/json-rpc";
            webRequest.Method = "POST";
            
            //Stream dataStream = webRequest.GetRequestStream();
            //dataStream.Write(content, 0, content.Length);
            //dataStream.Close();

            using (Stream dataStream = webRequest.GetRequestStream())
                dataStream.Write(content, 0, content.Length);
            
            WebResponse webResponse = null;
            try
            {
                webResponse = webRequest.GetResponse();
            }
            catch (WebException e)
            {
                Console.WriteLine("Web Error" + e.Message);
                Console.WriteLine ("Please check input");
                return false;
            }
            
            using (webResponse)
            using (Stream rstream = webResponse.GetResponseStream())
            {
                OSDMap mret = (OSDMap)OSDParser.DeserializeJson(rstream);
                        
                if (mret.ContainsKey("error"))
                    return false;
            
                // get params...
                OSD.DeserializeMembers(ref parameters, (OSDMap)mret["result"]);
                return true;
            }
        }
示例#5
0
 public override OSDMap ToOSD()
 {
     OSDMap map = new OSDMap();
     map.Add("MuteName", MuteName);
     map.Add("MuteID", MuteID);
     map.Add("MuteType", MuteType);
     return map;
 }
//        private static byte[] uintToByteArray(uint uIntValue)
//        {
//            byte[] result = new byte[4];
//            Utils.UIntToBytesBig(uIntValue, result, 0);
//            return result;
//        }

        public static OSD BuildEvent(string eventName, OSD eventBody)
        {
            OSDMap llsdEvent = new OSDMap(2);
            llsdEvent.Add("message", new OSDString(eventName));
            llsdEvent.Add("body", eventBody);

            return llsdEvent;
        }
        /// <summary>
        /// Sends json-rpc request with a serializable type.
        /// </summary>
        /// <returns>
        /// OSD Map.
        /// </returns>
        /// <param name='parameters'>
        /// Serializable type .
        /// </param>
        /// <param name='method'>
        /// Json-rpc method to call.
        /// </param>
        /// <param name='uri'>
        /// URI of json-rpc service.
        /// </param>
        /// <param name='jsonId'>
        /// Id for our call.
        /// </param>
        public bool JsonRpcRequest(ref object parameters, string method, string uri, string jsonId)
        {
            if (jsonId == null)
                throw new ArgumentNullException("jsonId");
            if (uri == null)
                throw new ArgumentNullException("uri");
            if (method == null)
                throw new ArgumentNullException("method");
            if (parameters == null)
                throw new ArgumentNullException("parameters");

            OSDMap request = new OSDMap();
            request.Add("jsonrpc", OSD.FromString("2.0"));
            request.Add("id", OSD.FromString(jsonId));
            request.Add("method", OSD.FromString(method));
            request.Add("params", OSD.SerializeMembers(parameters));

            OSDMap response;
            try
            {
                response = WebUtil.PostToService(uri, request, 10000, true);
            }
            catch (Exception e)
            {
                m_log.Debug(string.Format("JsonRpc request '{0}' failed", method), e);
                return false;
            }

            if (!response.ContainsKey("_Result"))
            {
                m_log.DebugFormat("JsonRpc request '{0}' returned an invalid response: {1}",
                    method, OSDParser.SerializeJsonString(response));
                return false;
            }
            response = (OSDMap)response["_Result"];

            OSD data;

            if (response.ContainsKey("error"))
            {
                data = response["error"];
                m_log.DebugFormat("JsonRpc request '{0}' returned an error: {1}",
                    method, OSDParser.SerializeJsonString(data));
                return false;
            }

            if (!response.ContainsKey("result"))
            {
                m_log.DebugFormat("JsonRpc request '{0}' returned an invalid response: {1}",
                    method, OSDParser.SerializeJsonString(response));
                return false;
            }

            data = response["result"];
            OSD.DeserializeMembers(ref parameters, (OSDMap)data);

            return true;
        }
示例#8
0
        public static OSDMap UpdateEstateInfo(uint EstateID, UUID RegionID)
        {
            OSDMap llsdBody = new OSDMap();

            llsdBody.Add("EstateID", EstateID);
            llsdBody.Add("RegionID", RegionID);

            return buildEvent("UpdateEstateInfo", llsdBody, UUID.Zero, 0);
        }
示例#9
0
        public static OSDMap ArrivedAtDestination(UUID AgentID, int DrawDistance, AgentCircuitData circuit, ulong requestingRegion)
        {
            OSDMap llsdBody = new OSDMap();

            llsdBody.Add("AgentID", AgentID);

            llsdBody.Add("DrawDistance", DrawDistance);
            llsdBody.Add("Circuit", circuit.PackAgentCircuitData());

            return buildEvent("ArrivedAtDestination", llsdBody, AgentID, requestingRegion);
        }
示例#10
0
        /// <summary>
        /// Tells the region to tell the given agent that the other agent is online
        /// </summary>
        /// <param name="AgentID">Agent that is either logging in or logging out</param>
        /// <param name="FriendToInformID">Friend that will be told of the incoming/outgoing user</param>
        /// <param name="newStatus">Whether they are logged in or out</param>
        /// <returns></returns>
        public static OSDMap AgentStatusChange(UUID AgentID, UUID FriendToInformID, bool newStatus)
        {
            OSDMap llsdBody = new OSDMap();

            llsdBody.Add("AgentID", AgentID);

            llsdBody.Add("FriendToInformID", FriendToInformID);
            llsdBody.Add("NewStatus", newStatus);

            return buildEvent("AgentStatusChange", llsdBody, AgentID, 0);
        }
示例#11
0
		public void SerializeMapTest() {
			OSDMap capsMap = new OSDMap();
			capsMap.Add("FetchInventoryDescendents2", "d5cb3302-2db8-4881-94de-161ce09df1a6");
			capsMap.Add("FetchInventory2", "e1563faf-a081-4410-b160-ea1639aef192");
			capsMap.Add("GetTexture", "26cecb27-ea2c-4152-b319-d06dd0b516ae");
			capsMap.Add("GetMesh", "24f57f22-59b0-4c4a-a2c2-95a8858de972");

			String result = OSDParser.SerializeJsonString(capsMap);
			String jsonString = "{\"FetchInventoryDescendents2\":\"d5cb3302-2db8-4881-94de-161ce09df1a6\",\"FetchInventory2\":\"e1563faf-a081-4410-b160-ea1639aef192\",\"GetTexture\":\"26cecb27-ea2c-4152-b319-d06dd0b516ae\",\"GetMesh\":\"24f57f22-59b0-4c4a-a2c2-95a8858de972\"}";
			Assert.That(jsonString.Equals(result));

		}
示例#12
0
        public static OSDMap EnableSimulator(ulong regionHandle, IPAddress ip, int port)
        {
            OSDMap llsdSimInfo = new OSDMap(3);

            llsdSimInfo.Add("Handle", OSD.FromULong(regionHandle));
            llsdSimInfo.Add("IP", OSD.FromBinary(ip.GetAddressBytes()));
            llsdSimInfo.Add("Port", OSD.FromInteger(port));

            OSDArray arr = new OSDArray(1);
            arr.Add(llsdSimInfo);

            OSDMap llsdBody = new OSDMap(1);
            llsdBody.Add("SimulatorInfo", arr);

            return llsdBody;
        }
示例#13
0
        public static OSD EnableSimulator(ulong handle, IPEndPoint endPoint)
        {
            OSDMap llsdSimInfo = new OSDMap(3);

            llsdSimInfo.Add("Handle", new OSDBinary(ulongToByteArray(handle)));
            llsdSimInfo.Add("IP", new OSDBinary(endPoint.Address.GetAddressBytes()));
            llsdSimInfo.Add("Port", new OSDInteger(endPoint.Port));

            OSDArray arr = new OSDArray(1);
            arr.Add(llsdSimInfo);

            OSDMap llsdBody = new OSDMap(1);
            llsdBody.Add("SimulatorInfo", arr);

            return BuildEvent("EnableSimulator", llsdBody);
        }
示例#14
0
        public static OSD EnableSimulator(ulong handle, byte[] IPAddress, int Port)
        {
            OSDMap llsdSimInfo = new OSDMap(3);

            llsdSimInfo.Add("Handle", new OSDBinary(ulongToByteArray(handle)));
            llsdSimInfo.Add("IP", new OSDBinary(IPAddress));
            llsdSimInfo.Add("Port", new OSDInteger(Port));

            OSDArray arr = new OSDArray(1);
            arr.Add(llsdSimInfo);

            OSDMap llsdBody = new OSDMap(1);
            llsdBody.Add("SimulatorInfo", arr);

            return buildEvent("EnableSimulator", llsdBody);
        }
示例#15
0
 public override OSDMap ToOSD()
 {
     OSDMap map = new OSDMap();
     map = base.ToOSD();
     map.Add("Point", m_Point);
     return map;
 }
示例#16
0
 public static OSD DeserializeJson(JsonData json)
 {
     switch (json.GetJsonType())
     {
         case JsonType.Boolean:
             return OSD.FromBoolean((bool)json);
         case JsonType.Int:
             return OSD.FromInteger((int)json);
         case JsonType.Long:
             return OSD.FromLong((long)json);
         case JsonType.Double:
             return OSD.FromReal((double)json);
         case JsonType.String:
             string str = (string)json;
             if (String.IsNullOrEmpty(str))
                 return new OSD();
             else
                 return OSD.FromString(str);
         case JsonType.Array:
             OSDArray array = new OSDArray(json.Count);
             for (int i = 0; i < json.Count; i++)
                 array.Add(DeserializeJson(json[i]));
             return array;
         case JsonType.Object:
             OSDMap map = new OSDMap(json.Count);
             IDictionaryEnumerator e = ((IOrderedDictionary)json).GetEnumerator();
             while (e.MoveNext())
                 map.Add((string)e.Key, DeserializeJson((JsonData)e.Value));
             return map;
         case JsonType.None:
         default:
             return new OSD();
     }
 }
示例#17
0
        public OSDMap GetExternalCaps(UUID agentID, GridRegion region)
        {
            if (m_registry == null) return new OSDMap();
            OSDMap resp = new OSDMap();
            if (m_registry.RequestModuleInterface<IGridServerInfoService>() != null)
            {
                m_servers = m_registry.RequestModuleInterface<IGridServerInfoService>().GetGridURIs("SyncMessageServerURI");
                OSDMap req = new OSDMap();
                req["AgentID"] = agentID;
                req["Region"] = region.ToOSD();
                req["Method"] = "GetCaps";

                List<ManualResetEvent> events = new List<ManualResetEvent>();
                foreach (string uri in m_servers)
                {
                    ManualResetEvent even = new ManualResetEvent(false);
                    m_syncPoster.Get(uri, req, (r) =>
                    {
                        if (r == null)
                            return;
                        foreach (KeyValuePair<string, OSD> kvp in r)
                            resp.Add(kvp.Key, kvp.Value);
                        even.Set();
                    });
                    events.Add(even);
                }
                ManualResetEvent.WaitAll(events.ToArray());
            }
            foreach (var h in GetHandlers(agentID, region.RegionID))
            {
                if (m_allowedCapsModules.Contains(h.Name))
                    h.IncomingCapsRequest(agentID, region, m_registry.RequestModuleInterface<ISimulationBase>(), ref resp);
            }
            return resp;
        }
示例#18
0
        public static OSDMap FromDictionaryString(Dictionary<string, string> dict)
        {
            if (dict != null)
            {
                OSDMap map = new OSDMap(dict.Count);
                foreach (KeyValuePair<string, string> entry in dict)
                    map.Add(entry.Key, OSD.FromString(entry.Value));
                return map;
            }

            return new OSDMap(0);
        }
示例#19
0
        public static OSDMap FromDictionaryUri(Dictionary<Uri, Uri> dict)
        {
            if (dict != null)
            {
                OSDMap map = new OSDMap(dict.Count);
                foreach (KeyValuePair<Uri, Uri> entry in dict)
                    map.Add(entry.Key.ToString(), OSD.FromUri(entry.Value));
                return map;
            }

            return new OSDMap(0);
        }
示例#20
0
        public OSDMap Serialize()
        {
            OSDMap map = new OSDMap(3);
            map["ID"] = OSD.FromUUID(ID);
            map["Identifier"] = OSD.FromUri(Identity);

            OSDMap dict = new OSDMap(Attributes.Count);
            foreach (KeyValuePair<Uri, OSD> entry in Attributes)
                dict.Add(entry.Key.ToString(), entry.Value);
            map["Attributes"] = dict;

            return map;
        }
示例#21
0
        private Hashtable ProcessServerReleaseNotes(Hashtable m_dhttpMethod, UUID agentID, UUID capuuid)
        {
            Hashtable responsedata = new Hashtable();
            responsedata["int_response_code"] = 200; //501; //410; //404;
            responsedata["content_type"] = "text/plain";
            responsedata["keepalive"] = false;

            OSDMap osd = new OSDMap();
            osd.Add("ServerReleaseNotes", new OSDString(Aurora.Framework.Utilities.GetServerReleaseNotesURL()));
            string response = OSDParser.SerializeLLSDXmlString(osd);
            responsedata["str_response_string"] = response;
            return responsedata;
        }
示例#22
0
        public override OSDMap ToOSD()
        {
            OSDMap map = new OSDMap();

            map.Add("PrincipalID", OSD.FromUUID(PrincipalID));
            map.Add("Flags", OSD.FromInteger((int)Flags));
            map.Add("MaxMaturity", OSD.FromInteger(MaxMaturity));
            map.Add("MaturityRating", OSD.FromInteger(MaturityRating));
            map.Add("Language", OSD.FromString(Language));
            map.Add("AcceptTOS", OSD.FromBoolean(AcceptTOS));
            map.Add("LanguageIsPublic", OSD.FromBoolean(LanguageIsPublic));
            map.Add("OtherAgentInformation", OSD.FromString(OSDParser.SerializeLLSDXmlString(OtherAgentInformation)));
            
            return map;
        }
示例#23
0
        public OSDMap Serialize()
        {
            OSDMap map = new OSDMap();
            if (MessageSessions.Count > 0)
            {
                OSDArray messageArray = new OSDArray(MessageSessions.Count);
                foreach (KeyValuePair<string, FilterEntry> kvp in MessageSessions)
                {
                    OSDMap sessionMap = new OSDMap(3);
                    sessionMap["Capability"] = OSD.FromString(kvp.Key);
                    sessionMap["Capture"] = OSD.FromBoolean(kvp.Value.Checked);
                    sessionMap["Type"] = OSD.FromString(kvp.Value.pType);
                    messageArray.Add(sessionMap);
                }
                map.Add("message_sessions", messageArray);
            }

            if (PacketSessions.Count > 0)
            {
                OSDArray packetArray = new OSDArray(PacketSessions.Count);
                foreach (KeyValuePair<string, FilterEntry> kvp in PacketSessions)
                {
                    OSDMap sessionMap = new OSDMap(3);
                    sessionMap["PacketName"] = OSD.FromString(kvp.Key);
                    sessionMap["Capture"] = OSD.FromBoolean(kvp.Value.Checked);
                    sessionMap["Type"] = OSD.FromString(kvp.Value.pType);
                    packetArray.Add(sessionMap);
                }
                map.Add("packet_sessions", packetArray);
            }

            map.Add("AutoScrollSessions", OSD.FromBoolean(AutoScrollEnabled));
            map.Add("CaptureStatistics", OSD.FromBoolean(StatisticsEnabled));
            map.Add("SaveProfileOnExit", OSD.FromBoolean(SaveSessionOnExit));
            map.Add("AutoCheckNewCaps", OSD.FromBoolean(AutoCheckNewCaps));

            return map;
        }
示例#24
0
        public override OSDMap ToOSD()
        {
            OSDMap map = new OSDMap();

            map.Add("PrincipalID", OSD.FromUUID(PrincipalID));
            map.Add("Flags", OSD.FromInteger((int)Flags));
            map.Add("MaxMaturity", OSD.FromInteger(MaxMaturity));
            map.Add("MaturityRating", OSD.FromInteger(MaturityRating));
            map.Add("Language", OSD.FromString(Language));
            map.Add("AcceptTOS", OSD.FromBoolean(AcceptTOS));
            map.Add("LanguageIsPublic", OSD.FromBoolean(LanguageIsPublic));
            
            return map;
        }
示例#25
0
        public static OSDMap TeleportFinish(UUID agentID, int locationID, ulong regionHandle, Uri seedCap, SimAccess simAccess,
            IPAddress simIP, int simPort, TeleportFlags teleportFlags)
        {
            OSDMap info = new OSDMap(8);
            info.Add("AgentID", OSD.FromUUID(agentID));
            info.Add("LocationID", OSD.FromInteger(locationID)); // Unused by the client
            info.Add("RegionHandle", OSD.FromULong(regionHandle));
            info.Add("SeedCapability", OSD.FromUri(seedCap));
            info.Add("SimAccess", OSD.FromInteger((byte)simAccess));
            info.Add("SimIP", OSD.FromBinary(simIP.GetAddressBytes()));
            info.Add("SimPort", OSD.FromInteger(simPort));
            info.Add("TeleportFlags", OSD.FromUInteger((uint)teleportFlags));

            OSDArray infoArray = new OSDArray(1);
            infoArray.Add(info);

            OSDMap teleport = new OSDMap(1);
            teleport.Add("Info", infoArray);

            return teleport;
        }
示例#26
0
        /// <summary>
        /// Serialize the object
        /// </summary>
        /// <returns>An <see cref="OSDMap"/> containing the objects data</returns>
        public OSDMap Serialize()
        {
            OSDMap map = new OSDMap(1);

            OSDArray infoArray = new OSDArray(1);

            OSDMap info = new OSDMap(8);
            info.Add("AgentID", OSD.FromUUID(AgentID));
            info.Add("LocationID", OSD.FromInteger(LocationID)); // Unused by the client
            info.Add("RegionHandle", OSD.FromULong(RegionHandle));
            info.Add("SeedCapability", OSD.FromUri(SeedCapability));
            info.Add("SimAccess", OSD.FromInteger((byte)SimAccess));
            info.Add("SimIP", MessageUtils.FromIP(IP));
            info.Add("SimPort", OSD.FromInteger(Port));
            info.Add("TeleportFlags", OSD.FromUInteger((uint)Flags));

            infoArray.Add(info);

            map.Add("Info", infoArray);

            return map;
        }
示例#27
0
 public object DoRemoteForUser(UUID userID, params object[] o)
 {
     if (!m_doRemoteCalls)
         return null;
     StackTrace stackTrace = new StackTrace();
     int upStack = 1;
     if (userID == UUID.Zero)
         upStack = 2;
     MethodInfo method = (MethodInfo)stackTrace.GetFrame(upStack).GetMethod();
     string methodName = method.Name;
     OSDMap map = new OSDMap();
     map["Method"] = methodName;
     int i = 0;
     foreach(ParameterInfo info in method.GetParameters())
     {
         map.Add(info.Name, Util.MakeOSD(o[i], o[i].GetType()));
         i++;
     }
     List<string> m_ServerURIs =
             m_configService.FindValueOf(userID.ToString(), "ServerURI", false);
     OSDMap response = null;
     foreach (string uri in m_ServerURIs)
     {
         if (GetOSDMap(uri, map, out response))
             break;
     }
     if (response == null || !response)
         return null;
     object inst =  Activator.CreateInstance(method.ReturnType);
     if (inst is IDataTransferable)
     {
         IDataTransferable instance = (IDataTransferable)inst;
         instance.FromOSD((OSDMap)response["Value"]);
         return instance;
     }
     else
         return Util.OSDToObject(response["Value"], method.ReturnType);
 }
        public void TestSerializeXml2()
        {
            TestHelpers.InMethod();
            //log4net.Config.XmlConfigurator.Configure();

            string             rpName      = "My Little Pony";
            UUID               rpUuid      = UUID.Parse("00000000-0000-0000-0000-000000000064");
            UUID               rpCreatorId = UUID.Parse("00000000-0000-0000-0000-000000000015");
            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);

            SceneObjectPart rp = new SceneObjectPart();

            rp.UUID      = rpUuid;
            rp.Name      = rpName;
            rp.CreatorID = rpCreatorId;
            rp.Shape     = shape;

            string daNamespace = "MyNamespace";
            string daStoreName = "MyStore";
            string daKey       = "foo";
            string daValue     = "bar";
            OSDMap myStore     = new OSDMap();

            myStore.Add(daKey, daValue);
            rp.DynAttrs = new DAMap();
            rp.DynAttrs.SetStore(daNamespace, daStoreName, myStore);

            SceneObjectGroup so = new SceneObjectGroup(rp);

            // Need to add the object to the scene so that the request to get script state succeeds
            m_scene.AddSceneObject(so);

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

            options["old-guids"] = true;
            string xml2 = m_serialiserModule.SerializeGroupToXml2(so, options);

            XmlTextReader xtr = new XmlTextReader(new StringReader(xml2));

            xtr.ReadStartElement("SceneObjectGroup");
            xtr.ReadStartElement("SceneObjectPart");

            UUID   uuid      = UUID.Zero;
            string name      = null;
            UUID   creatorId = UUID.Zero;
            DAMap  daMap     = null;

            while (xtr.Read() && xtr.Name != "SceneObjectPart")
            {
                if (xtr.NodeType != XmlNodeType.Element)
                {
                    continue;
                }

                switch (xtr.Name)
                {
                case "UUID":
                    xtr.ReadStartElement("UUID");
                    uuid = UUID.Parse(xtr.ReadElementString("Guid"));
                    xtr.ReadEndElement();
                    break;

                case "Name":
                    name = xtr.ReadElementContentAsString();
                    break;

                case "CreatorID":
                    xtr.ReadStartElement("CreatorID");
                    creatorId = UUID.Parse(xtr.ReadElementString("Guid"));
                    xtr.ReadEndElement();
                    break;

                case "DynAttrs":
                    daMap = new DAMap();
                    daMap.ReadXml(xtr);
                    break;
                }
            }

            xtr.ReadEndElement();
            xtr.ReadStartElement("OtherParts");
            xtr.ReadEndElement();
            xtr.Close();

            // TODO: More checks
            Assert.That(uuid, Is.EqualTo(rpUuid));
            Assert.That(name, Is.EqualTo(rpName));
            Assert.That(creatorId, Is.EqualTo(rpCreatorId));
            Assert.NotNull(daMap);
            Assert.AreEqual(daValue, daMap.GetStore(daNamespace, daStoreName)[daKey].AsString());
        }
示例#29
0
        public Hashtable GetEvents(UUID requestID, UUID pAgentId)
        {
            if (DebugLevel >= 2)
            {
                m_log.WarnFormat("POLLED FOR EQ MESSAGES BY {0} in {1}", pAgentId, m_scene.Name);
            }

            Queue <OSD> queue = GetQueue(pAgentId);

            if (queue == null)
            {
                return(NoEvents(requestID, pAgentId));
            }

            OSD      element    = null;;
            OSDArray array      = new OSDArray();
            int      thisID     = 0;
            bool     negativeID = false;

            lock (queue)
            {
                if (queue.Count == 0)
                {
                    return(NoEvents(requestID, pAgentId));
                }

                lock (m_ids)
                    thisID = m_ids[pAgentId];

                if (thisID < 0)
                {
                    negativeID = true;
                    thisID     = -thisID;
                }

                while (queue.Count > 0)
                {
                    element = queue.Dequeue();
                    // add elements until a marker is found
                    // so they get into a response
                    if (element == null)
                    {
                        break;
                    }
                    if (DebugLevel > 0)
                    {
                        LogOutboundDebugMessage(element, pAgentId);
                    }
                    array.Add(element);
                }
            }

            OSDMap events = null;

            if (array.Count > 0)
            {
                events = new OSDMap();
                events.Add("events", array);
                events.Add("id", new OSDInteger(thisID));
            }

            if (negativeID && element == null)
            {
                Random rnd = new Random(Environment.TickCount);
                thisID = rnd.Next(30000000);
            }

            lock (m_ids)
            {
                m_ids[pAgentId] = thisID + 1;
            }

            Hashtable responsedata;

            // if there where no elements before a marker send a NoEvents
            if (events == null)
            {
                return(NoEvents(requestID, pAgentId));
            }
            else
            {
                responsedata = new Hashtable();
                responsedata["int_response_code"] = 200;
                responsedata["content_type"]      = "application/xml";
                responsedata["bin_response_data"] = Encoding.UTF8.GetBytes(OSDParser.SerializeLLSDXmlString(events));
            }
            //m_log.DebugFormat("[EVENTQUEUE]: sending response for {0} in region {1}: {2}", pAgentId, m_scene.RegionInfo.RegionName, responsedata["str_response_string"]);
            return(responsedata);
        }
        // <summary>
        // </summary>
        // <param name=""></param>
        public bool SetAvatar(UUID userID, AvatarData avatar)
        {
            m_log.Debug("[SIMIAN AVATAR CONNECTOR]: SetAvatar called for " + userID);

            if (avatar.AvatarType == 1) // LLAvatar
            {
                AvatarAppearance appearance = avatar.ToAvatarAppearance();

                OSDMap map = new OSDMap();

                map["Height"] = OSD.FromReal(appearance.AvatarHeight);

                map["BodyItem"]        = appearance.Wearables[AvatarWearable.BODY][0].ItemID.ToString();
                map["EyesItem"]        = appearance.Wearables[AvatarWearable.EYES][0].ItemID.ToString();
                map["GlovesItem"]      = appearance.Wearables[AvatarWearable.GLOVES][0].ItemID.ToString();
                map["HairItem"]        = appearance.Wearables[AvatarWearable.HAIR][0].ItemID.ToString();
                map["JacketItem"]      = appearance.Wearables[AvatarWearable.JACKET][0].ItemID.ToString();
                map["PantsItem"]       = appearance.Wearables[AvatarWearable.PANTS][0].ItemID.ToString();
                map["ShirtItem"]       = appearance.Wearables[AvatarWearable.SHIRT][0].ItemID.ToString();
                map["ShoesItem"]       = appearance.Wearables[AvatarWearable.SHOES][0].ItemID.ToString();
                map["SkinItem"]        = appearance.Wearables[AvatarWearable.SKIN][0].ItemID.ToString();
                map["SkirtItem"]       = appearance.Wearables[AvatarWearable.SKIRT][0].ItemID.ToString();
                map["SocksItem"]       = appearance.Wearables[AvatarWearable.SOCKS][0].ItemID.ToString();
                map["UnderPantsItem"]  = appearance.Wearables[AvatarWearable.UNDERPANTS][0].ItemID.ToString();
                map["UnderShirtItem"]  = appearance.Wearables[AvatarWearable.UNDERSHIRT][0].ItemID.ToString();
                map["BodyAsset"]       = appearance.Wearables[AvatarWearable.BODY][0].AssetID.ToString();
                map["EyesAsset"]       = appearance.Wearables[AvatarWearable.EYES][0].AssetID.ToString();
                map["GlovesAsset"]     = appearance.Wearables[AvatarWearable.GLOVES][0].AssetID.ToString();
                map["HairAsset"]       = appearance.Wearables[AvatarWearable.HAIR][0].AssetID.ToString();
                map["JacketAsset"]     = appearance.Wearables[AvatarWearable.JACKET][0].AssetID.ToString();
                map["PantsAsset"]      = appearance.Wearables[AvatarWearable.PANTS][0].AssetID.ToString();
                map["ShirtAsset"]      = appearance.Wearables[AvatarWearable.SHIRT][0].AssetID.ToString();
                map["ShoesAsset"]      = appearance.Wearables[AvatarWearable.SHOES][0].AssetID.ToString();
                map["SkinAsset"]       = appearance.Wearables[AvatarWearable.SKIN][0].AssetID.ToString();
                map["SkirtAsset"]      = appearance.Wearables[AvatarWearable.SKIRT][0].AssetID.ToString();
                map["SocksAsset"]      = appearance.Wearables[AvatarWearable.SOCKS][0].AssetID.ToString();
                map["UnderPantsAsset"] = appearance.Wearables[AvatarWearable.UNDERPANTS][0].AssetID.ToString();
                map["UnderShirtAsset"] = appearance.Wearables[AvatarWearable.UNDERSHIRT][0].AssetID.ToString();


                OSDMap items = new OSDMap();
                foreach (KeyValuePair <string, string> kvp in avatar.Data)
                {
                    if (kvp.Key.StartsWith("_ap_"))
                    {
                        items.Add(kvp.Key, OSD.FromString(kvp.Value));
                    }
                }

                NameValueCollection requestArgs = new NameValueCollection
                {
                    { "RequestMethod", "AddUserData" },
                    { "UserID", userID.ToString() },
                    { "LLAppearance", OSDParser.SerializeJsonString(map) },
                    { "LLAttachments", OSDParser.SerializeJsonString(items) }
                };

                OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
                bool   success  = response["Success"].AsBoolean();

                if (!success)
                {
                    m_log.Warn("[SIMIAN AVATAR CONNECTOR]: Failed saving appearance for " + userID + ": " + response["Message"].AsString());
                }

                return(success);
            }
            else
            {
                m_log.Error("[SIMIAN AVATAR CONNECTOR]: Can't save appearance for " + userID + ". Unhandled avatar type " + avatar.AvatarType);
                return(false);
            }
        }
        public bool QueryAccess(GridRegion destination, UUID agentID, string agentHomeURI, bool viaTeleport, Vector3 position, List <UUID> featuresAvailable, EntityTransferContext ctx, out string reason)
        {
            Culture.SetCurrentCulture();

            reason = "Failed to contact destination";

            // m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: QueryAccess start, position={0}", position);

            // Eventually, we want to use a caps url instead of the agentID
            string uri = destination.ServerURI + AgentPath() + agentID + "/" + destination.RegionID.ToString() + "/";

            OSDMap request = new OSDMap();

            request.Add("viaTeleport", OSD.FromBoolean(viaTeleport));
            request.Add("position", OSD.FromString(position.ToString()));
            // To those who still understad this field, we're telling them
            // the lowest version just to be safe
            request.Add("my_version", OSD.FromString(String.Format("SIMULATION/{0}", VersionInfo.SimulationServiceVersionSupportedMin)));
            // New simulation service negotiation
            request.Add("simulation_service_supported_min", OSD.FromReal(VersionInfo.SimulationServiceVersionSupportedMin));
            request.Add("simulation_service_supported_max", OSD.FromReal(VersionInfo.SimulationServiceVersionSupportedMax));
            request.Add("simulation_service_accepted_min", OSD.FromReal(VersionInfo.SimulationServiceVersionAcceptedMin));
            request.Add("simulation_service_accepted_max", OSD.FromReal(VersionInfo.SimulationServiceVersionAcceptedMax));

            request.Add("context", ctx.Pack());

            OSDArray features = new OSDArray();

            foreach (UUID feature in featuresAvailable)
            {
                features.Add(OSD.FromString(feature.ToString()));
            }

            request.Add("features", features);

            if (agentHomeURI != null)
            {
                request.Add("agent_home_uri", OSD.FromString(agentHomeURI));
            }

            try
            {
                OSDMap result  = WebUtil.ServiceOSDRequest(uri, request, "QUERYACCESS", 30000, false, false);
                bool   success = result["success"].AsBoolean();
                if (result.ContainsKey("_Result"))
                {
                    OSDMap data = (OSDMap)result["_Result"];

                    // FIXME: If there is a _Result map then it's the success key here that indicates the true success
                    // or failure, not the sibling result node.
                    success = data["success"].AsBoolean();

                    reason = data["reason"].AsString();
                    // We will need to plumb this and start sing the outbound version as well
                    // TODO: lay the pipe for version plumbing
                    if (data.ContainsKey("negotiated_inbound_version") && data["negotiated_inbound_version"] != null)
                    {
                        ctx.InboundVersion  = (float)data["negotiated_inbound_version"].AsReal();
                        ctx.OutboundVersion = (float)data["negotiated_outbound_version"].AsReal();
                    }
                    else if (data["version"] != null && data["version"].AsString() != string.Empty)
                    {
                        string   versionString = data["version"].AsString();
                        String[] parts         = versionString.Split(new char[] { '/' });
                        if (parts.Length > 1)
                        {
                            ctx.InboundVersion  = float.Parse(parts[1], Culture.FormatProvider);
                            ctx.OutboundVersion = float.Parse(parts[1], Culture.FormatProvider);
                        }
                    }

                    m_log.DebugFormat(
                        "[REMOTE SIMULATION CONNECTOR]: QueryAccess to {0} returned {1}, reason {2}, version {3}/{4}",
                        uri, success, reason, ctx.InboundVersion, ctx.OutboundVersion);
                }

                if (!success || ctx.InboundVersion == 0f || ctx.OutboundVersion == 0f)
                {
                    // If we don't check this then OpenSimulator 0.7.3.1 and some period before will never see the
                    // actual failure message
                    if (!result.ContainsKey("_Result"))
                    {
                        if (result.ContainsKey("Message"))
                        {
                            string message = result["Message"].AsString();
                            if (message == "Service request failed: [MethodNotAllowed] MethodNotAllowed") // Old style region
                            {
                                m_log.Info("[REMOTE SIMULATION CONNECTOR]: The above web util error was caused by a TP to a sim that doesn't support QUERYACCESS and can be ignored");
                                return(true);
                            }

                            reason = result["Message"];
                        }
                        else
                        {
                            reason = "Communications failure";
                        }
                    }

                    return(false);
                }

                featuresAvailable.Clear();

                if (result.ContainsKey("features"))
                {
                    OSDArray array = (OSDArray)result["features"];

                    foreach (OSD o in array)
                    {
                        featuresAvailable.Add(new UUID(o.AsString()));
                    }
                }

                // Version stuff
                if (ctx.OutboundVersion < 0.5)
                {
                    ctx.WearablesCount = AvatarWearable.LEGACY_VERSION_MAX_WEARABLES;
                }
                else if (ctx.OutboundVersion < 0.6)
                {
                    ctx.WearablesCount = AvatarWearable.LEGACY_VERSION_MAX_WEARABLES + 1;
                }
                else
                {
                    ctx.WearablesCount = -1; // send all (just in case..)
                }
                return(success);
            }
            catch (Exception e)
            {
                m_log.WarnFormat("[REMOTE SIMULATION CONNECTOR] QueryAcesss failed with exception; {0}", e.ToString());
            }

            return(false);
        }
        public string GetJsonConfig()
        {
            OSDMap map = new OSDMap(9);

            map.Add("Realm", m_freeSwitchRealm);
            map.Add("SIPProxy", m_freeSwitchSIPProxy);
            map.Add("AttemptUseSTUN", m_freeSwitchAttemptUseSTUN);
            map.Add("EchoServer", m_freeSwitchEchoServer);
            map.Add("EchoPort", m_freeSwitchEchoPort);
            map.Add("DefaultWellKnownIP", m_freeSwitchDefaultWellKnownIP);
            map.Add("DefaultTimeout", m_freeSwitchDefaultTimeout);
            map.Add("Context", m_freeSwitchContext);
            map.Add("APIPrefix", m_freeSwitchAPIPrefix);

            return OSDParser.SerializeJsonString(map);
        }
示例#33
0
        ///
        /// <summary>
        /// Handles the avatar classifieds request.
        /// </summary>
        /// <param name='sender'>
        /// Sender.
        /// </param>
        /// <param name='method'>
        /// Method.
        /// </param>
        /// <param name='args'>
        /// Arguments.
        /// </param>
        public void ClassifiedsRequest(Object sender, string method, List <String> args)
        {
            if (!(sender is IClientAPI))
            {
                return;
            }

            IClientAPI remoteClient = (IClientAPI)sender;

            UUID targetID;

            UUID.TryParse(args[0], out targetID);

            // Can't handle NPC yet...
            ScenePresence p = FindPresence(targetID);

            if (null != p)
            {
                if (p.PresenceType == PresenceType.Npc)
                {
                    return;
                }
            }

            string serverURI = string.Empty;

            GetUserProfileServerURI(targetID, out serverURI);
            UUID creatorId = UUID.Zero;
            Dictionary <UUID, string> classifieds = new Dictionary <UUID, string>();

            OSDMap parameters = new OSDMap();

            UUID.TryParse(args[0], out creatorId);
            parameters.Add("creatorId", OSD.FromUUID(creatorId));
            OSD Params = (OSD)parameters;

            if (!rpc.JsonRpcRequest(ref Params, "avatarclassifiedsrequest", serverURI, UUID.Random().ToString()))
            {
                remoteClient.SendAvatarClassifiedReply(new UUID(args[0]), classifieds);
                return;
            }

            parameters = (OSDMap)Params;

            OSDArray list = (OSDArray)parameters["result"];


            foreach (OSD map in list)
            {
                OSDMap m    = (OSDMap)map;
                UUID   cid  = m["classifieduuid"].AsUUID();
                string name = m["name"].AsString();

                classifieds[cid] = name;

                lock (m_classifiedCache)
                {
                    if (!m_classifiedCache.ContainsKey(cid))
                    {
                        m_classifiedCache.Add(cid, creatorId);
                        m_classifiedInterest.Add(cid, 0);
                    }

                    m_classifiedInterest[cid]++;
                }
            }

            remoteClient.SendAvatarClassifiedReply(new UUID(args[0]), classifieds);
        }
        bool PrepRemoteCall(string url, object [] o, out MethodInfo method, out OSDMap map, out string serverURL)
        {
            var stackTrace = new StackTrace();
            int upStack    = 1;
            var frame      = stackTrace.GetFrame(1);

            if (frame.GetMethod().Name.Contains("DoRemote"))
            {
                upStack = 2;
                frame   = stackTrace.GetFrame(2);
                if (frame.GetMethod().Name.Contains("DoRemote"))
                {
                    upStack = 3;
                }
            }

            CanBeReflected reflection;

            GetReflection(upStack, stackTrace, out method, out reflection);
            string methodName = reflection != null && reflection.RenamedMethod != ""
                                    ? reflection.RenamedMethod
                                    : method.Name;

            map            = new OSDMap();
            map ["Method"] = methodName;
            if (reflection != null && reflection.UsePassword)
            {
                map ["Password"] = m_password;
            }
            int i          = 0;
            var parameters = method.GetParameters();

            if (o.Length != parameters.Length)
            {
                MainConsole.Instance.ErrorFormat(
                    "[ConnectorBase]: Failed to get valid number of parameters to send  in remote call to {0}, expected {1}, got {2}",
                    methodName, parameters.Length, o.Length);
                serverURL = "";
                return(false);
            }
            foreach (ParameterInfo info in parameters)
            {
                OSD osd = o [i] == null ? null : Util.MakeOSD(o [i], o [i].GetType());
                if (osd != null)
                {
                    map.Add(info.Name, osd);
                }
                else
                {
                    map.Add(info.Name, new OSD());
                }
                i++;
            }

            serverURL = m_configService == null ? "" : m_configService.FindValueOf(url);
            if (serverURL == "")
            {
                serverURL = url;
            }
            return(true);
        }
        /// <summary>
        /// Convert active connections information to JSON string. Returns a structure:
        /// <pre>
        /// {"regionName": {
        ///     "presenceName": {
        ///         "name": "presenceName",
        ///         "position": "<x,y,z>",
        ///         "isRoot": "false",
        ///         "throttle": {
        ///         },
        ///         "queue": {
        ///         }
        ///     },
        ///     ... // multiple presences in the scene
        ///   },
        ///   ...   // multiple regions in the sim
        /// }
        ///
        /// </pre>
        /// </summary>
        /// <param name="pModelResult"></param>
        /// <returns></returns>
        public string RenderJson(Hashtable pModelResult)
        {
            List <Scene> all_scenes = (List <Scene>)pModelResult["hdata"];

            OSDMap regionInfo = new OSDMap();

            foreach (Scene scene in all_scenes)
            {
                OSDMap sceneInfo = new OpenMetaverse.StructuredData.OSDMap();
                List <ScenePresence> avatarInScene = scene.GetScenePresences();
                foreach (ScenePresence av in avatarInScene)
                {
                    OSDMap presenceInfo = new OSDMap();
                    presenceInfo.Add("Name", new OSDString(av.Name));

                    Dictionary <string, string> queues = new Dictionary <string, string>();
                    if (av.ControllingClient is IStatsCollector)
                    {
                        IStatsCollector isClient = (IStatsCollector)av.ControllingClient;
                        queues = decodeQueueReport(isClient.Report());
                    }
                    OSDMap queueInfo = new OpenMetaverse.StructuredData.OSDMap();
                    foreach (KeyValuePair <string, string> kvp in queues)
                    {
                        queueInfo.Add(kvp.Key, new OSDString(kvp.Value));
                    }
                    sceneInfo.Add("queues", queueInfo);

                    if (av.IsChildAgent)
                    {
                        presenceInfo.Add("isRoot", new OSDString("false"));
                    }
                    else
                    {
                        presenceInfo.Add("isRoot", new OSDString("true"));
                    }

                    if (av.AbsolutePosition == DefaultNeighborPosition)
                    {
                        presenceInfo.Add("position", new OSDString("<0, 0, 0>"));
                    }
                    else
                    {
                        presenceInfo.Add("position", new OSDString(string.Format("<{0},{1},{2}>",
                                                                                 (int)av.AbsolutePosition.X,
                                                                                 (int)av.AbsolutePosition.Y,
                                                                                 (int)av.AbsolutePosition.Z)));
                    }

                    Dictionary <string, int> throttles = DecodeClientThrottles(av.ControllingClient.GetThrottlesPacked(1));
                    OSDMap throttleInfo = new OpenMetaverse.StructuredData.OSDMap();
                    foreach (string throttlename in throttles.Keys)
                    {
                        throttleInfo.Add(throttlename, new OSDString(throttles[throttlename].ToString()));
                    }
                    presenceInfo.Add("throttle", throttleInfo);

                    sceneInfo.Add(av.Name, presenceInfo);
                }
                regionInfo.Add(scene.RegionInfo.RegionName, sceneInfo);
            }
            return(regionInfo.ToString());
        }
示例#36
0
        public static OSD InstantMessageParams(UUID fromAgent, string message, UUID toAgent,
                                               string fromName, byte dialog, uint timeStamp, bool offline, int parentEstateID,
                                               Vector3 position, uint ttl, UUID transactionID, bool fromGroup, byte[] binaryBucket)
        {
            OSDMap messageParams = new OSDMap(15);

            messageParams.Add("type", new OSDInteger((int)dialog));

            OSDArray positionArray = new OSDArray(3);

            positionArray.Add(OSD.FromReal(position.X));
            positionArray.Add(OSD.FromReal(position.Y));
            positionArray.Add(OSD.FromReal(position.Z));
            messageParams.Add("position", positionArray);

            messageParams.Add("region_id", new OSDUUID(UUID.Zero));
            messageParams.Add("to_id", new OSDUUID(toAgent));
            messageParams.Add("source", new OSDInteger(0));

            OSDMap data = new OSDMap(1);

            data.Add("binary_bucket", OSD.FromBinary(binaryBucket));
            messageParams.Add("data", data);
            messageParams.Add("message", new OSDString(message));
            messageParams.Add("id", new OSDUUID(transactionID));
            messageParams.Add("from_name", new OSDString(fromName));
            messageParams.Add("timestamp", new OSDInteger((int)timeStamp));
            messageParams.Add("offline", new OSDInteger(offline ? 1 : 0));
            messageParams.Add("parent_estate_id", new OSDInteger(parentEstateID));
            messageParams.Add("ttl", new OSDInteger((int)ttl));
            messageParams.Add("from_id", new OSDUUID(fromAgent));
            messageParams.Add("from_group", new OSDInteger(fromGroup ? 1 : 0));

            return(messageParams);
        }
示例#37
0
        public static OSD PlacesQuery(PlacesReplyPacket PlacesReply, string[] regionType)
        {
            OSDMap placesReply = new OSDMap();

            placesReply.Add("message", OSD.FromString("PlacesReplyMessage"));

            OSDMap   body         = new OSDMap();
            OSDArray agentData    = new OSDArray();
            OSDMap   agentDataMap = new OSDMap();

            agentDataMap.Add("AgentID", OSD.FromUUID(PlacesReply.AgentData.AgentID));
            agentDataMap.Add("QueryID", OSD.FromUUID(PlacesReply.AgentData.QueryID));
            agentDataMap.Add("TransactionID", OSD.FromUUID(PlacesReply.TransactionData.TransactionID));
            agentData.Add(agentDataMap);
            body.Add("AgentData", agentData);

            OSDArray QueryData = new OSDArray();
            int      i         = 0;

            foreach (PlacesReplyPacket.QueryDataBlock groupDataBlock in PlacesReply.QueryData)
            {
                OSDMap QueryDataMap = new OSDMap();
                QueryDataMap.Add("ActualArea", OSD.FromInteger(groupDataBlock.ActualArea));
                QueryDataMap.Add("BillableArea", OSD.FromInteger(groupDataBlock.BillableArea));
                QueryDataMap.Add("Description", OSD.FromBinary(groupDataBlock.Desc));
                QueryDataMap.Add("Dwell", OSD.FromInteger((int)groupDataBlock.Dwell));
                QueryDataMap.Add("Flags", OSD.FromString(Convert.ToString(groupDataBlock.Flags)));
                QueryDataMap.Add("GlobalX", OSD.FromInteger((int)groupDataBlock.GlobalX));
                QueryDataMap.Add("GlobalY", OSD.FromInteger((int)groupDataBlock.GlobalY));
                QueryDataMap.Add("GlobalZ", OSD.FromInteger((int)groupDataBlock.GlobalZ));
                QueryDataMap.Add("Name", OSD.FromBinary(groupDataBlock.Name));
                QueryDataMap.Add("OwnerID", OSD.FromUUID(groupDataBlock.OwnerID));
                QueryDataMap.Add("SimName", OSD.FromBinary(groupDataBlock.SimName));
                QueryDataMap.Add("SnapShotID", OSD.FromUUID(groupDataBlock.SnapshotID));
                QueryDataMap.Add("ProductSku", OSD.FromString(regionType[i]));
                QueryDataMap.Add("Price", OSD.FromInteger(groupDataBlock.Price));

                QueryData.Add(QueryDataMap);
                i++;
            }
            body.Add("QueryData", QueryData);
            placesReply.Add("QueryData[]", body);

            placesReply.Add("body", body);

            return(placesReply);
        }
示例#38
0
        public override byte[] Handle(string path, Stream requestData,
                                      OSHttpRequest httpRequest, OSHttpResponse httpResponse)
        {
            StreamReader sr   = new StreamReader(requestData);
            string       body = sr.ReadToEnd();

            sr.Close();
            body = body.Trim();

            //m_log.DebugFormat("[XXX]: query String: {0}", body);
            string method = string.Empty;

            try
            {
                OSDMap map = (OSDMap)OSDParser.DeserializeJson(body);
                //Make sure that the person who is calling can access the web service
                if (VerifyPassword(map))
                {
                    method = map["Method"].AsString();
                    if (method == "Login")
                    {
                        return(ProcessLogin(map));
                    }
                    else if (method == "AdminLogin")
                    {
                        return(ProcessAdminLogin(map));
                    }
                    else if (method == "CreateAccount")
                    {
                        return(ProcessCreateAccount(map));
                    }
                    else if (method == "OnlineStatus")
                    {
                        return(ProcessOnlineStatus(map));
                    }
                    else if (method == "Authenticated")
                    {
                        return(Authenticated(map));
                    }
                    else if (method == "GetGridUserInfo")
                    {
                        return(GetGridUserInfo(map));
                    }
                    else if (method == "ChangePassword")
                    {
                        return(ChangePassword(map));
                    }
                    else if (method == "CheckIfUserExists")
                    {
                        return(CheckIfUserExists(map));
                    }
                    else if (method == "SaveEmail")
                    {
                        return(SaveEmail(map));
                    }
                    else if (method == "ChangeName")
                    {
                        return(ChangeName(map));
                    }
                    else if (method == "ConfirmUserEmailName")
                    {
                        return(ConfirmUserEmailName(map));
                    }
                    else if (method == "ForgotPassword")
                    {
                        return(ForgotPassword(map));
                    }
                    else if (method == "GetProfile")
                    {
                        return(GetProfile(map));
                    }
                    else if (method == "GetAvatarArchives")
                    {
                        return(GetAvatarArchives(map));
                    }
                    else if (method == "DeleteUser")
                    {
                        return(DeleteUser(map));
                    }
                    else if (method == "BanUser")
                    {
                        return(BanUser(map));
                    }
                    else if (method == "TempBanUser")
                    {
                        return(TempBanUser(map));
                    }
                    else if (method == "UnBanUser")
                    {
                        return(UnBanUser(map));
                    }
                    else if (method == "FindUsers")
                    {
                        return(FindUsers(map));
                    }
                    else if (method == "GetAbuseReports")
                    {
                        return(GetAbuseReports(map));
                    }
                    else if (method == "AbuseReportSaveNotes")
                    {
                        return(AbuseReportSaveNotes(map));
                    }
                    else if (method == "AbuseReportMarkComlete")
                    {
                        return(AbuseReportMarkComlete(map));
                    }
                }
            }
            catch (Exception)
            {
            }
            OSDMap resp = new OSDMap();

            resp.Add("response", OSD.FromString("Failed"));
            string       xmlString = OSDParser.SerializeJsonString(resp);
            UTF8Encoding encoding  = new UTF8Encoding();

            return(encoding.GetBytes(xmlString));
        }
示例#39
0
        public object DoRemoteCall(bool forced, string url, bool urlOverrides, UUID userID, params object[] o)
        {
            if (!m_doRemoteCalls && !forced)
            {
                return(null);
            }
            StackTrace stackTrace = new StackTrace();
            int        upStack    = 1;

            if (userID == UUID.Zero)
            {
                upStack = 2;
            }
            MethodInfo     method;
            CanBeReflected reflection;

            GetReflection(upStack, stackTrace, out method, out reflection);
            string methodName = reflection != null && reflection.RenamedMethod != "" ? reflection.RenamedMethod : method.Name;
            OSDMap map        = new OSDMap();

            map["Method"] = methodName;
            if (reflection.UsePassword)
            {
                map["Password"] = m_password;
            }
            int i          = 0;
            var parameters = method.GetParameters();

            if (o.Length != parameters.Length)
            {
                MainConsole.Instance.ErrorFormat("FAILED TO GET VALID NUMBER OF PARAMETERS TO SEND REMOTELY FOR {0}, EXPECTED {1}, GOT {2}", methodName, parameters.Length, o.Length);
                return(null);
            }
            foreach (ParameterInfo info in parameters)
            {
                OSD osd = o[i] == null ? null : Util.MakeOSD(o[i], o[i].GetType());
                if (osd != null)
                {
                    map.Add(info.Name, osd);
                }
                i++;
            }
            List <string> m_ServerURIs = GetURIs(urlOverrides, map, url, userID);
            OSDMap        response     = null;
            int           loops2Do     = (m_ServerURIs.Count < m_OSDRequestTryCount) ? m_ServerURIs.Count : m_OSDRequestTryCount;

            for (int index = 0; index < loops2Do; index++)
            {
                string uri = m_ServerURIs[index];
                if (GetOSDMap(uri, map, out response))
                {
                    break;
                }
            }
            if (response == null || !response)
            {
                return(null);
            }
            object inst = null;

            try
            {
                if (method.ReturnType == typeof(string))
                {
                    inst = string.Empty;
                }
                else if (method.ReturnType == typeof(void))
                {
                    return(null);
                }
                else if (method.ReturnType == typeof(System.Drawing.Image))
                {
                    inst = null;
                }
                else
                {
                    inst = Activator.CreateInstance(method.ReturnType);
                }
            }
            catch
            {
                if (method.ReturnType == typeof(string))
                {
                    inst = string.Empty;
                }
            }
            if (response["Value"] == "null")
            {
                return(null);
            }
            var instance = inst as IDataTransferable;

            if (instance != null)
            {
                instance.FromOSD((OSDMap)response["Value"]);
                return(instance);
            }
            return(Util.OSDToObject(response["Value"], method.ReturnType));
        }
        /// <summary>
        /// </summary>
        public bool QueryAccess(GridRegion destination, UUID id, Vector3 position, out string version, out string reason)
        {
            reason  = "Failed to contact destination";
            version = "Unknown";

            // m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: QueryAccess start, position={0}", position);

            IPEndPoint ext = destination.ExternalEndPoint;

            if (ext == null)
            {
                return(false);
            }

            // Eventually, we want to use a caps url instead of the agentID
            string uri = destination.ServerURI + AgentPath() + id + "/" + destination.RegionID.ToString() + "/";

            OSDMap request = new OSDMap();

            request.Add("position", OSD.FromString(position.ToString()));

            try
            {
                OSDMap result  = WebUtil.ServiceOSDRequest(uri, request, "QUERYACCESS", 30000, false);
                bool   success = result["success"].AsBoolean();
                if (result.ContainsKey("_Result"))
                {
                    OSDMap data = (OSDMap)result["_Result"];

                    // FIXME: If there is a _Result map then it's the success key here that indicates the true success
                    // or failure, not the sibling result node.
                    success = data["success"];

                    reason = data["reason"].AsString();
                    if (data["version"] != null && data["version"].AsString() != string.Empty)
                    {
                        version = data["version"].AsString();
                    }

                    m_log.DebugFormat(
                        "[REMOTE SIMULATION CONNECTOR]: QueryAccess to {0} returned {1}, reason {2}, version {3} ({4})",
                        uri, success, reason, version, data["version"].AsString());
                }

                if (!success)
                {
                    // If we don't check this then OpenSimulator 0.7.3.1 and some period before will never see the
                    // actual failure message
                    if (!result.ContainsKey("_Result"))
                    {
                        if (result.ContainsKey("Message"))
                        {
                            string message = result["Message"].AsString();
                            if (message == "Service request failed: [MethodNotAllowed] MethodNotAllowed") // Old style region
                            {
                                m_log.Info("[REMOTE SIMULATION CONNECTOR]: The above web util error was caused by a TP to a sim that doesn't support QUERYACCESS and can be ignored");
                                return(true);
                            }

                            reason = result["Message"];
                        }
                        else
                        {
                            reason = "Communications failure";
                        }
                    }

                    return(false);
                }

                return(success);
            }
            catch (Exception e)
            {
                m_log.WarnFormat("[REMOTE SIMULATION CONNECTOR] QueryAcesss failed with exception; {0}", e.ToString());
            }

            return(false);
        }
        public bool Charge (UUID agentID, int amount, string description, TransactionType transType,
            string identifer, bool chargeImmediately, bool runOnce)
        {
            var userService = m_registry.RequestModuleInterface<IUserAccountService> ();
            var user = userService.GetUserAccount (null, agentID);

            if (moneyModule != null) {
                if (chargeImmediately) {
                    bool success = moneyModule.Transfer (
                        (UUID)Constants.BankerUUID,            // pay the Banker
                        agentID,
                        amount,
                        description,
                        transType
                    );
                    if (!success) {
                        MainConsole.Instance.WarnFormat ("[Currency]: Unable to process {0} payment of {1}{2} from {3}",
                             description, currencySymbol, amount, user.Name);
                        return false;
                    }

                    MainConsole.Instance.WarnFormat ("[Currency]: Payment for {0} of {1}{2} from {3} has been paid",
                        description, currencySymbol, amount, user.Name);

                }

                if (!runOnce) {
                    // add a re-occurring scheduled payment
                    if (scheduler != null) {
                        string scid = UUID.Random ().ToString ();

                        OSDMap itemInfo = new OSDMap ();
                        itemInfo.Add ("AgentID", agentID);
                        itemInfo.Add ("Amount", amount);
                        itemInfo.Add ("Text", description);
                        itemInfo.Add ("Type", (int)transType);
                        itemInfo.Add ("SchedulerID", scid);

                        SchedulerItem item = new SchedulerItem (
                                             "ScheduledPayment " + identifer,                         // name
                                             OSDParser.SerializeJsonString (itemInfo),                // scheduled payment details
                                             false,                                                   // run once
                                             GetStipendPaytime (Constants.SCHEDULED_PAYMENTS_DELAY),  // next cycle + delay
                                             agentID);                                                // user to charge

                        // we need to use our own id here
                        item.id = scid;
                        scheduler.Save (item);
                    } else
                        MainConsole.Instance.WarnFormat ("[Currency]: Unable to add a new scheduled {0} payment of {1}{2} for {3}",
                            description, currencySymbol, amount, user.Name);
                }
            }
            return true;
        }
示例#42
0
        public Hashtable ProcessQueue(Hashtable request, UUID agentID, Caps caps)
        {
            // TODO: this has to be redone to not busy-wait (and block the thread),
            // TODO: as soon as we have a non-blocking way to handle HTTP-requests.

//            if (m_log.IsDebugEnabled)
//            {
//                String debug = "[EVENTQUEUE]: Got request for agent {0} in region {1} from thread {2}: [  ";
//                foreach (object key in request.Keys)
//                {
//                    debug += key.ToString() + "=" + request[key].ToString() + "  ";
//                }
//                m_log.DebugFormat(debug + "  ]", agentID, m_scene.RegionInfo.RegionName, System.Threading.Thread.CurrentThread.Name);
//            }

            Queue <OSD> queue   = TryGetQueue(agentID);
            OSD         element = queue.Dequeue(); // 15s timeout

            Hashtable responsedata = new Hashtable();

            int thisID = 0;

            lock (m_ids)
                thisID = m_ids[agentID];

            if (element == null)
            {
                //m_log.ErrorFormat("[EVENTQUEUE]: Nothing to process in " + m_scene.RegionInfo.RegionName);
                if (thisID == -1) // close-request
                {
                    m_log.ErrorFormat("[EVENTQUEUE]: 404 in " + m_scene.RegionInfo.RegionName);
                    responsedata["int_response_code"]   = 404; //501; //410; //404;
                    responsedata["content_type"]        = "text/plain";
                    responsedata["keepalive"]           = false;
                    responsedata["str_response_string"] = "Closed EQG";
                    return(responsedata);
                }
                responsedata["int_response_code"]     = 502;
                responsedata["content_type"]          = "text/plain";
                responsedata["keepalive"]             = false;
                responsedata["str_response_string"]   = "Upstream error: ";
                responsedata["error_status_text"]     = "Upstream error:";
                responsedata["http_protocol_version"] = "HTTP/1.0";
                return(responsedata);
            }

            OSDArray array = new OSDArray();

            if (element == null) // didn't have an event in 15s
            {
                // Send it a fake event to keep the client polling!   It doesn't like 502s like the proxys say!
                array.Add(EventQueueHelper.KeepAliveEvent());
                //m_log.DebugFormat("[EVENTQUEUE]: adding fake event for {0} in region {1}", agentID, m_scene.RegionInfo.RegionName);
            }
            else
            {
                array.Add(element);
                while (queue.Count > 0)
                {
                    array.Add(queue.Dequeue());
                    thisID++;
                }
            }

            OSDMap events = new OSDMap();

            events.Add("events", array);

            events.Add("id", new OSDInteger(thisID));
            lock (m_ids)
            {
                m_ids[agentID] = thisID + 1;
            }

            responsedata["int_response_code"]   = 200;
            responsedata["content_type"]        = "application/xml";
            responsedata["keepalive"]           = false;
            responsedata["str_response_string"] = OSDParser.SerializeLLSDXmlString(events);
            //m_log.DebugFormat("[EVENTQUEUE]: sending response for {0} in region {1}: {2}", agentID, m_scene.RegionInfo.RegionName, responsedata["str_response_string"]);

            return(responsedata);
        }
示例#43
0
 public OSD GetSerializationData(UUID itemID, UUID primID)
 {
     OSDMap data = new OSDMap();
     string key = MakeTimerKey(primID, itemID);
     TimerClass timer;
     if (Timers.TryGetValue(key, out timer))
     {
         data.Add("Interval", timer.interval);
         data.Add("Next", timer.next - Environment.TickCount);
     }
     return data;
 }
示例#44
0
        public Hashtable GetEvents(UUID requestID, UUID pAgentId, string request)
        {
            Queue <OSD> queue = TryGetQueue(pAgentId);
            OSD         element;

            lock (queue)
            {
                if (queue.Count == 0)
                {
                    return(NoEvents(requestID, pAgentId));
                }
                element = queue.Dequeue(); // 15s timeout
            }



            int thisID = 0;

            lock (m_ids)
                thisID = m_ids[pAgentId];

            OSDArray array = new OSDArray();

            if (element == null) // didn't have an event in 15s
            {
                // Send it a fake event to keep the client polling!   It doesn't like 502s like the proxys say!
                array.Add(EventQueueHelper.KeepAliveEvent());
                //m_log.DebugFormat("[EVENTQUEUE]: adding fake event for {0} in region {1}", pAgentId, m_scene.RegionInfo.RegionName);
            }
            else
            {
                array.Add(element);
                lock (queue)
                {
                    while (queue.Count > 0)
                    {
                        array.Add(queue.Dequeue());
                        thisID++;
                    }
                }
            }

            OSDMap events = new OSDMap();

            events.Add("events", array);

            events.Add("id", new OSDInteger(thisID));
            lock (m_ids)
            {
                m_ids[pAgentId] = thisID + 1;
            }
            Hashtable responsedata = new Hashtable();

            responsedata["int_response_code"]   = 200;
            responsedata["content_type"]        = "application/xml";
            responsedata["keepalive"]           = false;
            responsedata["reusecontext"]        = false;
            responsedata["str_response_string"] = OSDParser.SerializeLLSDXmlString(events);
            //m_log.DebugFormat("[EVENTQUEUE]: sending response for {0} in region {1}: {2}", pAgentId, m_scene.RegionInfo.RegionName, responsedata["str_response_string"]);
            return(responsedata);
        }