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(); } }
OSDMap GetParcelsByRegion (OSDMap map) { var resp = new OSDMap (); resp ["Parcels"] = new OSDArray (); resp ["Total"] = OSD.FromInteger (0); var directory = DataPlugins.RequestPlugin<IDirectoryServiceConnector> (); if (directory != null && map.ContainsKey ("Region") == true) { UUID regionID = UUID.Parse (map ["Region"]); UUID scopeID = map.ContainsKey ("ScopeID") ? UUID.Parse (map ["ScopeID"].ToString ()) : UUID.Zero; UUID owner = map.ContainsKey ("Owner") ? UUID.Parse (map ["Owner"].ToString ()) : UUID.Zero; uint start = map.ContainsKey ("Start") ? uint.Parse (map ["Start"].ToString ()) : 0; uint count = map.ContainsKey ("Count") ? uint.Parse (map ["Count"].ToString ()) : 10; ParcelFlags flags = map.ContainsKey ("Flags") ? (ParcelFlags)int.Parse (map ["Flags"].ToString ()) : ParcelFlags.None; ParcelCategory category = map.ContainsKey ("Category") ? (ParcelCategory)uint.Parse (map ["Flags"].ToString ()) : ParcelCategory.Any; uint total = directory.GetNumberOfParcelsByRegion (regionID, owner, flags, category); if (total > 0) { resp ["Total"] = OSD.FromInteger ((int)total); if (count == 0) { return resp; } List<LandData> regionParcels = directory.GetParcelsByRegion (start, count, regionID, owner, flags, category); OSDArray parcels = new OSDArray (regionParcels.Count); regionParcels.ForEach (delegate (LandData parcel) { parcels.Add (LandData2WebOSD (parcel)); }); resp ["Parcels"] = parcels; } } return resp; }
OSDMap GetAbuseReports (OSDMap map) { var resp = new OSDMap (); var areports = m_registry.RequestModuleInterface<IAbuseReports> (); int start = map ["Start"].AsInteger (); int count = map ["Count"].AsInteger (); bool active = map ["Active"].AsBoolean (); List<AbuseReport> arList = areports.GetAbuseReports (start, count, active); var AbuseReports = new OSDArray (); if (arList != null) { foreach (AbuseReport rpt in arList) { AbuseReports.Add (rpt.ToOSD ()); } } resp ["AbuseReports"] = AbuseReports; resp ["Start"] = OSD.FromInteger (start); resp ["Count"] = OSD.FromInteger (count); resp ["Active"] = OSD.FromBoolean (active); return resp; }
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(); } }
protected OSDMap OnMessageReceived(OSDMap message) { //If it is an async message request, make sure that the request is valid and check it if (message["Method"] == "AsyncMessageRequest") { try { OSDMap response = new OSDMap(); OSDArray array = new OSDArray(); if (m_regionMessages.ContainsKey(message["RegionHandle"].AsULong())) { foreach (OSDMap asyncMess in m_regionMessages[message["RegionHandle"].AsULong()]) { array.Add(asyncMess); } m_regionMessages.Remove(message["RegionHandle"].AsULong()); } response["Messages"] = array; return response; } catch { } } return null; }
public OSDMap PackAgentCircuitData() { OSDMap args = new OSDMap(); args["agent_id"] = OSD.FromUUID(AgentID); args["base_folder"] = OSD.FromUUID(BaseFolder); args["caps_path"] = OSD.FromString(CapsPath); OSDArray childrenSeeds = new OSDArray(ChildrenCapSeeds.Count); foreach (KeyValuePair<ulong, string> kvp in ChildrenCapSeeds) { OSDMap pair = new OSDMap(); pair["handle"] = OSD.FromString(kvp.Key.ToString()); pair["seed"] = OSD.FromString(kvp.Value); childrenSeeds.Add(pair); } if (ChildrenCapSeeds.Count > 0) args["children_seeds"] = childrenSeeds; args["child"] = OSD.FromBoolean(child); args["circuit_code"] = OSD.FromString(circuitcode.ToString()); args["first_name"] = OSD.FromString(firstname); args["last_name"] = OSD.FromString(lastname); args["inventory_folder"] = OSD.FromUUID(InventoryFolder); args["secure_session_id"] = OSD.FromUUID(SecureSessionID); args["session_id"] = OSD.FromUUID(SessionID); args["start_pos"] = OSD.FromString(startpos.ToString()); return args; }
public OSD ToOSD() { OSDArray array = new OSDArray(4) {null, null, null, null}; array[0] = new OSDMap {{"regionID", RegionID}}; Cycle.ToOSD(ref array); Water.ToOSD(ref array); return array; }
public override OSDMap ToOSD() { OSDMap map = new OSDMap(); map["Items"] = new OSDArray(Items.ConvertAll<OSD>((item) => item.ToOSD())); map["Folders"] = new OSDArray(Folders.ConvertAll<OSD>((folder) => folder.ToOSD())); map["UserID"] = UserID; return map; }
public OSDMap ToOSD() { OSDMap map = new OSDMap(); map["AuctionStart"] = AuctionStart; map["AuctionLength"] = AuctionLength; map["Description"] = Description; OSDArray array = new OSDArray(); foreach (AuctionBid bid in AuctionBids) array.Add(bid.ToOSD()); map["AuctionBids"] = array; return map; }
public override OSDMap ToOSD() { OSDMap result = new OSDMap(); foreach (KeyValuePair<ulong, List<mapItemReply>> kvp in items) { OSDArray array = new OSDArray(); foreach (mapItemReply item in kvp.Value) { array.Add(item.ToOSD()); } result[kvp.Key.ToString()] = array; } return result; }
/// <summary> /// This adds the entire region into the search database /// </summary> /// <param name="args"></param> public void AddRegion(List<LandData> parcels) { OSDMap mess = new OSDMap(); OSDArray requests = new OSDArray(); foreach (LandData data in parcels) requests.Add(data.ToOSD()); mess["Requests"] = requests; mess["Method"] = "addregion"; List<string> m_ServerURIs = m_registry.RequestModuleInterface<IConfigurationService>().FindValueOf("RemoteServerURI"); foreach (string m_ServerURI in m_ServerURIs) { WebUtils.PostToService (m_ServerURI + "osd", mess, false, false); } }
byte[] ProductInfoRequestCAP(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { //OSDMap data = m_service.GetCAPS (); var data = new OSDArray(); var mf = new OSDMap (); mf ["name"] = "mainland_full"; mf ["description"] = "Mainland / Full Region"; mf ["sku"] = "001"; data.Add(mf); var mh = new OSDMap (); mh ["name"] = "mainland_homestead"; mh ["description"] = "Mainland / Homestead"; mh ["sku"] = "011"; data.Add(mh); var mo = new OSDMap (); mo ["name"] = "mainland_openspace"; mo ["description"] = "Mainland / Openspace"; mo ["sku"] = "021"; data.Add(mo); var ef = new OSDMap (); ef ["name"] = "estate_full"; ef ["description"] = "Estate / Full Region"; ef ["sku"] = "002"; data.Add(ef); var eh = new OSDMap (); eh ["name"] = "estate_homestead"; eh ["description"] = "Estate / Homestead"; eh ["sku"] = "012"; data.Add(eh); var eo = new OSDMap (); eo ["name"] = "estate_openspace"; eo ["description"] = "Estate / Openspace"; eo ["sku"] = "022"; data.Add(eo); var wh = new OSDMap (); wh ["name"] = "universe_homes"; wh ["description"] = "Universe Homes / Full Region"; wh ["sku"] = "101"; data.Add(wh); return OSDParser.SerializeLLSDXmlBytes (data); }
public OSDArray ToOSD(ref OSDArray array) { OSDMap settings = new OSDMap(); OSDArray cycle = new OSDArray(); foreach (KeyValuePair<string, SkyData> kvp in DataSettings) { cycle.Add(new OSDArray {kvp.Key, kvp.Value.preset_name}); settings[kvp.Value.preset_name] = kvp.Value.ToOSD(); } array[1] = cycle; array[2] = settings; return array; }
void LoadFromOSD(ConcurrentDictionary<string, FilterItem> items, OSDArray filters) { try { foreach (var filter in filters) { if (filter is OSDMap) { var item = FilterItem.FromOSD((OSDMap)filter); items[item.Name] = item; } } } catch { } }
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); }
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; }
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); }
public static OSD EnableSimulator (ulong handle, byte[] IPAddress, int Port, int RegionSizeX, int RegionSizeY) { OSDMap llsdSimInfo = new OSDMap (3) { { "Handle", new OSDBinary (ulongToByteArray (handle)) }, { "IP", new OSDBinary (IPAddress) }, { "Port", new OSDInteger (Port) }, { "RegionSizeX", OSD.FromUInteger ((uint)RegionSizeX) }, { "RegionSizeY", OSD.FromUInteger ((uint)RegionSizeY) } }; OSDArray arr = new OSDArray (1) { llsdSimInfo }; OSDMap llsdBody = new OSDMap (1) { { "SimulatorInfo", arr } }; return buildEvent ("EnableSimulator", llsdBody); }
OSDMap GetRegions (OSDMap map) { OSDMap resp = new OSDMap (); RegionFlags type = map.Keys.Contains ("RegionFlags") ? (RegionFlags)map ["RegionFlags"].AsInteger () : RegionFlags.RegionOnline; int start = map.Keys.Contains ("Start") ? map ["Start"].AsInteger () : 0; if (start < 0) { start = 0; } int count = map.Keys.Contains ("Count") ? map ["Count"].AsInteger () : 10; if (count < 0) { count = 1; } var regiondata = DataPlugins.RequestPlugin<IRegionData> (); Dictionary<string, bool> sort = new Dictionary<string, bool> (); string [] supportedSort = { "SortRegionName", "SortLocX", "SortLocY" }; foreach (string sortable in supportedSort) { if (map.ContainsKey (sortable)) { sort [sortable.Substring (4)] = map [sortable].AsBoolean (); } } List<GridRegion> regions = regiondata.Get (type, sort); OSDArray Regions = new OSDArray (); if (start < regions.Count) { int i = 0; int j = regions.Count <= (start + count) ? regions.Count : (start + count); for (i = start; i < j; ++i) { Regions.Add (regions [i].ToOSD ()); } } resp ["Start"] = OSD.FromInteger (start); resp ["Count"] = OSD.FromInteger (count); resp ["Total"] = OSD.FromInteger (regions.Count); resp ["Regions"] = Regions; return resp; }
OSDMap GetGroups (OSDMap map) { var resp = new OSDMap (); var start = map.ContainsKey ("Start") ? map ["Start"].AsUInteger () : 0; resp ["Start"] = start; resp ["Total"] = 0; var groups = DataPlugins.RequestPlugin<IGroupsServiceConnector> (); var Groups = new OSDArray (); if (groups != null) { var sort = new Dictionary<string, bool> (); var boolFields = new Dictionary<string, bool> (); if (map.ContainsKey ("Sort") && map ["Sort"].Type == OSDType.Map) { var fields = (OSDMap)map ["Sort"]; foreach (string field in fields.Keys) { sort [field] = int.Parse (fields [field]) != 0; } } if (map.ContainsKey ("BoolFields") && map ["BoolFields"].Type == OSDType.Map) { var fields = (OSDMap)map ["BoolFields"]; foreach (string field in fields.Keys) { boolFields [field] = int.Parse (fields [field]) != 0; } } var reply = groups.GetGroupRecords ( AdminAgentID, start, map.ContainsKey ("Count") ? map ["Count"].AsUInteger () : 10, sort, boolFields ); if (reply.Count > 0) { foreach (GroupRecord groupReply in reply) { Groups.Add (GroupRecord2OSDMap (groupReply)); } } resp ["Total"] = groups.GetNumberOfGroups (AdminAgentID, boolFields); } resp ["Groups"] = Groups; return resp; }
public OSDMap ToOSD() { OSDMap map = new OSDMap(); map["CurrentAnimationPosition"] = CurrentAnimationPosition; map["CurrentMode"] = (int)CurrentMode; OSDArray times = new OSDArray(); foreach (int time in TimeList) times.Add(time); map["TimeList"] = times; OSDArray positions = new OSDArray(); foreach (Vector3 v in PositionList) positions.Add(v); map["PositionList"] = positions; OSDArray rotations = new OSDArray(); foreach (Quaternion v in RotationList) rotations.Add(v); map["RotationList"] = rotations; return map; }
OSDMap GetAvatarArchives (OSDMap map) { var resp = new OSDMap (); var temp = m_registry.RequestModuleInterface<IAvatarAppearanceArchiver> ().GetAvatarArchives (); var names = new OSDArray (); var snapshot = new OSDArray (); MainConsole.Instance.DebugFormat ("[API] {0} avatar archives found", temp.Count); foreach (AvatarArchive a in temp) { names.Add (OSD.FromString (a.FolderName)); //names.Add(OSD.FromString(a.FileName)); snapshot.Add (OSD.FromUUID (a.Snapshot)); } resp ["names"] = names; resp ["snapshot"] = snapshot; return resp; }
OSDMap GetClassifieds (OSDMap map) { var classifiedListVars = new List<Dictionary<string, object>> (); var resp = new OSDMap (); var directory = DataPlugins.RequestPlugin<IDirectoryServiceConnector> (); if (directory != null) { var classifieds = new List<Classified> (); int category = map.Keys.Contains ("category") ? map ["category"].AsInteger () : (int)DirectoryManager.ClassifiedCategories.Any; int maturity = map.Keys.Contains ("maturity") ? map ["maturity"].AsInteger () : (int)DirectoryManager.ClassifiedFlags.None; classifieds = directory.GetAllClassifieds (category, (uint)maturity); if (classifieds.Count > 0) { // build a list of classifieds var clarry = new OSDArray (); foreach (var classified in classifieds) clarry.Add (classified.ToOSD ()); resp ["classifieds"] = clarry; resp ["count"] = clarry.Count.ToString (); return resp; } } // no classifieds resp ["classifieds"] = new OSDArray (); resp ["count"] = "0"; return resp; }
public void FromOSD(OSDArray osd) { OSDArray array = osd as OSDArray; OSDArray settingsArray = array[1] as OSDArray; OSDMap windlightSettingsArray = array[2] as OSDMap; foreach (OSD setting in settingsArray) { OSDArray innerSetting = setting as OSDArray; string key = innerSetting[0]; string name = innerSetting[1]; OSDMap settings = windlightSettingsArray[name] as OSDMap; SkyData skySettings = new SkyData(); skySettings.FromOSD(name, settings); DataSettings[key] = skySettings; } if (DataSettings.Count == 1 && DataSettings.ContainsKey("-1")) IsStaticDayCycle = true; }
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; }
OSDMap GetEvents(OSDMap map) { var resp = new OSDMap (); var directory = DataPlugins.RequestPlugin<IDirectoryServiceConnector> (); if (directory != null) { var events = new List<EventData> (); var timeframe = map.Keys.Contains ("timeframe") ? map ["timeframe"].AsInteger () : 24; var category = map.Keys.Contains ("category") ? map ["category"].AsInteger () :(int)DirectoryManager.EventCategories.All; int eventMaturity = map.Keys.Contains ("maturity") ? map ["maturity"].AsInteger () : Util.ConvertEventMaturityToDBMaturity (DirectoryManager.EventFlags.PG); events = directory.GetAllEvents(timeframe, category , eventMaturity); if (events.Count > 0) { // build a list of classifieds var evarry = new OSDArray (); foreach (var evnt in events) evarry.Add (evnt.ToOSD ()); resp ["events"] = evarry; resp ["count"] = evarry.Count.ToString (); return resp; } } // no eventss resp ["events"] = new OSDArray (); resp ["count"] = "0"; return resp; }
/// <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; }
public OSDMap Serialize() { OSDMap map = new OSDMap(); if (MessageSessions.Count > 0) { OSDArray messageArray = new OSDArray(MessageSessions.Count); foreach (KeyValuePair<string, FilterEntryOptions> kvp in MessageSessions) { OSDMap sessionMap = new OSDMap(4); sessionMap["Name"] = OSD.FromString(kvp.Key); sessionMap["Type"] = OSD.FromString(kvp.Value.Type); sessionMap["Capture"] = OSD.FromBoolean(kvp.Value.Checked); sessionMap["Group"] = OSD.FromString(kvp.Value.Group); messageArray.Add(sessionMap); } map.Add("message_sessions", messageArray); } if (PacketSessions.Count > 0) { OSDArray packetArray = new OSDArray(PacketSessions.Count); foreach (KeyValuePair<string, FilterEntryOptions> kvp in PacketSessions) { OSDMap sessionMap = new OSDMap(4); sessionMap["Name"] = OSD.FromString(kvp.Key); sessionMap["Type"] = OSD.FromString(kvp.Value.Type); sessionMap["Capture"] = OSD.FromBoolean(kvp.Value.Checked); sessionMap["Group"] = OSD.FromString(kvp.Value.Group); packetArray.Add(sessionMap); } map.Add("packet_sessions", packetArray); } map.Add("CaptureStatistics", OSD.FromBoolean(StatisticsEnabled)); map.Add("SaveProfileOnExit", OSD.FromBoolean(SaveSessionOnExit)); map.Add("AutoCheckNewCaps", OSD.FromBoolean(AutoCheckNewCaps)); map.Add("FileVersion", OSD.FromInteger(FileVersion)); return map; }
public static OSD GetLLSD(Packet packet) { OSDMap body = new OSDMap(); Type type = packet.GetType(); foreach (FieldInfo field in type.GetFields()) { if (field.IsPublic) { Type blockType = field.FieldType; if (blockType.IsArray) { object blockArray = field.GetValue(packet); Array array = (Array)blockArray; OSDArray blockList = new OSDArray(array.Length); IEnumerator ie = array.GetEnumerator(); while (ie.MoveNext()) { object block = ie.Current; blockList.Add(BuildLLSDBlock(block)); } body[field.Name] = blockList; } else { object block = field.GetValue(packet); body[field.Name] = BuildLLSDBlock(block); } } } return body; }
public virtual byte[] FetchInventoryReply(OSDArray fetchRequest, UUID agentID, UUID forceOwnerID, UUID libraryOwnerID) { LLSDSerializationDictionary contents = new LLSDSerializationDictionary(); contents.WriteStartMap("llsd"); //Start llsd contents.WriteKey("folders"); //Start array items contents.WriteStartArray("folders"); //Start array folders foreach (OSD m in fetchRequest) { contents.WriteStartMap("internalContents"); //Start internalContents kvp OSDMap invFetch = (OSDMap)m; //UUID agent_id = invFetch["agent_id"].AsUUID(); UUID owner_id = invFetch["owner_id"].AsUUID(); UUID folder_id = invFetch["folder_id"].AsUUID(); bool fetch_folders = invFetch["fetch_folders"].AsBoolean(); bool fetch_items = invFetch["fetch_items"].AsBoolean(); //int sort_order = invFetch["sort_order"].AsInteger(); //Set the normal stuff contents["agent_id"] = agentID; contents["owner_id"] = owner_id; contents["folder_id"] = folder_id; int count = 0; string query = ""; if (fetch_items) { contents.WriteKey("items"); //Start array items contents.WriteStartArray("items"); List <UUID> moreLinkedItems = new List <UUID>(); bool addToCount = true; query = string.Format("where {0} = '{1}'", "parentFolderID", folder_id); redoQuery: using (DataReaderConnection retVal = GD.QueryData(query, m_itemsrealm, "*")) { try { while (retVal.DataReader.Read()) { contents.WriteStartMap("item"); //Start item kvp UUID assetID = UUID.Parse(retVal.DataReader["assetID"].ToString()); contents["asset_id"] = assetID; contents["name"] = retVal.DataReader["inventoryName"].ToString(); contents["desc"] = retVal.DataReader["inventoryDescription"].ToString(); contents.WriteKey("permissions"); //Start permissions kvp contents.WriteStartMap("permissions"); contents["group_id"] = UUID.Parse(retVal.DataReader["groupID"].ToString()); contents["is_owner_group"] = int.Parse(retVal.DataReader["groupOwned"].ToString()) == 1; contents["group_mask"] = uint.Parse(retVal.DataReader["inventoryGroupPermissions"].ToString()); contents["owner_id"] = forceOwnerID == UUID.Zero ? UUID.Parse(retVal.DataReader["avatarID"].ToString()) : forceOwnerID; contents["last_owner_id"] = UUID.Parse(retVal.DataReader["avatarID"].ToString()); contents["next_owner_mask"] = uint.Parse(retVal.DataReader["inventoryNextPermissions"].ToString()); contents["owner_mask"] = uint.Parse(retVal.DataReader["inventoryCurrentPermissions"].ToString()); UUID creator; if (UUID.TryParse(retVal.DataReader["creatorID"].ToString(), out creator)) { contents["creator_id"] = creator; } else { contents["creator_id"] = UUID.Zero; } contents["base_mask"] = uint.Parse(retVal.DataReader["inventoryBasePermissions"].ToString()); contents["everyone_mask"] = uint.Parse(retVal.DataReader["inventoryEveryOnePermissions"].ToString()); contents.WriteEndMap(/*Permissions*/); contents.WriteKey("sale_info"); //Start permissions kvp contents.WriteStartMap("sale_info"); //Start sale_info kvp contents["sale_price"] = int.Parse(retVal.DataReader["salePrice"].ToString()); switch (byte.Parse(retVal.DataReader["saleType"].ToString())) { default: contents["sale_type"] = "not"; break; case 1: contents["sale_type"] = "original"; break; case 2: contents["sale_type"] = "copy"; break; case 3: contents["sale_type"] = "contents"; break; } contents.WriteEndMap(/*sale_info*/); contents["created_at"] = int.Parse(retVal.DataReader["creationDate"].ToString()); contents["flags"] = uint.Parse(retVal.DataReader["flags"].ToString()); UUID inventoryID = UUID.Parse(retVal.DataReader["inventoryID"].ToString()); contents["item_id"] = inventoryID; contents["parent_id"] = UUID.Parse(retVal.DataReader["parentFolderID"].ToString()); UUID avatarID = forceOwnerID == UUID.Zero ? UUID.Parse(retVal.DataReader["avatarID"].ToString()) : forceOwnerID; contents["agent_id"] = avatarID; AssetType assetType = (AssetType)int.Parse(retVal.DataReader["assetType"].ToString()); if (assetType == AssetType.Link) { moreLinkedItems.Add(assetID); } if (assetType == AssetType.Unknown) { assetType = AssetType.Link; } contents["type"] = Utils.AssetTypeToString((AssetType)Util.CheckMeshType((sbyte)assetType)); InventoryType invType = (InventoryType)int.Parse(retVal.DataReader["invType"].ToString()); contents["inv_type"] = Utils.InventoryTypeToString(invType); if ((int)invType == -1) { //Asset problem, fix it, it's supposed to be 0 List <InventoryItemBase> itms = GetItems(agentID, new string[] { "inventoryID", "avatarID" }, new string[] { inventoryID.ToString(), avatarID.ToString() }); itms[0].InvType = 0; StoreItem(itms[0]); } if (addToCount) { count++; } contents.WriteEndMap(/*"item"*/); //end array items } } catch { } finally { GD.CloseDatabase(retVal); } } if (moreLinkedItems.Count > 0) { addToCount = false; query = "where ("; query = moreLinkedItems.Aggregate(query, (current, t) => current + string.Format("{0} = '{1}' or ", "inventoryID", t)); query = query.Remove(query.Length - 4, 4); query += ")"; moreLinkedItems.Clear(); goto redoQuery; } contents.WriteEndArray(/*"items"*/); //end array items } contents.WriteStartArray("categories"); //We don't send any folders int version = 0; QueryFilter filter = new QueryFilter(); filter.andFilters["folderID"] = folder_id; List <string> versionRetVal = GD.Query(new[] { "version", "type" }, m_foldersrealm, filter, null, null, null); if (versionRetVal.Count > 0) { version = int.Parse(versionRetVal[0]); if (fetch_folders) { if (int.Parse(versionRetVal[1]) == (int)FolderType.Trash || int.Parse(versionRetVal[1]) == (int)FolderType.CurrentOutfit || int.Parse(versionRetVal[1]) == (int)AssetType.LinkFolder) { //If it is the trash folder, we need to send its descendents, because the viewer wants it query = string.Format("where {0} = '{1}' and {2} = '{3}'", "parentFolderID", folder_id, "agentID", agentID); using (DataReaderConnection retVal = GD.QueryData(query, m_foldersrealm, "*")) { try { while (retVal.DataReader.Read()) { contents.WriteStartMap("folder"); //Start item kvp contents["folder_id"] = UUID.Parse(retVal.DataReader["folderID"].ToString()); contents["parent_id"] = UUID.Parse(retVal.DataReader["parentFolderID"].ToString()); contents["name"] = retVal.DataReader["folderName"].ToString(); int type = int.Parse(retVal.DataReader["type"].ToString()); contents["type"] = type; contents["preferred_type"] = type; count++; contents.WriteEndMap(/*"folder"*/); //end array items } } catch { } finally { GD.CloseDatabase(retVal); } } } } } contents.WriteEndArray(/*"categories"*/); contents["descendents"] = count; contents["version"] = version; //Now add it to the folder array contents.WriteEndMap(); //end array internalContents } contents.WriteEndArray(); //end array folders contents.WriteEndMap(/*"llsd"*/); //end llsd try { return(contents.GetSerializer()); } finally { contents = null; } }
OSDArray ParseLLSDInventoryItems(IDataReader retVal) { OSDArray array = new OSDArray(); while (retVal.Read()) { OSDMap item = new OSDMap(); OSDMap permissions = new OSDMap(); item["asset_id"] = UUID.Parse(retVal["assetID"].ToString()); item["name"] = retVal["inventoryName"].ToString(); item["desc"] = retVal["inventoryDescription"].ToString(); permissions["next_owner_mask"] = uint.Parse(retVal["inventoryNextPermissions"].ToString()); permissions["owner_mask"] = uint.Parse(retVal["inventoryCurrentPermissions"].ToString()); UUID creator; if (UUID.TryParse(retVal["creatorID"].ToString(), out creator)) { permissions["creator_id"] = creator; } else { permissions["creator_id"] = UUID.Zero; } permissions["base_mask"] = uint.Parse(retVal["inventoryBasePermissions"].ToString()); permissions["everyone_mask"] = uint.Parse(retVal["inventoryEveryOnePermissions"].ToString()); OSDMap sale_info = new OSDMap(); sale_info["sale_price"] = int.Parse(retVal["salePrice"].ToString()); switch (byte.Parse(retVal["saleType"].ToString())) { default: sale_info["sale_type"] = "not"; break; case 1: sale_info["sale_type"] = "original"; break; case 2: sale_info["sale_type"] = "copy"; break; case 3: sale_info["sale_type"] = "contents"; break; } item["sale_info"] = sale_info; item["created_at"] = int.Parse(retVal["creationDate"].ToString()); permissions["group_id"] = UUID.Parse(retVal["groupID"].ToString()); permissions["is_owner_group"] = int.Parse(retVal["groupOwned"].ToString()) == 1; item["flags"] = uint.Parse(retVal["flags"].ToString()); item["item_id"] = UUID.Parse(retVal["inventoryID"].ToString()); item["parent_id"] = UUID.Parse(retVal["parentFolderID"].ToString()); permissions["group_mask"] = uint.Parse(retVal["inventoryGroupPermissions"].ToString()); item["agent_id"] = UUID.Parse(retVal["avatarID"].ToString()); permissions["owner_id"] = item["agent_id"]; permissions["last_owner_id"] = item["agent_id"]; item["type"] = Utils.AssetTypeToString((AssetType)int.Parse(retVal["assetType"].ToString())); item["inv_type"] = Utils.InventoryTypeToString((InventoryType)int.Parse(retVal["invType"].ToString())); item["permissions"] = permissions; array.Add(item); } //retVal.Close(); return(array); }
public OSDArray GetUserImageAssets(UUID avatarId) { OSDArray data = new OSDArray(); string query = "SELECT \"snapshotuuid\" FROM {0} WHERE \"creatoruuid\" = :Id"; try { using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) { dbcon.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format(query, "\"classifieds\""), dbcon)) { cmd.Parameters.Add(m_database.CreateParameter("Id", avatarId)); using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if (reader.HasRows) { while (reader.Read()) { data.Add(new OSDString(reader["snapshotuuid"].ToString())); } } } } dbcon.Close(); dbcon.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format(query, "\"userpicks\""), dbcon)) { cmd.Parameters.Add(m_database.CreateParameter("Id", avatarId)); using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if (reader.HasRows) { while (reader.Read()) { data.Add(new OSDString(reader["snapshotuuid"].ToString())); } } } } dbcon.Close(); dbcon.Open(); query = "SELECT \"profileImage\", \"profileFirstImage\" FROM \"userprofile\" WHERE \"useruuid\" = :Id"; using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format(query, "\"userpicks\""), dbcon)) { cmd.Parameters.Add(m_database.CreateParameter("Id", avatarId)); using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if (reader.HasRows) { while (reader.Read()) { data.Add(new OSDString(reader["profileImage"].ToString())); data.Add(new OSDString(reader["profileFirstImage"].ToString())); } } } } } } catch (Exception e) { m_log.Error("[PROFILES_DATA]: GetUserImageAssets exception ", e); } return(data); }
/// <summary> /// Unpack agent circuit data map into an AgentCiruitData object /// </summary> /// <param name="args"></param> public void UnpackAgentCircuitData(OSDMap args) { if (args["agent_id"] != null) { AgentID = args["agent_id"].AsUUID(); } if (args["base_folder"] != null) { BaseFolder = args["base_folder"].AsUUID(); } if (args["caps_path"] != null) { CapsPath = args["caps_path"].AsString(); } if ((args["children_seeds"] != null) && (args["children_seeds"].Type == OSDType.Array)) { OSDArray childrenSeeds = (OSDArray)(args["children_seeds"]); ChildrenCapSeeds = new Dictionary <ulong, string>(); foreach (OSD o in childrenSeeds) { if (o.Type == OSDType.Map) { ulong handle = 0; string seed = ""; OSDMap pair = (OSDMap)o; if (pair["handle"] != null) { if (!UInt64.TryParse(pair["handle"].AsString(), out handle)) { continue; } } if (pair["seed"] != null) { seed = pair["seed"].AsString(); } if (!ChildrenCapSeeds.ContainsKey(handle)) { ChildrenCapSeeds.Add(handle, seed); } } } } else { ChildrenCapSeeds = new Dictionary <ulong, string>(); } if (args["child"] != null) { child = args["child"].AsBoolean(); } if (args["circuit_code"] != null) { UInt32.TryParse(args["circuit_code"].AsString(), out circuitcode); } if (args["first_name"] != null) { firstname = args["first_name"].AsString(); } if (args["last_name"] != null) { lastname = args["last_name"].AsString(); } if (args["inventory_folder"] != null) { InventoryFolder = args["inventory_folder"].AsUUID(); } if (args["secure_session_id"] != null) { SecureSessionID = args["secure_session_id"].AsUUID(); } if (args["session_id"] != null) { SessionID = args["session_id"].AsUUID(); } if (args["service_session_id"] != null) { ServiceSessionID = args["service_session_id"].AsString(); } if (args["client_ip"] != null) { IPAddress = args["client_ip"].AsString(); } if (args["viewer"] != null) { Viewer = args["viewer"].AsString(); } if (args["channel"] != null) { Channel = args["channel"].AsString(); } if (args["mac"] != null) { Mac = args["mac"].AsString(); } if (args["id0"] != null) { Id0 = args["id0"].AsString(); } if (args["start_pos"] != null) { Vector3.TryParse(args["start_pos"].AsString(), out startpos); } //m_log.InfoFormat("[AGENTCIRCUITDATA]: agentid={0}, child={1}, startpos={2}", AgentID, child, startpos); try { // Unpack various appearance elements Appearance = new AvatarAppearance(); // Eventually this code should be deprecated, use full appearance // packing in packed_appearance if (args["appearance_serial"] != null) { Appearance.Serial = args["appearance_serial"].AsInteger(); } if (args.ContainsKey("packed_appearance") && (args["packed_appearance"].Type == OSDType.Map)) { Appearance.Unpack((OSDMap)args["packed_appearance"]); // m_log.InfoFormat("[AGENTCIRCUITDATA] unpacked appearance"); } else { m_log.Warn("[AGENTCIRCUITDATA]: failed to find a valid packed_appearance"); } } catch (Exception e) { m_log.ErrorFormat("[AGENTCIRCUITDATA] failed to unpack appearance; {0}", e.Message); } ServiceURLs = new Dictionary <string, object>(); // Try parse the new way, OSDMap if (args.ContainsKey("serviceurls") && args["serviceurls"] != null && (args["serviceurls"]).Type == OSDType.Map) { OSDMap urls = (OSDMap)(args["serviceurls"]); foreach (KeyValuePair <String, OSD> kvp in urls) { ServiceURLs[kvp.Key] = kvp.Value.AsString(); //System.Console.WriteLine("XXX " + kvp.Key + "=" + ServiceURLs[kvp.Key]); } } // else try the old way, OSDArray // OBSOLETE -- soon to be deleted else if (args.ContainsKey("service_urls") && args["service_urls"] != null && (args["service_urls"]).Type == OSDType.Array) { OSDArray urls = (OSDArray)(args["service_urls"]); for (int i = 0; i < urls.Count / 2; i++) { ServiceURLs[urls[i * 2].AsString()] = urls[(i * 2) + 1].AsString(); //System.Console.WriteLine("XXX " + urls[i * 2].AsString() + "=" + urls[(i * 2) + 1].AsString()); } } }
public void RenderMaterialsPostCap(IOSHttpRequest request, IOSHttpResponse response, UUID agentID) { OSDMap req; try { req = (OSDMap)OSDParser.DeserializeLLSDXml(request.InputStream); } catch { response.StatusCode = (int)HttpStatusCode.BadRequest; return; } OSDArray respArr = new OSDArray(); OSD tmpOSD; if (req.TryGetValue("Zipped", out tmpOSD)) { OSD osd = null; byte[] inBytes = tmpOSD.AsBinary(); try { osd = ZDecompressBytesToOsd(inBytes); if (osd != null && osd is OSDArray) { foreach (OSD elem in (OSDArray)osd) { try { UUID id = new UUID(elem.AsBinary(), 0); lock (materialslock) { if (m_Materials.ContainsKey(id)) { OSDMap matMap = new OSDMap(); matMap["ID"] = OSD.FromBinary(id.GetBytes()); matMap["Material"] = m_Materials[id].toOSD(); respArr.Add(matMap); } else { m_log.Warn("[Materials]: request for unknown material ID: " + id.ToString()); // Theoretically we could try to load the material from the assets service, // but that shouldn't be necessary because the viewer should only request // materials that exist in a prim on the region, and all of these materials // are already stored in m_regionMaterials. } } } catch (Exception e) { m_log.Error("Error getting materials in response to viewer request", e); continue; } } } } catch (Exception e) { m_log.Warn("[Materials]: exception decoding zipped CAP payload ", e); response.StatusCode = (int)HttpStatusCode.BadRequest; return; } } OSDMap resp = new OSDMap(); resp["Zipped"] = ZCompressOSD(respArr, false); response.RawBuffer = Encoding.UTF8.GetBytes(OSDParser.SerializeLLSDXmlString(resp)); //m_log.Debug("[Materials]: cap request: " + request); //m_log.Debug("[Materials]: cap request (zipped portion): " + ZippedOsdBytesToString(req["Zipped"].AsBinary())); //m_log.Debug("[Materials]: cap response: " + response); }
void RequestCompletedHandler(HttpWebRequest request, HttpWebResponse response, byte[] responseData, Exception error) { // We don't care about this request now that it has completed _Request = null; OSDArray events = null; int ack = 0; if (responseData != null) { _errorCount = 0; // Got a response OSDMap result = OSDParser.DeserializeLLSDXml(responseData) as OSDMap; if (result != null) { events = result["events"] as OSDArray; ack = result["id"].AsInteger(); } else { Logger.Log("Got an unparseable response from the event queue: \"" + System.Text.Encoding.UTF8.GetString(responseData) + "\"", Helpers.LogLevel.Warning); } } else if (error != null) { #region Error handling HttpStatusCode code = HttpStatusCode.OK; if (error is WebException) { WebException webException = (WebException)error; if (webException.Response != null) { code = ((HttpWebResponse)webException.Response).StatusCode; } else if (webException.Status == WebExceptionStatus.RequestCanceled) { goto HandlingDone; } } if (error is WebException && ((WebException)error).Response != null) { code = ((HttpWebResponse)((WebException)error).Response).StatusCode; } if (code == HttpStatusCode.NotFound || code == HttpStatusCode.Gone) { Logger.Log(String.Format("Closing event queue at {0} due to missing caps URI", _Address), Helpers.LogLevel.Info); _Running = false; _Dead = true; } else if (code == HttpStatusCode.BadGateway) { // This is not good (server) protocol design, but it's normal. // The EventQueue server is a proxy that connects to a Squid // cache which will time out periodically. The EventQueue server // interprets this as a generic error and returns a 502 to us // that we ignore } else { ++_errorCount; // Try to log a meaningful error message if (code != HttpStatusCode.OK) { Logger.Log(String.Format("Unrecognized caps connection problem from {0}: {1}", _Address, code), Helpers.LogLevel.Warning); } else if (error.InnerException != null) { Logger.Log(String.Format("Unrecognized internal caps exception from {0}: {1}", _Address, error.InnerException.Message), Helpers.LogLevel.Warning); } else { Logger.Log(String.Format("Unrecognized caps exception from {0}: {1}", _Address, error.Message), Helpers.LogLevel.Warning); } } #endregion Error handling } else { ++_errorCount; Logger.Log("No response from the event queue but no reported error either", Helpers.LogLevel.Warning); } HandlingDone: #region Resume the connection if (_Running) { OSDMap osdRequest = new OSDMap(); if (ack != 0) { osdRequest["ack"] = OSD.FromInteger(ack); } else { osdRequest["ack"] = new OSD(); } osdRequest["done"] = OSD.FromBoolean(_Dead); byte[] postData = OSDParser.SerializeLLSDXmlBytes(osdRequest); if (_errorCount > 0) // Exponentially back off, so we don't hammer the CPU { Thread.Sleep(_random.Next(500 + (int)Math.Pow(2, _errorCount))); } // Resume the connection. The event handler for the connection opening // just sets class _Request variable to the current HttpWebRequest CapsBase.UploadDataAsync(_Address, null, "application/xml", postData, REQUEST_TIMEOUT, delegate(HttpWebRequest newRequest) { _Request = newRequest; }, null, RequestCompletedHandler); // If the event queue is dead at this point, turn it off since // that was the last thing we want to do if (_Dead) { _Running = false; Logger.DebugLog("Sent event queue shutdown message"); } } #endregion Resume the connection #region Handle incoming events if (OnEvent != null && events != null && events.Count > 0) { // Fire callbacks for each event received foreach (OSDMap evt in events) { string msg = evt["message"].AsString(); OSDMap body = (OSDMap)evt["body"]; try { OnEvent(msg, body); } catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, ex); } } } #endregion Handle incoming events }
public void Initialize(ISimulationBase openSim) { try { //Check whether this is enabled IConfig updateConfig = openSim.ConfigSource.Configs["Update"]; if (updateConfig == null || updateConfig.GetString("Module", string.Empty) != Name || !updateConfig.GetBoolean("Enabled", false)) { return; } InfoMsg("Checking for updates..."); string WebSite = m_urlToCheckForUpdates; // Call the github API OSD data = OSDParser.DeserializeJson(Utilities.ReadExternalWebsite(WebSite)); if (data.Type != OSDType.Array) { ErrorMsg("Failed to get downloads from github API."); return; } OSDArray JsonData = (OSDArray)data; if (JsonData.Count == 0) { ErrorMsg("No downloads found."); return; } else { TraceMsg(JsonData.Count + " downloads found, parsing."); } SortedDictionary <Version, OSDMap> releases = new SortedDictionary <Version, OSDMap>(); foreach (OSD map in JsonData) { if (map.Type == OSDType.Map) { OSDMap download = (OSDMap)map; if ( download.ContainsKey("download_count") && download.ContainsKey("created_at") && download.ContainsKey("description") && download.ContainsKey("url") && download.ContainsKey("html_url") && download.ContainsKey("size") && download.ContainsKey("name") && download.ContainsKey("content_type") && download.ContainsKey("id") && download["content_type"].AsString() == ".zip" && Regex.IsMatch(download["name"].ToString(), m_regexRelease) ) { Match matches = Regex.Match(download["name"].ToString(), m_regexRelease); releases[new Version(matches.Groups[1].ToString())] = download; } } } if (releases.Count < 1) { ErrorMsg("No releases found"); return; } KeyValuePair <Version, OSDMap> latest = releases.OrderByDescending(kvp => kvp.Key).First(); if (latest.Key <= new Version(VersionInfo.VERSION_NUMBER)) { InfoMsg("You are already using a newer version, no updated is necessary."); return; } DialogResult result = MessageBox.Show("A new version of Aurora has been released, version " + latest.Key.ToString() + " (" + latest.Value["description"] + ")" + ", do you want to download the update?", "Aurora Update", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { Utilities.DownloadFile(latest.Value["html_url"], "Updates" + System.IO.Path.DirectorySeparatorChar + "AuroraVersion" + latest.Key.ToString() + ".zip"); MessageBox.Show(string.Format("Downloaded to {0}, exiting for user to upgrade.", "Updates" + System.IO.Path.DirectorySeparatorChar + "AuroraVersion" + latest.Key.ToString() + ".zip"), "Aurora Update"); Environment.Exit(0); } updateConfig.Set("LatestRelease", latest.Key.ToString()); updateConfig.ConfigSource.Save(); } catch { } }
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> /// 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); }
public AvatarWearable(OSDArray args) { Unpack(args); }
public string RenderMaterialsPostCap(string request, UUID agentID) { OSDMap req = (OSDMap)OSDParser.DeserializeLLSDXml(request); OSDMap resp = new OSDMap(); OSDMap materialsFromViewer = null; OSDArray respArr = new OSDArray(); if (req.ContainsKey("Zipped")) { OSD osd = null; byte[] inBytes = req["Zipped"].AsBinary(); try { osd = ZDecompressBytesToOsd(inBytes); if (osd != null) { if (osd is OSDArray) // assume array of MaterialIDs designating requested material entries { foreach (OSD elem in (OSDArray)osd) { try { UUID id = new UUID(elem.AsBinary(), 0); lock (m_regionMaterials) { if (m_regionMaterials.ContainsKey(id)) { OSDMap matMap = new OSDMap(); matMap["ID"] = OSD.FromBinary(id.GetBytes()); matMap["Material"] = m_regionMaterials[id]; respArr.Add(matMap); } else { m_log.Warn("[Materials]: request for unknown material ID: " + id.ToString()); // Theoretically we could try to load the material from the assets service, // but that shouldn't be necessary because the viewer should only request // materials that exist in a prim on the region, and all of these materials // are already stored in m_regionMaterials. } } } catch (Exception e) { m_log.Error("Error getting materials in response to viewer request", e); continue; } } } else if (osd is OSDMap) // request to assign a material { materialsFromViewer = osd as OSDMap; if (materialsFromViewer.ContainsKey("FullMaterialsPerFace")) { OSD matsOsd = materialsFromViewer["FullMaterialsPerFace"]; if (matsOsd is OSDArray) { OSDArray matsArr = matsOsd as OSDArray; try { foreach (OSDMap matsMap in matsArr) { uint primLocalID = 0; try { primLocalID = matsMap["ID"].AsUInteger(); } catch (Exception e) { m_log.Warn("[Materials]: cannot decode \"ID\" from matsMap: " + e.Message); continue; } OSDMap mat = null; try { mat = matsMap["Material"] as OSDMap; } catch (Exception e) { m_log.Warn("[Materials]: cannot decode \"Material\" from matsMap: " + e.Message); continue; } SceneObjectPart sop = m_scene.GetSceneObjectPart(primLocalID); if (sop == null) { m_log.WarnFormat("[Materials]: SOP not found for localId: {0}", primLocalID.ToString()); continue; } if (!m_scene.Permissions.CanEditObject(sop.UUID, agentID)) { m_log.WarnFormat("User {0} can't edit object {1} {2}", agentID, sop.Name, sop.UUID); continue; } Primitive.TextureEntry te = new Primitive.TextureEntry(sop.Shape.TextureEntry, 0, sop.Shape.TextureEntry.Length); if (te == null) { m_log.WarnFormat("[Materials]: Error in TextureEntry for SOP {0} {1}", sop.Name, sop.UUID); continue; } UUID id; if (mat == null) { // This happens then the user removes a material from a prim id = UUID.Zero; } else { id = StoreMaterialAsAsset(agentID, mat, sop); } int face = -1; if (matsMap.ContainsKey("Face")) { face = matsMap["Face"].AsInteger(); Primitive.TextureEntryFace faceEntry = te.CreateFace((uint)face); faceEntry.MaterialID = id; } else { if (te.DefaultTexture == null) { m_log.WarnFormat("[Materials]: TextureEntry.DefaultTexture is null in {0} {1}", sop.Name, sop.UUID); } else { te.DefaultTexture.MaterialID = id; } } //m_log.DebugFormat("[Materials]: in \"{0}\" {1}, setting material ID for face {2} to {3}", sop.Name, sop.UUID, face, id); // We can't use sop.UpdateTextureEntry(te) because it filters, so do it manually sop.Shape.TextureEntry = te.GetBytes(); if (sop.ParentGroup != null) { sop.TriggerScriptChangedEvent(Changed.TEXTURE); sop.UpdateFlag = UpdateRequired.FULL; sop.ParentGroup.HasGroupChanged = true; sop.ScheduleFullUpdate(); } } } catch (Exception e) { m_log.Warn("[Materials]: exception processing received material ", e); } } } } } } catch (Exception e) { m_log.Warn("[Materials]: exception decoding zipped CAP payload ", e); //return ""; } } resp["Zipped"] = ZCompressOSD(respArr, false); string response = OSDParser.SerializeLLSDXmlString(resp); //m_log.Debug("[Materials]: cap request: " + request); //m_log.Debug("[Materials]: cap request (zipped portion): " + ZippedOsdBytesToString(req["Zipped"].AsBinary())); //m_log.Debug("[Materials]: cap response: " + response); return(response); }
/// <summary> /// Finds any legacy materials stored in DynAttrs that may exist for this part and add them to 'm_regionMaterials'. /// </summary> /// <param name="part"></param> private bool GetLegacyStoredMaterialsInPart(SceneObjectPart part) { if (part.DynAttrs == null) { return(false); } OSD OSMaterials = null; OSDArray matsArr = null; bool partchanged = false; lock (part.DynAttrs) { if (part.DynAttrs.ContainsStore("OpenSim", "Materials")) { OSDMap materialsStore = part.DynAttrs.GetStore("OpenSim", "Materials"); if (materialsStore == null) { return(false); } materialsStore.TryGetValue("Materials", out OSMaterials); part.DynAttrs.RemoveStore("OpenSim", "Materials"); partchanged = true; } if (OSMaterials != null && OSMaterials is OSDArray) { matsArr = OSMaterials as OSDArray; } else { return(partchanged); } } if (matsArr == null) { return(partchanged); } foreach (OSD elemOsd in matsArr) { if (elemOsd != null && elemOsd is OSDMap) { OSDMap matMap = elemOsd as OSDMap; OSD OSDID; OSD OSDMaterial; if (matMap.TryGetValue("ID", out OSDID) && matMap.TryGetValue("Material", out OSDMaterial) && OSDMaterial is OSDMap) { try { lock (materialslock) { UUID id = OSDID.AsUUID(); if (m_Materials.ContainsKey(id)) { continue; } OSDMap theMatMap = (OSDMap)OSDMaterial; FaceMaterial fmat = new FaceMaterial(theMatMap); if (fmat == null || (fmat.DiffuseAlphaMode == 1 && fmat.NormalMapID == UUID.Zero && fmat.SpecularMapID == UUID.Zero)) { continue; } fmat.ID = id; m_Materials[id] = fmat; m_MaterialsRefCount[id] = 0; } } catch (Exception e) { m_log.Warn("[Materials]: exception decoding persisted legacy material: " + e.ToString()); } } } } return(partchanged); }
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); }
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); }
public OSDArray GetUserImageAssets(UUID avatarId) { IDataReader reader = null; OSDArray data = new OSDArray(); string query = "SELECT `snapshotuuid` FROM {0} WHERE `creatoruuid` = :Id"; // Get classified image assets try { using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand()) { cmd.CommandText = query; cmd.Parameters.AddWithValue(":Id", avatarId.ToString()); using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { while (reader.Read()) { data.Add(new OSDString((string)reader["snapshotuuid"].ToString())); } } } using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand()) { cmd.CommandText = query; cmd.Parameters.AddWithValue(":Id", avatarId.ToString()); using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if (reader.Read()) { data.Add(new OSDString((string)reader["snapshotuuid"].ToString())); } } } query = "SELECT `profileImage`, `profileFirstImage` FROM `userprofile` WHERE `useruuid` = :Id"; using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand()) { cmd.CommandText = query; cmd.Parameters.AddWithValue(":Id", avatarId.ToString()); using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if (reader.Read()) { data.Add(new OSDString((string)reader["profileImage"].ToString())); data.Add(new OSDString((string)reader["profileFirstImage"].ToString())); } } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": GetAvatarNotes exception {0}", e.Message); } return(data); }
public static OSD PlacesQuery(PlacesReplyPacket PlacesReply, string[] regionType) { OpenMetaverse.Messages.Linden.PlacesReplyMessage message = new PlacesReplyMessage(); message.AgentID = PlacesReply.AgentData.AgentID; message.QueryID = PlacesReply.AgentData.QueryID; message.TransactionID = PlacesReply.TransactionData.TransactionID; message.QueryDataBlocks = new PlacesReplyMessage.QueryData[PlacesReply.QueryData.Length]; OSDMap placesReply = new OSDMap { { "message", OSD.FromString("PlacesReplyMessage") } }; OSDArray QueryData = new OSDArray(); #if (!ISWIN) int i = 0; foreach (PlacesReplyPacket.QueryDataBlock groupDataBlock in PlacesReply.QueryData) { message.QueryDataBlocks[i] = new PlacesReplyMessage.QueryData(); message.QueryDataBlocks[i].ActualArea = groupDataBlock.ActualArea; message.QueryDataBlocks[i].BillableArea = groupDataBlock.BillableArea; message.QueryDataBlocks[i].Description = Utils.BytesToString(groupDataBlock.Desc); message.QueryDataBlocks[i].Dwell = groupDataBlock.Dwell; message.QueryDataBlocks[i].Flags = groupDataBlock.Flags; message.QueryDataBlocks[i].GlobalX = groupDataBlock.GlobalX; message.QueryDataBlocks[i].GlobalY = groupDataBlock.GlobalY; message.QueryDataBlocks[i].GlobalZ = groupDataBlock.GlobalZ; message.QueryDataBlocks[i].Name = Utils.BytesToString(groupDataBlock.Name); message.QueryDataBlocks[i].OwnerID = groupDataBlock.OwnerID; message.QueryDataBlocks[i].SimName = Utils.BytesToString(groupDataBlock.SimName); message.QueryDataBlocks[i].SnapShotID = groupDataBlock.SnapshotID; message.QueryDataBlocks[i].ProductSku = regionType[i]; message.QueryDataBlocks[i].Price = groupDataBlock.Price; i++; } #else int[] i = { 0 }; foreach (OSDMap QueryDataMap in PlacesReply.QueryData.Select(groupDataBlock => new OSDMap { { "ActualArea", OSD.FromInteger(groupDataBlock.ActualArea) }, { "BillableArea", OSD.FromInteger(groupDataBlock.BillableArea) }, { "Description", OSD.FromBinary(groupDataBlock.Desc) }, { "Dwell", OSD.FromInteger((int)groupDataBlock.Dwell) }, { "Flags", OSD.FromString(Convert.ToString(groupDataBlock.Flags)) }, { "GlobalX", OSD.FromInteger((int)groupDataBlock.GlobalX) }, { "GlobalY", OSD.FromInteger((int)groupDataBlock.GlobalY) }, { "GlobalZ", OSD.FromInteger((int)groupDataBlock.GlobalZ) }, { "Name", OSD.FromBinary(groupDataBlock.Name) }, { "OwnerID", OSD.FromUUID(groupDataBlock.OwnerID) }, { "SimName", OSD.FromBinary(groupDataBlock.SimName) }, { "SnapShotID", OSD.FromUUID(groupDataBlock.SnapshotID) }, { "ProductSku", OSD.FromString(regionType[i[0]]) }, { "Price", OSD.FromInteger(groupDataBlock.Price) } })) { QueryData.Add(QueryDataMap); i[0]++; } #endif OSDMap map = message.Serialize(); placesReply["body"] = map; return(placesReply); }
/// <summary> /// Pack AgentCircuitData into an OSDMap for transmission over LLSD XML or LLSD json /// </summary> /// <returns>map of the agent circuit data</returns> public OSDMap PackAgentCircuitData() { OSDMap args = new OSDMap(); args["agent_id"] = OSD.FromUUID(AgentID); args["base_folder"] = OSD.FromUUID(BaseFolder); args["caps_path"] = OSD.FromString(CapsPath); if (ChildrenCapSeeds != null) { OSDArray childrenSeeds = new OSDArray(ChildrenCapSeeds.Count); foreach (KeyValuePair <ulong, string> kvp in ChildrenCapSeeds) { OSDMap pair = new OSDMap(); pair["handle"] = OSD.FromString(kvp.Key.ToString()); pair["seed"] = OSD.FromString(kvp.Value); childrenSeeds.Add(pair); } if (ChildrenCapSeeds.Count > 0) { args["children_seeds"] = childrenSeeds; } } args["child"] = OSD.FromBoolean(child); args["circuit_code"] = OSD.FromString(circuitcode.ToString()); args["first_name"] = OSD.FromString(firstname); args["last_name"] = OSD.FromString(lastname); args["inventory_folder"] = OSD.FromUUID(InventoryFolder); args["secure_session_id"] = OSD.FromUUID(SecureSessionID); args["session_id"] = OSD.FromUUID(SessionID); args["service_session_id"] = OSD.FromString(ServiceSessionID); args["start_pos"] = OSD.FromString(startpos.ToString()); args["client_ip"] = OSD.FromString(IPAddress); args["viewer"] = OSD.FromString(Viewer); args["channel"] = OSD.FromString(Channel); args["mac"] = OSD.FromString(Mac); args["id0"] = OSD.FromString(Id0); if (Appearance != null) { args["appearance_serial"] = OSD.FromInteger(Appearance.Serial); OSDMap appmap = Appearance.Pack(); args["packed_appearance"] = appmap; } // Old, bad way. Keeping it fow now for backwards compatibility // OBSOLETE -- soon to be deleted if (ServiceURLs != null && ServiceURLs.Count > 0) { OSDArray urls = new OSDArray(ServiceURLs.Count * 2); foreach (KeyValuePair <string, object> kvp in ServiceURLs) { //System.Console.WriteLine("XXX " + kvp.Key + "=" + kvp.Value); urls.Add(OSD.FromString(kvp.Key)); urls.Add(OSD.FromString((kvp.Value == null) ? string.Empty : kvp.Value.ToString())); } args["service_urls"] = urls; } // again, this time the right way if (ServiceURLs != null && ServiceURLs.Count > 0) { OSDMap urls = new OSDMap(); foreach (KeyValuePair <string, object> kvp in ServiceURLs) { //System.Console.WriteLine("XXX " + kvp.Key + "=" + kvp.Value); urls[kvp.Key] = OSD.FromString((kvp.Value == null) ? string.Empty : kvp.Value.ToString()); } args["serviceurls"] = urls; } return(args); }
public static new Avatar FromOSD(OSD O) { OSDMap tex = (OSDMap)O; Avatar A = new Avatar(); Primitive P = Primitive.FromOSD(O); Type Prim = typeof(Primitive); FieldInfo[] Fields = Prim.GetFields(); for (int x = 0; x < Fields.Length; x++) { Logger.Log("Field Matched in FromOSD: " + Fields[x].Name, Helpers.LogLevel.Debug); Fields[x].SetValue(A, Fields[x].GetValue(P)); } A.Groups = new List <UUID>(); foreach (OSD U in (OSDArray)tex["groups"]) { A.Groups.Add(U.AsUUID()); } A.ProfileStatistics = Statistics.FromOSD(tex["profile_statistics"]); A.ProfileProperties = AvatarProperties.FromOSD(tex["profile_properties"]); A.ProfileInterests = Interests.FromOSD(tex["profile_interest"]); A.ControlFlags = (AgentManager.ControlFlags)tex["control_flags"].AsInteger(); OSDArray vp = (OSDArray)tex["visual_parameters"]; A.VisualParameters = new byte[vp.Count]; for (int i = 0; i < vp.Count; i++) { A.VisualParameters[i] = (byte)vp[i].AsInteger(); } // *********************From Code Above ******************************* /*if (NameValues[i].Name == "FirstName" && NameValues[i].Type == NameValue.ValueType.String) * firstName = (string)NameValues[i].Value; * else if (NameValues[i].Name == "LastName" && NameValues[i].Type == NameValue.ValueType.String) * lastName = (string)NameValues[i].Value;*/ // ******************************************************************** A.NameValues = new NameValue[3]; NameValue First = new NameValue(); First.Name = "FirstName"; First.Type = NameValue.ValueType.String; First.Value = tex["first_name"].AsString(); NameValue Last = new NameValue(); Last.Name = "LastName"; Last.Type = NameValue.ValueType.String; Last.Value = tex["last_name"].AsString(); // ***************From Code Above*************** // if (NameValues[i].Name == "Title" && NameValues[i].Type == NameValue.ValueType.String) // ********************************************* NameValue Group = new NameValue(); Group.Name = "Title"; Group.Type = NameValue.ValueType.String; Group.Value = tex["group_name"].AsString(); A.NameValues[0] = First; A.NameValues[1] = Last; A.NameValues[2] = Group; return(A); }
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 void RenderMaterialsPutCap(IOSHttpRequest request, IOSHttpResponse response, UUID agentID) { OSDMap req; try { req = (OSDMap)OSDParser.DeserializeLLSDXml(request.InputStream); } catch { response.StatusCode = (int)HttpStatusCode.BadRequest; return; } OSDMap materialsFromViewer = null; OSDArray respArr = new OSDArray(); OSD tmpOSD; HashSet <SceneObjectPart> parts = new HashSet <SceneObjectPart>(); if (req.TryGetValue("Zipped", out tmpOSD)) { OSD osd = null; byte[] inBytes = tmpOSD.AsBinary(); try { osd = ZDecompressBytesToOsd(inBytes); if (osd != null && osd is OSDMap) { materialsFromViewer = osd as OSDMap; if (materialsFromViewer.TryGetValue("FullMaterialsPerFace", out tmpOSD) && (tmpOSD is OSDArray)) { OSDArray matsArr = tmpOSD as OSDArray; try { foreach (OSDMap matsMap in matsArr) { uint primLocalID = 0; try { primLocalID = matsMap["ID"].AsUInteger(); } catch (Exception e) { m_log.Warn("[Materials]: cannot decode \"ID\" from matsMap: " + e.Message); continue; } SceneObjectPart sop = m_scene.GetSceneObjectPart(primLocalID); if (sop == null) { m_log.WarnFormat("[Materials]: SOP not found for localId: {0}", primLocalID.ToString()); continue; } if (!m_scene.Permissions.CanEditObject(sop.UUID, agentID)) { m_log.WarnFormat("User {0} can't edit object {1} {2}", agentID, sop.Name, sop.UUID); continue; } OSDMap mat = null; try { mat = matsMap["Material"] as OSDMap; } catch (Exception e) { m_log.Warn("[Materials]: cannot decode \"Material\" from matsMap: " + e.Message); continue; } Primitive.TextureEntry te = new Primitive.TextureEntry(sop.Shape.TextureEntry, 0, sop.Shape.TextureEntry.Length); if (te == null) { m_log.WarnFormat("[Materials]: Error in TextureEntry for SOP {0} {1}", sop.Name, sop.UUID); continue; } int face = -1; UUID oldid = UUID.Zero; Primitive.TextureEntryFace faceEntry = null; if (matsMap.TryGetValue("Face", out tmpOSD)) { face = tmpOSD.AsInteger(); faceEntry = te.CreateFace((uint)face); } else { faceEntry = te.DefaultTexture; } if (faceEntry == null) { continue; } UUID id; FaceMaterial newFaceMat = null; if (mat == null) { // This happens then the user removes a material from a prim id = UUID.Zero; } else { newFaceMat = new FaceMaterial(mat); if (newFaceMat.DiffuseAlphaMode == 1 && newFaceMat.NormalMapID == UUID.Zero && newFaceMat.SpecularMapID == UUID.Zero ) { id = UUID.Zero; } else { newFaceMat.genID(); id = newFaceMat.ID; } } oldid = faceEntry.MaterialID; if (oldid == id) { continue; } if (faceEntry != null) { faceEntry.MaterialID = id; //m_log.DebugFormat("[Materials]: in \"{0}\" {1}, setting material ID for face {2} to {3}", sop.Name, sop.UUID, face, id); // We can't use sop.UpdateTextureEntry(te) because it filters, so do it manually sop.Shape.TextureEntry = te.GetBytes(9); } if (oldid != UUID.Zero) { RemoveMaterial(oldid); } lock (materialslock) { if (id != UUID.Zero) { if (m_Materials.ContainsKey(id)) { m_MaterialsRefCount[id]++; } else { m_Materials[id] = newFaceMat; m_MaterialsRefCount[id] = 1; m_changed[newFaceMat] = Util.GetTimeStamp(); } } } if (!parts.Contains(sop)) { parts.Add(sop); } } foreach (SceneObjectPart sop in parts) { if (sop.ParentGroup != null && !sop.ParentGroup.IsDeleted) { sop.TriggerScriptChangedEvent(Changed.TEXTURE); sop.ScheduleFullUpdate(); sop.ParentGroup.HasGroupChanged = true; } } } catch (Exception e) { m_log.Warn("[Materials]: exception processing received material ", e); response.StatusCode = (int)HttpStatusCode.BadRequest; return; } } } } catch (Exception e) { m_log.Warn("[Materials]: exception decoding zipped CAP payload ", e); response.StatusCode = (int)HttpStatusCode.BadRequest; return; } } OSDMap resp = new OSDMap(); resp["Zipped"] = ZCompressOSD(respArr, false); response.RawBuffer = Encoding.UTF8.GetBytes(OSDParser.SerializeLLSDXmlString(resp)); //m_log.Debug("[Materials]: cap request: " + request); //m_log.Debug("[Materials]: cap request (zipped portion): " + ZippedOsdBytesToString(req["Zipped"].AsBinary())); //m_log.Debug("[Materials]: cap response: " + response); }
public AvatarWearable(OSDArray args) { FromOSD(args); }
public OSDMap GetUrlForRegisteringClient(string SessionID) { GridRegistrationURLs urls = m_genericsConnector.GetGeneric <GridRegistrationURLs>(UUID.Zero, "GridRegistrationUrls", SessionID); OSDMap retVal = new OSDMap(); if (urls != null) { if (urls.HostNames == null || urls.Ports == null || urls.URLS == null || urls.SessionID != SessionID || MainServer.Instance.HostName != urls._ParentHostName || !CheckModuleNames(urls) || urls.VersionNumber < GridRegistrationURLs.CurrentVersionNumber) { if (urls.VersionNumber == GridRegistrationURLs.CurrentVersionNumber) { if (CheckModuleNames(urls)) { MainConsole.Instance.Warn("[GridRegService]: Null stuff in GetUrls, HostNames " + (urls.HostNames == null) + ", Ports " + (urls.Ports == null) + ", URLS " + (urls.URLS == null) + ", SessionID 1 " + SessionID + ", SessionID 2 " + urls.SessionID + ", checkModuleNames: " + CheckModuleNames(urls)); } } RemoveUrlsForClient(urls.SessionID); } else { urls.Expiration = DateTime.UtcNow.AddMinutes(m_timeBeforeTimeout * 60); urls.SessionID = SessionID; InnerUpdateUrlsForClient(urls); foreach (KeyValuePair <string, OSD> module in urls.URLS) { if (module.Value.Type == OSDType.Array) { OSDArray array = new OSDArray(); int i = 0; foreach (OSD o in (OSDArray)module.Value) { //Build the URL if (o.AsString().StartsWith("http://") || o.AsString().StartsWith("https://")) { array.Add(o.AsString()); } else { array.Add(((OSDArray)urls.HostNames[module.Key])[i] + ":" + (int)((OSDArray)urls.Ports[module.Key])[i].AsUInteger() + o.AsString()); } i++; } retVal[module.Key] = array; } else { //Build the URL if (module.Value.AsString().StartsWith("http://") || module.Value.AsString().StartsWith("https://")) { retVal[module.Key] = module.Value.AsString(); } else { retVal[module.Key] = urls.HostNames[module.Key] + ":" + urls.Ports[module.Key] + module.Value.AsString(); } } } return(retVal); } } OSDMap databaseSave = new OSDMap(); OSDMap ports = new OSDMap(); OSDMap hostnames = new OSDMap(); //Get the URLs from all the modules that have registered with us foreach (IGridRegistrationUrlModule module in m_modules.Values) { List <uint> port; List <string> hostName; List <string> innerURL; m_loadBalancer.GetHost(module.UrlName, module, SessionID, out port, out hostName, out innerURL); ports[module.UrlName] = port.Count == 1 ? (OSD)port[0] : (OSD)port.ToOSDArray(); hostnames[module.UrlName] = hostName.Count == 1 ? (OSD)hostName[0] : (OSD)hostName.ToOSDArray(); databaseSave[module.UrlName] = innerURL.Count == 1 ? (OSD)innerURL[0] : (OSD)innerURL.ToOSDArray(); } foreach (KeyValuePair <string, OSD> module in databaseSave) { if (module.Value.Type == OSDType.Array) { OSDArray array = new OSDArray(); int i = 0; foreach (OSD o in (OSDArray)module.Value) { //Build the URL if (o.AsString().StartsWith("http://") || o.AsString().StartsWith("https://")) { array.Add(o.AsString()); } else { array.Add(((OSDArray)hostnames[module.Key])[i] + ":" + (int)((OSDArray)ports[module.Key])[i].AsUInteger() + o.AsString()); } i++; } retVal[module.Key] = array; } else { //Build the URL if (module.Value.AsString().StartsWith("http://") || module.Value.AsString().StartsWith("https://")) { retVal[module.Key] = module.Value.AsString(); } else { retVal[module.Key] = hostnames[module.Key] + ":" + ports[module.Key] + module.Value.AsString(); } } } //Save into the database so that we can rebuild later if the server goes offline urls = new GridRegistrationURLs { URLS = databaseSave, SessionID = SessionID, Ports = ports, HostNames = hostnames, Expiration = DateTime.UtcNow.AddMinutes(m_timeBeforeTimeout * 60), _ParentHostName = MainServer.Instance.HostName }; m_genericsConnector.AddGeneric(UUID.Zero, "GridRegistrationUrls", SessionID, urls.ToOSD()); return(retVal); }
/// <summary> /// Create an OSDMap from the appearance data /// </summary> public OSDMap Pack() { OSDMap data = new OSDMap(); data["serial"] = OSD.FromInteger(m_serial); data["height"] = OSD.FromReal(m_avatarHeight); // Wearables OSDArray wears = new OSDArray(AvatarWearable.MAX_WEARABLES); for (int i = 0; i < AvatarWearable.MAX_WEARABLES; i++) wears.Add(m_wearables[i].Pack()); data["wearables"] = wears; // Avatar Textures OSDArray textures = new OSDArray(AvatarAppearance.TEXTURE_COUNT); for (uint i = 0; i < AvatarAppearance.TEXTURE_COUNT; i++) { if (m_texture.FaceTextures[i] != null) textures.Add(OSD.FromUUID(m_texture.FaceTextures[i].TextureID)); else textures.Add(OSD.FromUUID(AppearanceManager.DEFAULT_AVATAR_TEXTURE)); } data["textures"] = textures; // Visual Parameters OSDBinary visualparams = new OSDBinary(m_visualparams); data["visualparams"] = visualparams; // Attachments OSDArray attachs = new OSDArray(m_attachments.Count); foreach (AvatarAttachment attach in GetAttachments()) attachs.Add(attach.Pack()); data["attachments"] = attachs; return data; }
///<summary> ///</summary> ///<param name = "assetID"></param> ///<param name = "inventoryItem"></param> ///<param name = "data"></param> public UUID UploadCompleteHandler(string assetName, string assetDescription, UUID assetID, UUID inventoryItem, UUID parentFolder, byte[] data, string inventoryType, string assetType, uint everyone_mask, uint group_mask, uint next_owner_mask) { sbyte assType = 0; sbyte inType = 0; if (inventoryType == "sound") { inType = 1; assType = 1; } else if (inventoryType == "animation") { inType = 19; assType = 20; } else if (inventoryType == "snapshot") { inType = 15; assType = 0; } else if (inventoryType == "wearable") { inType = 18; switch (assetType) { case "bodypart": assType = 13; break; case "clothing": assType = 5; break; } } else if (inventoryType == "object") { inType = (sbyte)InventoryType.Object; assType = (sbyte)AssetType.Object; List <Vector3> positions = new List <Vector3>(); List <Quaternion> rotations = new List <Quaternion>(); OSDMap request = (OSDMap)OSDParser.DeserializeLLSDXml(data); OSDArray instance_list = (OSDArray)request["instance_list"]; OSDArray mesh_list = (OSDArray)request["mesh_list"]; OSDArray texture_list = (OSDArray)request["texture_list"]; SceneObjectGroup grp = null; List <UUID> textures = new List <UUID>(); #if (!ISWIN) for (int i = 0; i < texture_list.Count; i++) { AssetBase textureAsset = new AssetBase(UUID.Random(), assetName, AssetType.Texture, m_service.AgentID); textureAsset.Data = texture_list[i].AsBinary(); textureAsset.ID = m_assetService.Store(textureAsset); textures.Add(textureAsset.ID); } #else foreach (AssetBase textureAsset in texture_list.Select(t => new AssetBase(UUID.Random(), assetName, AssetType.Texture, m_service.AgentID) { Data = t.AsBinary() })) { textureAsset.ID = m_assetService.Store(textureAsset); textures.Add(textureAsset.ID); } #endif InventoryFolderBase meshFolder = m_inventoryService.GetFolderForType(m_service.AgentID, InventoryType.Mesh, AssetType.Mesh); for (int i = 0; i < mesh_list.Count; i++) { PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox(); Primitive.TextureEntry textureEntry = new Primitive.TextureEntry(Primitive.TextureEntry.WHITE_TEXTURE); OSDMap inner_instance_list = (OSDMap)instance_list[i]; OSDArray face_list = (OSDArray)inner_instance_list["face_list"]; for (uint face = 0; face < face_list.Count; face++) { OSDMap faceMap = (OSDMap)face_list[(int)face]; Primitive.TextureEntryFace f = pbs.Textures.CreateFace(face); if (faceMap.ContainsKey("fullbright")) { f.Fullbright = faceMap["fullbright"].AsBoolean(); } if (faceMap.ContainsKey("diffuse_color")) { f.RGBA = faceMap["diffuse_color"].AsColor4(); } int textureNum = faceMap["image"].AsInteger(); float imagerot = faceMap["imagerot"].AsInteger(); float offsets = (float)faceMap["offsets"].AsReal(); float offsett = (float)faceMap["offsett"].AsReal(); float scales = (float)faceMap["scales"].AsReal(); float scalet = (float)faceMap["scalet"].AsReal(); if (imagerot != 0) { f.Rotation = imagerot; } if (offsets != 0) { f.OffsetU = offsets; } if (offsett != 0) { f.OffsetV = offsett; } if (scales != 0) { f.RepeatU = scales; } if (scalet != 0) { f.RepeatV = scalet; } f.TextureID = textures.Count > textureNum ? textures[textureNum] : Primitive.TextureEntry.WHITE_TEXTURE; textureEntry.FaceTextures[face] = f; } pbs.TextureEntry = textureEntry.GetBytes(); AssetBase meshAsset = new AssetBase(UUID.Random(), assetName, AssetType.Mesh, m_service.AgentID) { Data = mesh_list[i].AsBinary() }; meshAsset.ID = m_assetService.Store(meshAsset); if (meshFolder == null) { m_inventoryService.CreateUserInventory(m_service.AgentID, false); meshFolder = m_inventoryService.GetFolderForType(m_service.AgentID, InventoryType.Mesh, AssetType.Mesh); } InventoryItemBase itemBase = new InventoryItemBase(UUID.Random(), m_service.AgentID) { AssetType = (sbyte)AssetType.Mesh, AssetID = meshAsset.ID, CreatorId = m_service.AgentID.ToString(), Folder = meshFolder.ID, InvType = (int)InventoryType.Texture, Name = "(Mesh) - " + assetName, CurrentPermissions = (uint)PermissionMask.All, BasePermissions = (uint)PermissionMask.All, EveryOnePermissions = everyone_mask, GroupPermissions = group_mask, NextPermissions = next_owner_mask }; //Bad... but whatever m_inventoryService.AddItem(itemBase); pbs.SculptEntry = true; pbs.SculptTexture = meshAsset.ID; pbs.SculptType = (byte)SculptType.Mesh; pbs.SculptData = meshAsset.Data; Vector3 position = inner_instance_list["position"].AsVector3(); Vector3 scale = inner_instance_list["scale"].AsVector3(); Quaternion rotation = inner_instance_list["rotation"].AsQuaternion(); int physicsShapeType = inner_instance_list["physics_shape_type"].AsInteger(); int material = inner_instance_list["material"].AsInteger(); int mesh = inner_instance_list["mesh"].AsInteger(); UUID owner_id = m_service.AgentID; IScene fakeScene = new Scene(); fakeScene.AddModuleInterfaces(m_service.Registry.GetInterfaces()); SceneObjectPart prim = new SceneObjectPart(owner_id, pbs, position, Quaternion.Identity, Vector3.Zero, assetName, fakeScene) { Scale = scale, AbsolutePosition = position }; rotations.Add(rotation); positions.Add(position); prim.UUID = UUID.Random(); prim.CreatorID = owner_id; prim.OwnerID = owner_id; prim.GroupID = UUID.Zero; prim.LastOwnerID = prim.OwnerID; prim.CreationDate = Util.UnixTimeSinceEpoch(); prim.Name = assetName; prim.Description = ""; prim.PhysicsType = (byte)physicsShapeType; prim.BaseMask = (uint)PermissionMask.All; prim.EveryoneMask = everyone_mask; prim.NextOwnerMask = next_owner_mask; prim.GroupMask = group_mask; prim.OwnerMask = (uint)PermissionMask.All; if (grp == null) { grp = new SceneObjectGroup(prim, fakeScene); } else { grp.AddChild(prim, i + 1); } grp.RootPart.IsAttachment = false; } if (grp.ChildrenList.Count > 1) //Fix first link # { grp.RootPart.LinkNum++; } Vector3 rootPos = positions[0]; grp.SetAbsolutePosition(false, rootPos); for (int i = 0; i < positions.Count; i++) { Vector3 offset = positions[i] - rootPos; grp.ChildrenList[i].SetOffsetPosition(offset); Vector3 abs = grp.ChildrenList[i].AbsolutePosition; Vector3 currentPos = positions[i]; } //grp.Rotation = rotations[0]; for (int i = 0; i < rotations.Count; i++) { if (i != 0) { grp.ChildrenList[i].SetRotationOffset(false, rotations[i], false); } } grp.UpdateGroupRotationR(rotations[0]); data = Encoding.ASCII.GetBytes(grp.ToXml2()); } AssetBase asset = new AssetBase(assetID, assetName, (AssetType)assType, m_service.AgentID) { Data = data }; asset.ID = m_assetService.Store(asset); assetID = asset.ID; InventoryItemBase item = new InventoryItemBase { Owner = m_service.AgentID, CreatorId = m_service.AgentID.ToString(), ID = inventoryItem, AssetID = asset.ID, Description = assetDescription, Name = assetName, AssetType = assType, InvType = inType, Folder = parentFolder, CurrentPermissions = (uint)PermissionMask.All, BasePermissions = (uint)PermissionMask.All, EveryOnePermissions = everyone_mask, NextPermissions = next_owner_mask, GroupPermissions = group_mask, CreationDate = Util.UnixTimeSinceEpoch() }; m_inventoryService.AddItem(item); return(assetID); }