diff --git a/BUILDING.txt b/BUILDING.txt index 03fb482226..972fe4696c 100644 --- a/BUILDING.txt +++ b/BUILDING.txt @@ -1,4 +1,4 @@ -== Building OpenSim == +=== Building OpenSim === === Building on Windows === diff --git a/LICENSE.txt b/LICENSE.txt index a004cad48e..570f7328af 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,4 +1,4 @@ -Copyright (c) Contributors, http://opensimulator.org/ +Copyright (c) Contributors, http://opensimulator.org/ See CONTRIBUTORS.TXT for a full list of copyright holders. Redistribution and use in source and binary forms, with or without diff --git a/OpenSim/ApplicationPlugins/RemoteController/RemoteAdminPlugin.cs b/OpenSim/ApplicationPlugins/RemoteController/RemoteAdminPlugin.cs index 5a23c90185..7ebb5de6dd 100644 --- a/OpenSim/ApplicationPlugins/RemoteController/RemoteAdminPlugin.cs +++ b/OpenSim/ApplicationPlugins/RemoteController/RemoteAdminPlugin.cs @@ -63,7 +63,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController private static Object SOLock = new Object(); private OpenSimBase m_app; - private BaseHttpServer m_httpd; + private IHttpServer m_httpd; private IConfig m_config; private IConfigSource m_configSource; private string m_requiredPassword = String.Empty; @@ -113,9 +113,10 @@ namespace OpenSim.ApplicationPlugins.RemoteController m_config = m_configSource.Configs["RemoteAdmin"]; m_log.Info("[RADMIN]: Remote Admin Plugin Enabled"); m_requiredPassword = m_config.GetString("access_password", String.Empty); + int port = m_config.GetInt("port", 0); m_app = openSim; - m_httpd = openSim.HttpServer; + m_httpd = MainServer.GetHttpServer((uint)port); Dictionary availableMethods = new Dictionary(); availableMethods["admin_create_region"] = XmlRpcCreateRegionMethod; @@ -1119,9 +1120,9 @@ namespace OpenSim.ApplicationPlugins.RemoteController } else { - PresenceInfo[] pinfos = m_app.SceneManager.CurrentOrFirstScene.PresenceService.GetAgents(new string[] { account.PrincipalID.ToString() }); - if (pinfos != null && pinfos.Length >= 1) - responseData["lastlogin"] = pinfos[0].Login; + GridUserInfo guinfo = m_app.SceneManager.CurrentOrFirstScene.GridUserService.GetGridUserInfo(account.PrincipalID.ToString()); + if (guinfo != null) + responseData["lastlogin"] = guinfo.Login; else responseData["lastlogin"] = 0; @@ -1611,7 +1612,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController GridRegion home = m_app.SceneManager.CurrentOrFirstScene.GridService.GetRegionByPosition(scopeID, (int)(regX * Constants.RegionSize), (int)(regY * Constants.RegionSize)); if (home != null) - m_app.SceneManager.CurrentOrFirstScene.PresenceService.SetHomeLocation(account.PrincipalID.ToString(), home.RegionID, new Vector3(128, 128, 0), new Vector3(0, 1, 0)); + m_app.SceneManager.CurrentOrFirstScene.GridUserService.SetHome(account.PrincipalID.ToString(), home.RegionID, new Vector3(128, 128, 0), new Vector3(0, 1, 0)); } else { diff --git a/OpenSim/ApplicationPlugins/Rest/Inventory/RestAppearanceServices.cs b/OpenSim/ApplicationPlugins/Rest/Inventory/RestAppearanceServices.cs index b70a5116ca..4369216b26 100644 --- a/OpenSim/ApplicationPlugins/Rest/Inventory/RestAppearanceServices.cs +++ b/OpenSim/ApplicationPlugins/Rest/Inventory/RestAppearanceServices.cs @@ -39,8 +39,7 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory public class RestAppearanceServices : IRest { - - private static readonly int PARM_USERID = 0; +// private static readonly int PARM_USERID = 0; // private static readonly int PARM_PATH = 1; @@ -64,6 +63,7 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory { Rest.Log.InfoFormat("{0} Domain is relative, adding absolute prefix", MsgId); qPrefix = String.Format("{0}{1}{2}", Rest.Prefix, Rest.UrlPathSeparator, qPrefix); + qPrefix = String.Format("{0}{1}{2}", Rest.Prefix, Rest.UrlPathSeparator, qPrefix); Rest.Log.InfoFormat("{0} Domain is now <{1}>", MsgId, qPrefix); } @@ -294,31 +294,31 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory /// /// HTTP service request work area - private void DoGet(AppearanceRequestData rdata) - { - AvatarData adata = Rest.AvatarServices.GetAvatar(rdata.userProfile.ID); - - if (adata == null) - { - rdata.Fail(Rest.HttpStatusCodeNoContent, - String.Format("appearance data not found for user {0} {1}", - rdata.userProfile.FirstName, rdata.userProfile.SurName)); - } - rdata.userAppearance = adata.ToAvatarAppearance(rdata.userProfile.ID); - - rdata.initXmlWriter(); - - FormatUserAppearance(rdata); - - // Indicate a successful request - - rdata.Complete(); - - // Send the response to the user. The body will be implicitly - // constructed from the result of the XML writer. - - rdata.Respond(String.Format("Appearance {0} Normal completion", rdata.method)); - } +// private void DoGet(AppearanceRequestData rdata) +// { +// AvatarData adata = Rest.AvatarServices.GetAvatar(rdata.userProfile.ID); +// +// if (adata == null) +// { +// rdata.Fail(Rest.HttpStatusCodeNoContent, +// String.Format("appearance data not found for user {0} {1}", +// rdata.userProfile.FirstName, rdata.userProfile.SurName)); +// } +// rdata.userAppearance = adata.ToAvatarAppearance(rdata.userProfile.ID); +// +// rdata.initXmlWriter(); +// +// FormatUserAppearance(rdata); +// +// // Indicate a successful request +// +// rdata.Complete(); +// +// // Send the response to the user. The body will be implicitly +// // constructed from the result of the XML writer. +// +// rdata.Respond(String.Format("Appearance {0} Normal completion", rdata.method)); +// } /// /// POST adds NEW information to the user profile database. @@ -326,112 +326,112 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory /// characteristics supplied in the request. /// - private void DoExtend(AppearanceRequestData rdata) - { - - bool created = false; - bool modified = false; - string newnode = String.Empty; - - Rest.Log.DebugFormat("{0} POST ENTRY", MsgId); - - //AvatarAppearance old = Rest.AvatarServices.GetUserAppearance(rdata.userProfile.ID); - - rdata.userAppearance = new AvatarAppearance(); - - // Although the following behavior is admitted by HTTP I am becoming - // increasingly doubtful that it is appropriate for REST. If I attempt to - // add a new record, and it already exists, then it seems to me that the - // attempt should fail, rather than update the existing record. - AvatarData adata = null; - if (GetUserAppearance(rdata)) - { - modified = rdata.userAppearance != null; - created = !modified; - adata = new AvatarData(rdata.userAppearance); - Rest.AvatarServices.SetAvatar(rdata.userProfile.ID, adata); - // Rest.UserServices.UpdateUserProfile(rdata.userProfile); - } - else - { - created = true; - adata = new AvatarData(rdata.userAppearance); - Rest.AvatarServices.SetAvatar(rdata.userProfile.ID, adata); - // Rest.UserServices.UpdateUserProfile(rdata.userProfile); - } - - if (created) - { - newnode = String.Format("{0} {1}", rdata.userProfile.FirstName, - rdata.userProfile.SurName); - // Must include a location header with a URI that identifies the new resource. - - rdata.AddHeader(Rest.HttpHeaderLocation,String.Format("http://{0}{1}:{2}{3}{4}", - rdata.hostname,rdata.port,rdata.path,Rest.UrlPathSeparator, newnode)); - rdata.Complete(Rest.HttpStatusCodeCreated); - - } - else - { - if (modified) - { - rdata.Complete(Rest.HttpStatusCodeOK); - } - else - { - rdata.Complete(Rest.HttpStatusCodeNoContent); - } - } - - rdata.Respond(String.Format("Appearance {0} : Normal completion", rdata.method)); - - } +// private void DoExtend(AppearanceRequestData rdata) +// { +// +// bool created = false; +// bool modified = false; +// string newnode = String.Empty; +// +// Rest.Log.DebugFormat("{0} POST ENTRY", MsgId); +// +// //AvatarAppearance old = Rest.AvatarServices.GetUserAppearance(rdata.userProfile.ID); +// +// rdata.userAppearance = new AvatarAppearance(); +// +// // Although the following behavior is admitted by HTTP I am becoming +// // increasingly doubtful that it is appropriate for REST. If I attempt to +// // add a new record, and it already exists, then it seems to me that the +// // attempt should fail, rather than update the existing record. +// AvatarData adata = null; +// if (GetUserAppearance(rdata)) +// { +// modified = rdata.userAppearance != null; +// created = !modified; +// adata = new AvatarData(rdata.userAppearance); +// Rest.AvatarServices.SetAvatar(rdata.userProfile.ID, adata); +// // Rest.UserServices.UpdateUserProfile(rdata.userProfile); +// } +// else +// { +// created = true; +// adata = new AvatarData(rdata.userAppearance); +// Rest.AvatarServices.SetAvatar(rdata.userProfile.ID, adata); +// // Rest.UserServices.UpdateUserProfile(rdata.userProfile); +// } +// +// if (created) +// { +// newnode = String.Format("{0} {1}", rdata.userProfile.FirstName, +// rdata.userProfile.SurName); +// // Must include a location header with a URI that identifies the new resource. +// +// rdata.AddHeader(Rest.HttpHeaderLocation,String.Format("http://{0}{1}:{2}{3}{4}", +// rdata.hostname,rdata.port,rdata.path,Rest.UrlPathSeparator, newnode)); +// rdata.Complete(Rest.HttpStatusCodeCreated); +// +// } +// else +// { +// if (modified) +// { +// rdata.Complete(Rest.HttpStatusCodeOK); +// } +// else +// { +// rdata.Complete(Rest.HttpStatusCodeNoContent); +// } +// } +// +// rdata.Respond(String.Format("Appearance {0} : Normal completion", rdata.method)); +// +// } /// /// This updates the user's appearance. not all aspects need to be provided, /// only those supplied will be changed. /// - private void DoUpdate(AppearanceRequestData rdata) - { - - // REFACTORING PROBLEM This was commented out. It doesn't work for 0.7 - - //bool created = false; - //bool modified = false; - - - //rdata.userAppearance = Rest.AvatarServices.GetUserAppearance(rdata.userProfile.ID); - - //// If the user exists then this is considered a modification regardless - //// of what may, or may not be, specified in the payload. - - //if (rdata.userAppearance != null) - //{ - // modified = true; - // Rest.AvatarServices.UpdateUserAppearance(rdata.userProfile.ID, rdata.userAppearance); - // Rest.UserServices.UpdateUserProfile(rdata.userProfile); - //} - - //if (created) - //{ - // rdata.Complete(Rest.HttpStatusCodeCreated); - //} - //else - //{ - // if (modified) - // { - // rdata.Complete(Rest.HttpStatusCodeOK); - // } - // else - // { - // rdata.Complete(Rest.HttpStatusCodeNoContent); - // } - //} - - rdata.Respond(String.Format("Appearance {0} : Normal completion", rdata.method)); - - } +// private void DoUpdate(AppearanceRequestData rdata) +// { +// +// // REFACTORING PROBLEM This was commented out. It doesn't work for 0.7 +// +// //bool created = false; +// //bool modified = false; +// +// +// //rdata.userAppearance = Rest.AvatarServices.GetUserAppearance(rdata.userProfile.ID); +// +// //// If the user exists then this is considered a modification regardless +// //// of what may, or may not be, specified in the payload. +// +// //if (rdata.userAppearance != null) +// //{ +// // modified = true; +// // Rest.AvatarServices.UpdateUserAppearance(rdata.userProfile.ID, rdata.userAppearance); +// // Rest.UserServices.UpdateUserProfile(rdata.userProfile); +// //} +// +// //if (created) +// //{ +// // rdata.Complete(Rest.HttpStatusCodeCreated); +// //} +// //else +// //{ +// // if (modified) +// // { +// // rdata.Complete(Rest.HttpStatusCodeOK); +// // } +// // else +// // { +// // rdata.Complete(Rest.HttpStatusCodeNoContent); +// // } +// //} +// +// rdata.Respond(String.Format("Appearance {0} : Normal completion", rdata.method)); +// +// } /// /// Delete the specified user's appearance. This actually performs a reset @@ -439,31 +439,29 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory /// Existing ownership is preserved. All prior updates are lost and can not /// be recovered. /// - - private void DoDelete(AppearanceRequestData rdata) - { - AvatarData adata = Rest.AvatarServices.GetAvatar(rdata.userProfile.ID); - - if (adata != null) - { - AvatarAppearance old = adata.ToAvatarAppearance(rdata.userProfile.ID); - rdata.userAppearance = new AvatarAppearance(); - rdata.userAppearance.Owner = old.Owner; - adata = new AvatarData(rdata.userAppearance); - - Rest.AvatarServices.SetAvatar(rdata.userProfile.ID, adata); - - rdata.Complete(); - } - else - { - - rdata.Complete(Rest.HttpStatusCodeNoContent); - } - - rdata.Respond(String.Format("Appearance {0} : Normal completion", rdata.method)); - - } +// private void DoDelete(AppearanceRequestData rdata) +// { +// AvatarData adata = Rest.AvatarServices.GetAvatar(rdata.userProfile.ID); +// +// if (adata != null) +// { +// AvatarAppearance old = adata.ToAvatarAppearance(rdata.userProfile.ID); +// rdata.userAppearance = new AvatarAppearance(); +// rdata.userAppearance.Owner = old.Owner; +// adata = new AvatarData(rdata.userAppearance); +// +// Rest.AvatarServices.SetAvatar(rdata.userProfile.ID, adata); +// +// rdata.Complete(); +// } +// else +// { +// +// rdata.Complete(Rest.HttpStatusCodeNoContent); +// } +// +// rdata.Respond(String.Format("Appearance {0} : Normal completion", rdata.method)); +// } #endregion method-specific processing diff --git a/OpenSim/ApplicationPlugins/Rest/Inventory/RestInventoryServices.cs b/OpenSim/ApplicationPlugins/Rest/Inventory/RestInventoryServices.cs index 10f387df4f..a4135dbaed 100644 --- a/OpenSim/ApplicationPlugins/Rest/Inventory/RestInventoryServices.cs +++ b/OpenSim/ApplicationPlugins/Rest/Inventory/RestInventoryServices.cs @@ -45,10 +45,10 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory { public class RestInventoryServices : IRest { - private static readonly int PARM_USERID = 0; +// private static readonly int PARM_USERID = 0; private static readonly int PARM_PATH = 1; - private bool enabled = false; +// private bool enabled = false; private string qPrefix = "inventory"; private static readonly string PRIVATE_ROOT_NAME = "My Inventory"; @@ -79,7 +79,7 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory // Activate if everything went OK - enabled = true; +// enabled = true; Rest.Log.InfoFormat("{0} Inventory services initialization complete", MsgId); } @@ -100,7 +100,7 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory public void Close() { - enabled = false; +// enabled = false; Rest.Log.InfoFormat("{0} Inventory services closing down", MsgId); } @@ -139,7 +139,7 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory /// A consolidated HTTP request work area private void DoInventory(RequestData hdata) { - InventoryRequestData rdata = (InventoryRequestData) hdata; +// InventoryRequestData rdata = (InventoryRequestData) hdata; Rest.Log.DebugFormat("{0} DoInventory ENTRY", MsgId); @@ -354,32 +354,32 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory /// corresponding subtree based upon node name. /// /// HTTP service request work area - private void DoGet(InventoryRequestData rdata) - { - rdata.initXmlWriter(); - - rdata.writer.WriteStartElement(String.Empty,"Inventory",String.Empty); - - // If there are additional parameters, then these represent - // a path relative to the root of the inventory. This path - // must be traversed before we format the sub-tree thus - // identified. - - traverse(rdata, rdata.root, PARM_PATH); - - // Close all open elements - - rdata.writer.WriteFullEndElement(); - - // Indicate a successful request - - rdata.Complete(); - - // Send the response to the user. The body will be implicitly - // constructed from the result of the XML writer. - - rdata.Respond(String.Format("Inventory {0} Normal completion", rdata.method)); - } +// private void DoGet(InventoryRequestData rdata) +// { +// rdata.initXmlWriter(); +// +// rdata.writer.WriteStartElement(String.Empty,"Inventory",String.Empty); +// +// // If there are additional parameters, then these represent +// // a path relative to the root of the inventory. This path +// // must be traversed before we format the sub-tree thus +// // identified. +// +// traverse(rdata, rdata.root, PARM_PATH); +// +// // Close all open elements +// +// rdata.writer.WriteFullEndElement(); +// +// // Indicate a successful request +// +// rdata.Complete(); +// +// // Send the response to the user. The body will be implicitly +// // constructed from the result of the XML writer. +// +// rdata.Respond(String.Format("Inventory {0} Normal completion", rdata.method)); +// } /// /// In the case of the inventory, and probably in general, @@ -419,210 +419,210 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory /// context identified by the URI. /// /// HTTP service request work area - private void DoExtend(InventoryRequestData rdata) - { - bool created = false; - bool modified = false; - string newnode = String.Empty; - - // Resolve the context node specified in the URI. Entity - // data will be ADDED beneath this node. rdata already contains - // information about the current content of the user's - // inventory. - - Object InventoryNode = getInventoryNode(rdata, rdata.root, PARM_PATH, Rest.Fill); - - // Processing depends upon the type of inventory node - // identified in the URI. This is the CONTEXT for the - // change. We either got a context or we threw an - // exception. - - // It follows that we can only add information if the URI - // has identified a folder. So only a type of folder is supported - // in this case. - - if (typeof(InventoryFolderBase) == InventoryNode.GetType() || - typeof(InventoryFolderImpl) == InventoryNode.GetType()) - { - // Cast the context node appropriately. - - InventoryFolderBase context = (InventoryFolderBase) InventoryNode; - - Rest.Log.DebugFormat("{0} {1}: Resource(s) will be added to folder {2}", - MsgId, rdata.method, rdata.path); - - // Reconstitute the inventory sub-tree from the XML supplied in the entity. - // The result is a stand-alone inventory subtree, not yet integrated into the - // existing tree. An inventory collection consists of three components: - // [1] A (possibly empty) set of folders. - // [2] A (possibly empty) set of items. - // [3] A (possibly empty) set of assets. - // If all of these are empty, then the POST is a harmless no-operation. - - XmlInventoryCollection entity = ReconstituteEntity(rdata); - - // Inlined assets can be included in entity. These must be incorporated into - // the asset database before we attempt to update the inventory. If anything - // fails, return a failure to requestor. - - if (entity.Assets.Count > 0) - { - Rest.Log.DebugFormat("{0} Adding {1} assets to server", - MsgId, entity.Assets.Count); - - foreach (AssetBase asset in entity.Assets) - { - Rest.Log.DebugFormat("{0} Rest asset: {1} {2} {3}", - MsgId, asset.ID, asset.Type, asset.Name); - Rest.AssetServices.Store(asset); - - created = true; - rdata.appendStatus(String.Format("

Created asset {0}, UUID {1}

", - asset.Name, asset.ID)); - - if (Rest.DEBUG && Rest.DumpAsset) - { - Rest.Dump(asset.Data); - } - } - } - - // Modify the context using the collection of folders and items - // returned in the XmlInventoryCollection. - - foreach (InventoryFolderBase folder in entity.Folders) - { - InventoryFolderBase found; - - // If the parentID is zero, then this folder is going - // into the root folder identified by the URI. The requestor - // may have already set the parent ID explicitly, in which - // case we don't have to do it here. - - if (folder.ParentID == UUID.Zero || folder.ParentID == context.ID) - { - if (newnode != String.Empty) - { - Rest.Log.DebugFormat("{0} Too many resources", MsgId); - rdata.Fail(Rest.HttpStatusCodeBadRequest, "only one root entity is allowed"); - } - folder.ParentID = context.ID; - newnode = folder.Name; - } - - // Search the existing inventory for an existing entry. If - // we have one, we need to decide if it has really changed. - // It could just be present as (unnecessary) context, and we - // don't want to waste time updating the database in that - // case, OR, it could be being moved from another location - // in which case an update is most certainly necessary. - - found = null; - - foreach (InventoryFolderBase xf in rdata.folders) - { - // Compare identifying attribute - if (xf.ID == folder.ID) - { - found = xf; - break; - } - } - - if (found != null && FolderHasChanged(folder,found)) - { - Rest.Log.DebugFormat("{0} Updating existing folder", MsgId); - Rest.InventoryServices.MoveFolder(folder); - - modified = true; - rdata.appendStatus(String.Format("

Created folder {0}, UUID {1}

", - folder.Name, folder.ID)); - } - else - { - Rest.Log.DebugFormat("{0} Adding new folder", MsgId); - Rest.InventoryServices.AddFolder(folder); - - created = true; - rdata.appendStatus(String.Format("

Modified folder {0}, UUID {1}

", - folder.Name, folder.ID)); - } - } - - // Now we repeat a similar process for the items included - // in the entity. - - foreach (InventoryItemBase item in entity.Items) - { - InventoryItemBase found = null; - - // If the parentID is zero, then this is going - // directly into the root identified by the URI. - - if (item.Folder == UUID.Zero) - { - item.Folder = context.ID; - } - - // Determine whether this is a new item or a - // replacement definition. - - foreach (InventoryItemBase xi in rdata.items) - { - // Compare identifying attribute - if (xi.ID == item.ID) - { - found = xi; - break; - } - } - - if (found != null && ItemHasChanged(item, found)) - { - Rest.Log.DebugFormat("{0} Updating item {1} {2} {3} {4} {5}", - MsgId, item.ID, item.AssetID, item.InvType, item.AssetType, item.Name); - Rest.InventoryServices.UpdateItem(item); - modified = true; - rdata.appendStatus(String.Format("

Modified item {0}, UUID {1}

", item.Name, item.ID)); - } - else - { - Rest.Log.DebugFormat("{0} Adding item {1} {2} {3} {4} {5}", - MsgId, item.ID, item.AssetID, item.InvType, item.AssetType, item.Name); - Rest.InventoryServices.AddItem(item); - created = true; - rdata.appendStatus(String.Format("

Created item {0}, UUID {1}

", item.Name, item.ID)); - } - } - - if (created) - { - // Must include a location header with a URI that identifies the new resource. - rdata.AddHeader(Rest.HttpHeaderLocation,String.Format("http://{0}{1}:{2}/{3}", - rdata.hostname, rdata.port,rdata.path,newnode)); - rdata.Complete(Rest.HttpStatusCodeCreated); - } - else - { - if (modified) - { - rdata.Complete(Rest.HttpStatusCodeOK); - } - else - { - rdata.Complete(Rest.HttpStatusCodeNoContent); - } - } - - rdata.Respond(String.Format("Profile {0} : Normal completion", rdata.method)); - } - else - { - Rest.Log.DebugFormat("{0} {1}: Resource {2} is not a valid context: {3}", - MsgId, rdata.method, rdata.path, InventoryNode.GetType()); - rdata.Fail(Rest.HttpStatusCodeBadRequest, "invalid resource context"); - } - } +// private void DoExtend(InventoryRequestData rdata) +// { +// bool created = false; +// bool modified = false; +// string newnode = String.Empty; +// +// // Resolve the context node specified in the URI. Entity +// // data will be ADDED beneath this node. rdata already contains +// // information about the current content of the user's +// // inventory. +// +// Object InventoryNode = getInventoryNode(rdata, rdata.root, PARM_PATH, Rest.Fill); +// +// // Processing depends upon the type of inventory node +// // identified in the URI. This is the CONTEXT for the +// // change. We either got a context or we threw an +// // exception. +// +// // It follows that we can only add information if the URI +// // has identified a folder. So only a type of folder is supported +// // in this case. +// +// if (typeof(InventoryFolderBase) == InventoryNode.GetType() || +// typeof(InventoryFolderImpl) == InventoryNode.GetType()) +// { +// // Cast the context node appropriately. +// +// InventoryFolderBase context = (InventoryFolderBase) InventoryNode; +// +// Rest.Log.DebugFormat("{0} {1}: Resource(s) will be added to folder {2}", +// MsgId, rdata.method, rdata.path); +// +// // Reconstitute the inventory sub-tree from the XML supplied in the entity. +// // The result is a stand-alone inventory subtree, not yet integrated into the +// // existing tree. An inventory collection consists of three components: +// // [1] A (possibly empty) set of folders. +// // [2] A (possibly empty) set of items. +// // [3] A (possibly empty) set of assets. +// // If all of these are empty, then the POST is a harmless no-operation. +// +// XmlInventoryCollection entity = ReconstituteEntity(rdata); +// +// // Inlined assets can be included in entity. These must be incorporated into +// // the asset database before we attempt to update the inventory. If anything +// // fails, return a failure to requestor. +// +// if (entity.Assets.Count > 0) +// { +// Rest.Log.DebugFormat("{0} Adding {1} assets to server", +// MsgId, entity.Assets.Count); +// +// foreach (AssetBase asset in entity.Assets) +// { +// Rest.Log.DebugFormat("{0} Rest asset: {1} {2} {3}", +// MsgId, asset.ID, asset.Type, asset.Name); +// Rest.AssetServices.Store(asset); +// +// created = true; +// rdata.appendStatus(String.Format("

Created asset {0}, UUID {1}

", +// asset.Name, asset.ID)); +// +// if (Rest.DEBUG && Rest.DumpAsset) +// { +// Rest.Dump(asset.Data); +// } +// } +// } +// +// // Modify the context using the collection of folders and items +// // returned in the XmlInventoryCollection. +// +// foreach (InventoryFolderBase folder in entity.Folders) +// { +// InventoryFolderBase found; +// +// // If the parentID is zero, then this folder is going +// // into the root folder identified by the URI. The requestor +// // may have already set the parent ID explicitly, in which +// // case we don't have to do it here. +// +// if (folder.ParentID == UUID.Zero || folder.ParentID == context.ID) +// { +// if (newnode != String.Empty) +// { +// Rest.Log.DebugFormat("{0} Too many resources", MsgId); +// rdata.Fail(Rest.HttpStatusCodeBadRequest, "only one root entity is allowed"); +// } +// folder.ParentID = context.ID; +// newnode = folder.Name; +// } +// +// // Search the existing inventory for an existing entry. If +// // we have one, we need to decide if it has really changed. +// // It could just be present as (unnecessary) context, and we +// // don't want to waste time updating the database in that +// // case, OR, it could be being moved from another location +// // in which case an update is most certainly necessary. +// +// found = null; +// +// foreach (InventoryFolderBase xf in rdata.folders) +// { +// // Compare identifying attribute +// if (xf.ID == folder.ID) +// { +// found = xf; +// break; +// } +// } +// +// if (found != null && FolderHasChanged(folder,found)) +// { +// Rest.Log.DebugFormat("{0} Updating existing folder", MsgId); +// Rest.InventoryServices.MoveFolder(folder); +// +// modified = true; +// rdata.appendStatus(String.Format("

Created folder {0}, UUID {1}

", +// folder.Name, folder.ID)); +// } +// else +// { +// Rest.Log.DebugFormat("{0} Adding new folder", MsgId); +// Rest.InventoryServices.AddFolder(folder); +// +// created = true; +// rdata.appendStatus(String.Format("

Modified folder {0}, UUID {1}

", +// folder.Name, folder.ID)); +// } +// } +// +// // Now we repeat a similar process for the items included +// // in the entity. +// +// foreach (InventoryItemBase item in entity.Items) +// { +// InventoryItemBase found = null; +// +// // If the parentID is zero, then this is going +// // directly into the root identified by the URI. +// +// if (item.Folder == UUID.Zero) +// { +// item.Folder = context.ID; +// } +// +// // Determine whether this is a new item or a +// // replacement definition. +// +// foreach (InventoryItemBase xi in rdata.items) +// { +// // Compare identifying attribute +// if (xi.ID == item.ID) +// { +// found = xi; +// break; +// } +// } +// +// if (found != null && ItemHasChanged(item, found)) +// { +// Rest.Log.DebugFormat("{0} Updating item {1} {2} {3} {4} {5}", +// MsgId, item.ID, item.AssetID, item.InvType, item.AssetType, item.Name); +// Rest.InventoryServices.UpdateItem(item); +// modified = true; +// rdata.appendStatus(String.Format("

Modified item {0}, UUID {1}

", item.Name, item.ID)); +// } +// else +// { +// Rest.Log.DebugFormat("{0} Adding item {1} {2} {3} {4} {5}", +// MsgId, item.ID, item.AssetID, item.InvType, item.AssetType, item.Name); +// Rest.InventoryServices.AddItem(item); +// created = true; +// rdata.appendStatus(String.Format("

Created item {0}, UUID {1}

", item.Name, item.ID)); +// } +// } +// +// if (created) +// { +// // Must include a location header with a URI that identifies the new resource. +// rdata.AddHeader(Rest.HttpHeaderLocation,String.Format("http://{0}{1}:{2}/{3}", +// rdata.hostname, rdata.port,rdata.path,newnode)); +// rdata.Complete(Rest.HttpStatusCodeCreated); +// } +// else +// { +// if (modified) +// { +// rdata.Complete(Rest.HttpStatusCodeOK); +// } +// else +// { +// rdata.Complete(Rest.HttpStatusCodeNoContent); +// } +// } +// +// rdata.Respond(String.Format("Profile {0} : Normal completion", rdata.method)); +// } +// else +// { +// Rest.Log.DebugFormat("{0} {1}: Resource {2} is not a valid context: {3}", +// MsgId, rdata.method, rdata.path, InventoryNode.GetType()); +// rdata.Fail(Rest.HttpStatusCodeBadRequest, "invalid resource context"); +// } +// } ///

/// PUT updates the URI-identified element in the inventory. This @@ -646,243 +646,242 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory /// during the reconstitution process. /// /// HTTP service request work area - private void DoUpdate(InventoryRequestData rdata) - { - int count = 0; - bool created = false; - bool modified = false; - - // Resolve the inventory node that is to be modified. - // rdata already contains information about the current - // content of the user's inventory. - - Object InventoryNode = getInventoryNode(rdata, rdata.root, PARM_PATH, Rest.Fill); - - // As long as we have a node, then we have something - // meaningful to do, unlike POST. So we reconstitute the - // subtree before doing anything else. Note that we - // etiher got a valid node or we threw an exception. - - XmlInventoryCollection entity = ReconstituteEntity(rdata); - - // Incorporate any inlined assets first. Any failures - // will terminate the request. - - if (entity.Assets.Count > 0) - { - Rest.Log.DebugFormat("{0} Adding {1} assets to server", - MsgId, entity.Assets.Count); - - foreach (AssetBase asset in entity.Assets) - { - Rest.Log.DebugFormat("{0} Rest asset: {1} {2} {3}", - MsgId, asset.ID, asset.Type, asset.Name); - - // The asset was validated during the collection process - - Rest.AssetServices.Store(asset); - - created = true; - rdata.appendStatus(String.Format("

Created asset {0}, UUID {1}

", asset.Name, asset.ID)); - - if (Rest.DEBUG && Rest.DumpAsset) - { - Rest.Dump(asset.Data); - } - } - } - - // The URI specifies either a folder or an item to be updated. - // - // The root node in the entity will replace the node identified - // by the URI. This means the parent will remain the same, but - // any or all attributes associated with the named element - // will change. - // - // If the inventory collection contains an element with a zero - // parent ID, then this is taken to be the replacement for the - // named node. The collection MAY also specify an explicit - // parent ID, in this case it MAY identify the same parent as - // the current node, or it MAY specify a different parent, - // indicating that the folder is being moved in addition to any - // other modifications being made. - - if (typeof(InventoryFolderBase) == InventoryNode.GetType() || - typeof(InventoryFolderImpl) == InventoryNode.GetType()) - { - bool rfound = false; - InventoryFolderBase uri = (InventoryFolderBase) InventoryNode; - InventoryFolderBase xml = null; - - // If the entity to be replaced resolved to be the root - // directory itself (My Inventory), then make sure that - // the supplied data include as appropriately typed and - // named folder. Note that we can;t rule out the possibility - // of a sub-directory being called "My Inventory", so that - // is anticipated. - - if (uri == rdata.root) - { - foreach (InventoryFolderBase folder in entity.Folders) - { - if ((rfound = (folder.Name == PRIVATE_ROOT_NAME))) - { - if ((rfound = (folder.ParentID == UUID.Zero))) - break; - } - } - - if (!rfound) - { - Rest.Log.DebugFormat("{0} {1}: Path <{2}> will result in loss of inventory", - MsgId, rdata.method, rdata.path); - rdata.Fail(Rest.HttpStatusCodeBadRequest, "invalid inventory structure"); - } - } - - // Scan the set of folders in the entity collection for an - // entry that matches the context folder. It is assumed that - // the only reliable indicator of this is a zero UUID (using - // implicit context), or the parent's UUID matches that of the - // URI designated node (explicit context). We don't allow - // ambiguity in this case because this is POST and we are - // supposed to be modifying a specific node. - // We assign any element IDs required as an economy; we don't - // want to iterate over the fodler set again if it can be - // helped. - - foreach (InventoryFolderBase folder in entity.Folders) - { - if (folder.ParentID == uri.ParentID || - folder.ParentID == UUID.Zero) - { - folder.ParentID = uri.ParentID; - xml = folder; - count++; - } - } - - // More than one entry is ambiguous. Other folders should be - // added using the POST verb. - - if (count > 1) - { - Rest.Log.DebugFormat("{0} {1}: Request for <{2}> is ambiguous", - MsgId, rdata.method, rdata.path); - rdata.Fail(Rest.HttpStatusCodeConflict, "context is ambiguous"); - } - - // Exactly one entry means we ARE replacing the node - // identified by the URI. So we delete the old folder - // by moving it to the trash and then purging it. - // We then add all of the folders and items we - // included in the entity. The subtree has been - // modified. - - if (count == 1) - { - InventoryFolderBase TrashCan = GetTrashCan(rdata); - - // All went well, so we generate a UUID is one is - // needed. - - if (xml.ID == UUID.Zero) - { - xml.ID = UUID.Random(); - } - - uri.ParentID = TrashCan.ID; - Rest.InventoryServices.MoveFolder(uri); - Rest.InventoryServices.PurgeFolder(TrashCan); - modified = true; - } - - // Now, regardelss of what they represent, we - // integrate all of the elements in the entity. - - foreach (InventoryFolderBase f in entity.Folders) - { - rdata.appendStatus(String.Format("

Moving folder {0} UUID {1}

", f.Name, f.ID)); - Rest.InventoryServices.MoveFolder(f); - } - - foreach (InventoryItemBase it in entity.Items) - { - rdata.appendStatus(String.Format("

Storing item {0} UUID {1}

", it.Name, it.ID)); - Rest.InventoryServices.AddItem(it); - } - } - - ///

- /// URI specifies an item to be updated - /// - /// - /// The entity must contain a single item node to be - /// updated. ID and Folder ID must be correct. - /// - - else - { - InventoryItemBase uri = (InventoryItemBase) InventoryNode; - InventoryItemBase xml = null; - - if (entity.Folders.Count != 0) - { - Rest.Log.DebugFormat("{0} {1}: Request should not contain any folders <{2}>", - MsgId, rdata.method, rdata.path); - rdata.Fail(Rest.HttpStatusCodeBadRequest, "folder is not allowed"); - } - - if (entity.Items.Count > 1) - { - Rest.Log.DebugFormat("{0} {1}: Entity contains too many items <{2}>", - MsgId, rdata.method, rdata.path); - rdata.Fail(Rest.HttpStatusCodeBadRequest, "too may items"); - } - - xml = entity.Items[0]; - - if (xml.ID == UUID.Zero) - { - xml.ID = UUID.Random(); - } - - // If the folder reference has changed, then this item is - // being moved. Otherwise we'll just delete the old, and - // add in the new. - - // Delete the old item - - List uuids = new List(); - uuids.Add(uri.ID); - Rest.InventoryServices.DeleteItems(uri.Owner, uuids); - - // Add the new item to the inventory - - Rest.InventoryServices.AddItem(xml); - - rdata.appendStatus(String.Format("

Storing item {0} UUID {1}

", xml.Name, xml.ID)); - } - - if (created) - { - rdata.Complete(Rest.HttpStatusCodeCreated); - } - else - { - if (modified) - { - rdata.Complete(Rest.HttpStatusCodeOK); - } - else - { - rdata.Complete(Rest.HttpStatusCodeNoContent); - } - } - - rdata.Respond(String.Format("Profile {0} : Normal completion", rdata.method)); - - } +// private void DoUpdate(InventoryRequestData rdata) +// { +// int count = 0; +// bool created = false; +// bool modified = false; +// +// // Resolve the inventory node that is to be modified. +// // rdata already contains information about the current +// // content of the user's inventory. +// +// Object InventoryNode = getInventoryNode(rdata, rdata.root, PARM_PATH, Rest.Fill); +// +// // As long as we have a node, then we have something +// // meaningful to do, unlike POST. So we reconstitute the +// // subtree before doing anything else. Note that we +// // etiher got a valid node or we threw an exception. +// +// XmlInventoryCollection entity = ReconstituteEntity(rdata); +// +// // Incorporate any inlined assets first. Any failures +// // will terminate the request. +// +// if (entity.Assets.Count > 0) +// { +// Rest.Log.DebugFormat("{0} Adding {1} assets to server", +// MsgId, entity.Assets.Count); +// +// foreach (AssetBase asset in entity.Assets) +// { +// Rest.Log.DebugFormat("{0} Rest asset: {1} {2} {3}", +// MsgId, asset.ID, asset.Type, asset.Name); +// +// // The asset was validated during the collection process +// +// Rest.AssetServices.Store(asset); +// +// created = true; +// rdata.appendStatus(String.Format("

Created asset {0}, UUID {1}

", asset.Name, asset.ID)); +// +// if (Rest.DEBUG && Rest.DumpAsset) +// { +// Rest.Dump(asset.Data); +// } +// } +// } +// +// // The URI specifies either a folder or an item to be updated. +// // +// // The root node in the entity will replace the node identified +// // by the URI. This means the parent will remain the same, but +// // any or all attributes associated with the named element +// // will change. +// // +// // If the inventory collection contains an element with a zero +// // parent ID, then this is taken to be the replacement for the +// // named node. The collection MAY also specify an explicit +// // parent ID, in this case it MAY identify the same parent as +// // the current node, or it MAY specify a different parent, +// // indicating that the folder is being moved in addition to any +// // other modifications being made. +// +// if (typeof(InventoryFolderBase) == InventoryNode.GetType() || +// typeof(InventoryFolderImpl) == InventoryNode.GetType()) +// { +// bool rfound = false; +// InventoryFolderBase uri = (InventoryFolderBase) InventoryNode; +// InventoryFolderBase xml = null; +// +// // If the entity to be replaced resolved to be the root +// // directory itself (My Inventory), then make sure that +// // the supplied data include as appropriately typed and +// // named folder. Note that we can;t rule out the possibility +// // of a sub-directory being called "My Inventory", so that +// // is anticipated. +// +// if (uri == rdata.root) +// { +// foreach (InventoryFolderBase folder in entity.Folders) +// { +// if ((rfound = (folder.Name == PRIVATE_ROOT_NAME))) +// { +// if ((rfound = (folder.ParentID == UUID.Zero))) +// break; +// } +// } +// +// if (!rfound) +// { +// Rest.Log.DebugFormat("{0} {1}: Path <{2}> will result in loss of inventory", +// MsgId, rdata.method, rdata.path); +// rdata.Fail(Rest.HttpStatusCodeBadRequest, "invalid inventory structure"); +// } +// } +// +// // Scan the set of folders in the entity collection for an +// // entry that matches the context folder. It is assumed that +// // the only reliable indicator of this is a zero UUID (using +// // implicit context), or the parent's UUID matches that of the +// // URI designated node (explicit context). We don't allow +// // ambiguity in this case because this is POST and we are +// // supposed to be modifying a specific node. +// // We assign any element IDs required as an economy; we don't +// // want to iterate over the fodler set again if it can be +// // helped. +// +// foreach (InventoryFolderBase folder in entity.Folders) +// { +// if (folder.ParentID == uri.ParentID || +// folder.ParentID == UUID.Zero) +// { +// folder.ParentID = uri.ParentID; +// xml = folder; +// count++; +// } +// } +// +// // More than one entry is ambiguous. Other folders should be +// // added using the POST verb. +// +// if (count > 1) +// { +// Rest.Log.DebugFormat("{0} {1}: Request for <{2}> is ambiguous", +// MsgId, rdata.method, rdata.path); +// rdata.Fail(Rest.HttpStatusCodeConflict, "context is ambiguous"); +// } +// +// // Exactly one entry means we ARE replacing the node +// // identified by the URI. So we delete the old folder +// // by moving it to the trash and then purging it. +// // We then add all of the folders and items we +// // included in the entity. The subtree has been +// // modified. +// +// if (count == 1) +// { +// InventoryFolderBase TrashCan = GetTrashCan(rdata); +// +// // All went well, so we generate a UUID is one is +// // needed. +// +// if (xml.ID == UUID.Zero) +// { +// xml.ID = UUID.Random(); +// } +// +// uri.ParentID = TrashCan.ID; +// Rest.InventoryServices.MoveFolder(uri); +// Rest.InventoryServices.PurgeFolder(TrashCan); +// modified = true; +// } +// +// // Now, regardelss of what they represent, we +// // integrate all of the elements in the entity. +// +// foreach (InventoryFolderBase f in entity.Folders) +// { +// rdata.appendStatus(String.Format("

Moving folder {0} UUID {1}

", f.Name, f.ID)); +// Rest.InventoryServices.MoveFolder(f); +// } +// +// foreach (InventoryItemBase it in entity.Items) +// { +// rdata.appendStatus(String.Format("

Storing item {0} UUID {1}

", it.Name, it.ID)); +// Rest.InventoryServices.AddItem(it); +// } +// } +// +// ///

+// /// URI specifies an item to be updated +// /// +// /// +// /// The entity must contain a single item node to be +// /// updated. ID and Folder ID must be correct. +// /// +// +// else +// { +// InventoryItemBase uri = (InventoryItemBase) InventoryNode; +// InventoryItemBase xml = null; +// +// if (entity.Folders.Count != 0) +// { +// Rest.Log.DebugFormat("{0} {1}: Request should not contain any folders <{2}>", +// MsgId, rdata.method, rdata.path); +// rdata.Fail(Rest.HttpStatusCodeBadRequest, "folder is not allowed"); +// } +// +// if (entity.Items.Count > 1) +// { +// Rest.Log.DebugFormat("{0} {1}: Entity contains too many items <{2}>", +// MsgId, rdata.method, rdata.path); +// rdata.Fail(Rest.HttpStatusCodeBadRequest, "too may items"); +// } +// +// xml = entity.Items[0]; +// +// if (xml.ID == UUID.Zero) +// { +// xml.ID = UUID.Random(); +// } +// +// // If the folder reference has changed, then this item is +// // being moved. Otherwise we'll just delete the old, and +// // add in the new. +// +// // Delete the old item +// +// List uuids = new List(); +// uuids.Add(uri.ID); +// Rest.InventoryServices.DeleteItems(uri.Owner, uuids); +// +// // Add the new item to the inventory +// +// Rest.InventoryServices.AddItem(xml); +// +// rdata.appendStatus(String.Format("

Storing item {0} UUID {1}

", xml.Name, xml.ID)); +// } +// +// if (created) +// { +// rdata.Complete(Rest.HttpStatusCodeCreated); +// } +// else +// { +// if (modified) +// { +// rdata.Complete(Rest.HttpStatusCodeOK); +// } +// else +// { +// rdata.Complete(Rest.HttpStatusCodeNoContent); +// } +// } +// +// rdata.Respond(String.Format("Profile {0} : Normal completion", rdata.method)); +// } ///

/// Arguably the most damaging REST interface. It deletes the inventory @@ -904,42 +903,41 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory /// elements. /// /// HTTP service request work area - - private void DoDelete(InventoryRequestData rdata) - { - Object InventoryNode = getInventoryNode(rdata, rdata.root, PARM_PATH, false); - - if (typeof(InventoryFolderBase) == InventoryNode.GetType() || - typeof(InventoryFolderImpl) == InventoryNode.GetType()) - { - InventoryFolderBase TrashCan = GetTrashCan(rdata); - - InventoryFolderBase folder = (InventoryFolderBase) InventoryNode; - Rest.Log.DebugFormat("{0} {1}: Folder {2} will be deleted", - MsgId, rdata.method, rdata.path); - folder.ParentID = TrashCan.ID; - Rest.InventoryServices.MoveFolder(folder); - Rest.InventoryServices.PurgeFolder(TrashCan); - - rdata.appendStatus(String.Format("

Deleted folder {0} UUID {1}

", folder.Name, folder.ID)); - } - - // Deleting items is much more straight forward. - - else - { - InventoryItemBase item = (InventoryItemBase) InventoryNode; - Rest.Log.DebugFormat("{0} {1}: Item {2} will be deleted", - MsgId, rdata.method, rdata.path); - List uuids = new List(); - uuids.Add(item.ID); - Rest.InventoryServices.DeleteItems(item.Owner, uuids); - rdata.appendStatus(String.Format("

Deleted item {0} UUID {1}

", item.Name, item.ID)); - } - - rdata.Complete(); - rdata.Respond(String.Format("Profile {0} : Normal completion", rdata.method)); - } +// private void DoDelete(InventoryRequestData rdata) +// { +// Object InventoryNode = getInventoryNode(rdata, rdata.root, PARM_PATH, false); +// +// if (typeof(InventoryFolderBase) == InventoryNode.GetType() || +// typeof(InventoryFolderImpl) == InventoryNode.GetType()) +// { +// InventoryFolderBase TrashCan = GetTrashCan(rdata); +// +// InventoryFolderBase folder = (InventoryFolderBase) InventoryNode; +// Rest.Log.DebugFormat("{0} {1}: Folder {2} will be deleted", +// MsgId, rdata.method, rdata.path); +// folder.ParentID = TrashCan.ID; +// Rest.InventoryServices.MoveFolder(folder); +// Rest.InventoryServices.PurgeFolder(TrashCan); +// +// rdata.appendStatus(String.Format("

Deleted folder {0} UUID {1}

", folder.Name, folder.ID)); +// } +// +// // Deleting items is much more straight forward. +// +// else +// { +// InventoryItemBase item = (InventoryItemBase) InventoryNode; +// Rest.Log.DebugFormat("{0} {1}: Item {2} will be deleted", +// MsgId, rdata.method, rdata.path); +// List uuids = new List(); +// uuids.Add(item.ID); +// Rest.InventoryServices.DeleteItems(item.Owner, uuids); +// rdata.appendStatus(String.Format("

Deleted item {0} UUID {1}

", item.Name, item.ID)); +// } +// +// rdata.Complete(); +// rdata.Respond(String.Format("Profile {0} : Normal completion", rdata.method)); +// } #endregion method-specific processing diff --git a/OpenSim/Client/MXP/ClientStack/MXPClientView.cs b/OpenSim/Client/MXP/ClientStack/MXPClientView.cs index 2c395ae4d0..098d73e062 100644 --- a/OpenSim/Client/MXP/ClientStack/MXPClientView.cs +++ b/OpenSim/Client/MXP/ClientStack/MXPClientView.cs @@ -934,6 +934,10 @@ namespace OpenSim.Client.MXP.ClientStack // Need to translate to MXP somehow } + public void SendGenericMessage(string method, List message) + { + } + public void SendGenericMessage(string method, List message) { // Need to translate to MXP somehow @@ -1029,23 +1033,6 @@ namespace OpenSim.Client.MXP.ClientStack // Need to translate to MXP somehow } - public void SendAvatarData(SendAvatarData data) - { - //ScenePresence presence=((Scene)this.Scene).GetScenePresence(avatarID); - UUID ownerID = data.AvatarID; - MXPSendAvatarData(data.FirstName + " " + data.LastName, ownerID, UUID.Zero, data.AvatarID, data.AvatarLocalID, data.Position, data.Rotation); - } - - public void SendAvatarTerseUpdate(SendAvatarTerseData data) - { - MovementEventMessage me = new MovementEventMessage(); - me.ObjectIndex = data.LocalID; - me.Location = ToOmVector(data.Position); - me.Orientation = ToOmQuaternion(data.Rotation); - - Session.Send(me); - } - public void SendCoarseLocationUpdate(List users, List CoarseLocations) { // Minimap function, not used. @@ -1061,23 +1048,31 @@ namespace OpenSim.Client.MXP.ClientStack // Need to translate to MXP somehow } - public void SendPrimitiveToClient(SendPrimitiveData data) + public void SendAvatarDataImmediate(ISceneEntity avatar) { - MXPSendPrimitive(data.localID, data.ownerID, data.acc, data.rvel, data.primShape, data.pos, data.objectID, data.vel, - data.rotation, (uint)data.flags, data.text, data.color, data.parentID, data.particleSystem, data.clickAction, - data.material, data.textureanim); + //ScenePresence presence=((Scene)this.Scene).GetScenePresence(avatarID); + ScenePresence presence = (ScenePresence)avatar; + UUID ownerID = presence.UUID; + MXPSendAvatarData(presence.Firstname + " " + presence.Lastname, ownerID, UUID.Zero, presence.UUID, presence.LocalId, presence.AbsolutePosition, presence.Rotation); } - public void SendPrimTerseUpdate(SendPrimitiveTerseData data) + public void SendPrimUpdate(ISceneEntity entity, PrimUpdateFlags updateFlags) { - MovementEventMessage me = new MovementEventMessage(); - me.ObjectIndex = data.LocalID; - me.Location = ToOmVector(data.Position); - me.Orientation = ToOmQuaternion(data.Rotation); - Session.Send(me); + //MovementEventMessage me = new MovementEventMessage(); + //me.ObjectIndex = data.LocalID; + //me.Location = ToOmVector(data.Position); + //me.Orientation = ToOmQuaternion(data.Rotation); + + //MXPSendPrimitive(data.localID, data.ownerID, data.acc, data.rvel, data.primShape, data.pos, data.objectID, data.vel, + // data.rotation, (uint)data.flags, data.text, data.color, data.parentID, data.particleSystem, data.clickAction, + // data.material, data.textureanim); + + //Session.Send(me); + + throw new System.NotImplementedException(); } - public void ReprioritizeUpdates(StateUpdateTypes type, UpdatePriorityHandler handler) + public void ReprioritizeUpdates() { } diff --git a/OpenSim/Client/Sirikata/ClientStack/SirikataClientView.cs b/OpenSim/Client/Sirikata/ClientStack/SirikataClientView.cs index 5287222ec5..072be411c4 100644 --- a/OpenSim/Client/Sirikata/ClientStack/SirikataClientView.cs +++ b/OpenSim/Client/Sirikata/ClientStack/SirikataClientView.cs @@ -507,6 +507,10 @@ namespace OpenSim.Client.Sirikata.ClientStack throw new System.NotImplementedException(); } + public void SendGenericMessage(string method, List message) + { + } + public void SendGenericMessage(string method, List message) { throw new System.NotImplementedException(); @@ -587,16 +591,6 @@ namespace OpenSim.Client.Sirikata.ClientStack throw new System.NotImplementedException(); } - public void SendAvatarData(SendAvatarData data) - { - throw new System.NotImplementedException(); - } - - public void SendAvatarTerseUpdate(SendAvatarTerseData data) - { - throw new System.NotImplementedException(); - } - public void SendCoarseLocationUpdate(List users, List CoarseLocations) { throw new System.NotImplementedException(); @@ -612,22 +606,17 @@ namespace OpenSim.Client.Sirikata.ClientStack throw new System.NotImplementedException(); } - public void SendPrimitiveToClient(SendPrimitiveData data) + public void SendAvatarDataImmediate(ISceneEntity avatar) { throw new System.NotImplementedException(); } - public void SendPrimTerseUpdate(SendPrimitiveTerseData data) + public void SendPrimUpdate(ISceneEntity entity, PrimUpdateFlags updateFlags) { throw new System.NotImplementedException(); } - public void ReprioritizeUpdates(StateUpdateTypes type, UpdatePriorityHandler handler) - { - throw new System.NotImplementedException(); - } - - public void SendInventoryFolderDetails(UUID ownerID, UUID folderID, List items, List folders, int version, bool fetchFolders, bool fetchItems) + public void ReprioritizeUpdates() { throw new System.NotImplementedException(); } @@ -637,6 +626,11 @@ namespace OpenSim.Client.Sirikata.ClientStack throw new System.NotImplementedException(); } + public void SendInventoryFolderDetails(UUID ownerID, UUID folderID, List items, List folders, int version, bool fetchFolders, bool fetchItems) + { + throw new System.NotImplementedException(); + } + public void SendInventoryItemDetails(UUID ownerID, InventoryItemBase item) { throw new System.NotImplementedException(); diff --git a/OpenSim/Client/VWoHTTP/ClientStack/VWHClientView.cs b/OpenSim/Client/VWoHTTP/ClientStack/VWHClientView.cs index f9b7efca01..4711035b20 100644 --- a/OpenSim/Client/VWoHTTP/ClientStack/VWHClientView.cs +++ b/OpenSim/Client/VWoHTTP/ClientStack/VWHClientView.cs @@ -513,6 +513,10 @@ namespace OpenSim.Client.VWoHTTP.ClientStack throw new System.NotImplementedException(); } + public void SendGenericMessage(string method, List message) + { + } + public void SendGenericMessage(string method, List message) { throw new System.NotImplementedException(); @@ -593,16 +597,6 @@ namespace OpenSim.Client.VWoHTTP.ClientStack throw new System.NotImplementedException(); } - public void SendAvatarData(SendAvatarData data) - { - throw new System.NotImplementedException(); - } - - public void SendAvatarTerseUpdate(SendAvatarTerseData data) - { - throw new System.NotImplementedException(); - } - public void SendCoarseLocationUpdate(List users, List CoarseLocations) { throw new System.NotImplementedException(); @@ -618,17 +612,17 @@ namespace OpenSim.Client.VWoHTTP.ClientStack throw new System.NotImplementedException(); } - public void SendPrimitiveToClient(SendPrimitiveData data) + public void SendAvatarDataImmediate(ISceneEntity avatar) { throw new System.NotImplementedException(); } - public void SendPrimTerseUpdate(SendPrimitiveTerseData data) + public void SendPrimUpdate(ISceneEntity entity, PrimUpdateFlags updateFlags) { throw new System.NotImplementedException(); } - public void ReprioritizeUpdates(StateUpdateTypes type, UpdatePriorityHandler handler) + public void ReprioritizeUpdates() { throw new System.NotImplementedException(); } diff --git a/OpenSim/Data/AssetDataBase.cs b/OpenSim/Data/AssetDataBase.cs index 5deb44e61e..e1a810c9af 100644 --- a/OpenSim/Data/AssetDataBase.cs +++ b/OpenSim/Data/AssetDataBase.cs @@ -48,5 +48,6 @@ namespace OpenSim.Data public abstract void Initialise(string connect); public abstract void Initialise(); public abstract void Dispose(); + public abstract bool Delete(string id); } } diff --git a/OpenSim/Data/DBGuids.cs b/OpenSim/Data/DBGuids.cs new file mode 100644 index 0000000000..fb6832b8d1 --- /dev/null +++ b/OpenSim/Data/DBGuids.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Text; +using OpenMetaverse; + +namespace OpenSim.Data +{ + + public static class DBGuid + { + ///

This function converts a value returned from the database in one of the + /// supported formats into a UUID. This function is not actually DBMS-specific right + /// now + /// + /// + /// + /// + public static UUID FromDB(object id) + { + if( (id == null) || (id == DBNull.Value)) + return UUID.Zero; + + if (id.GetType() == typeof(Guid)) + return new UUID((Guid)id); + + if (id.GetType() == typeof(byte[])) + { + if (((byte[])id).Length == 0) + return UUID.Zero; + else if (((byte[])id).Length == 16) + return new UUID((byte[])id, 0); + } + else if (id.GetType() == typeof(string)) + { + if (((string)id).Length == 0) + return UUID.Zero; + else if (((string)id).Length == 36) + return new UUID((string)id); + } + + throw new Exception("Failed to convert db value to UUID: " + id.ToString()); + } + } +} diff --git a/OpenSim/Data/IAssetData.cs b/OpenSim/Data/IAssetData.cs index 2149bcac0a..90d5eeb489 100644 --- a/OpenSim/Data/IAssetData.cs +++ b/OpenSim/Data/IAssetData.cs @@ -38,6 +38,7 @@ namespace OpenSim.Data bool ExistsAsset(UUID uuid); List FetchAssetMetadataSet(int start, int count); void Initialise(string connect); + bool Delete(string id); } public class AssetDataInitialiser : PluginInitialiserBase diff --git a/OpenSim/Data/IGridUserData.cs b/OpenSim/Data/IGridUserData.cs index bd7a435391..e15a1f88a5 100644 --- a/OpenSim/Data/IGridUserData.cs +++ b/OpenSim/Data/IGridUserData.cs @@ -37,6 +37,11 @@ namespace OpenSim.Data { public string UserID; public Dictionary Data; + + public GridUserData() + { + Data = new Dictionary(); + } } /// @@ -44,7 +49,7 @@ namespace OpenSim.Data /// public interface IGridUserData { - GridUserData GetGridUserData(string userID); - bool StoreGridUserData(GridUserData data); + GridUserData Get(string userID); + bool Store(GridUserData data); } } \ No newline at end of file diff --git a/OpenSim/Data/IPresenceData.cs b/OpenSim/Data/IPresenceData.cs index 71d0e31a1f..b871f5636c 100644 --- a/OpenSim/Data/IPresenceData.cs +++ b/OpenSim/Data/IPresenceData.cs @@ -50,10 +50,8 @@ namespace OpenSim.Data PresenceData Get(UUID sessionID); void LogoutRegionAgents(UUID regionID); - bool ReportAgent(UUID sessionID, UUID regionID, string position, string lookAt); - bool SetHomeLocation(string userID, UUID regionID, Vector3 position, Vector3 lookAt); + bool ReportAgent(UUID sessionID, UUID regionID); PresenceData[] Get(string field, string data); - void Prune(string userID); bool Delete(string field, string val); } } diff --git a/OpenSim/Data/MSSQL/MSSQLAssetData.cs b/OpenSim/Data/MSSQL/MSSQLAssetData.cs index d6ea26254a..c7488d853c 100644 --- a/OpenSim/Data/MSSQL/MSSQLAssetData.cs +++ b/OpenSim/Data/MSSQL/MSSQLAssetData.cs @@ -121,15 +121,16 @@ namespace OpenSim.Data.MSSQL if (reader.Read()) { AssetBase asset = new AssetBase( - new UUID((Guid)reader["id"]), + DBGuid.FromDB(reader["id"]), (string)reader["name"], Convert.ToSByte(reader["assetType"]), - String.Empty + reader["creatorid"].ToString() ); // Region Main asset.Description = (string)reader["description"]; asset.Local = Convert.ToBoolean(reader["local"]); asset.Temporary = Convert.ToBoolean(reader["temporary"]); + asset.Flags = (AssetFlags)(Convert.ToInt32(reader["asset_flags"])); asset.Data = (byte[])reader["data"]; return asset; } @@ -144,26 +145,19 @@ namespace OpenSim.Data.MSSQL /// the asset override public void StoreAsset(AssetBase asset) { - if (ExistsAsset(asset.FullID)) - UpdateAsset(asset); - else - InsertAsset(asset); - } - - - private void InsertAsset(AssetBase asset) - { - if (ExistsAsset(asset.FullID)) - { - return; - } - - string sql = @"INSERT INTO assets - ([id], [name], [description], [assetType], [local], - [temporary], [create_time], [access_time], [data]) - VALUES - (@id, @name, @description, @assetType, @local, - @temporary, @create_time, @access_time, @data)"; + + string sql = + @"IF EXISTS(SELECT * FROM assets WHERE id=@id) + UPDATE assets set name = @name, description = @description, assetType = @assetType, + local = @local, temporary = @temporary, creatorid = @creatorid, data = @data + WHERE id=@id + ELSE + INSERT INTO assets + ([id], [name], [description], [assetType], [local], + [temporary], [create_time], [access_time], [creatorid], [asset_flags], [data]) + VALUES + (@id, @name, @description, @assetType, @local, + @temporary, @create_time, @access_time, @creatorid, @asset_flags, @data)"; string assetName = asset.Name; if (asset.Name.Length > 64) @@ -191,6 +185,8 @@ namespace OpenSim.Data.MSSQL command.Parameters.Add(m_database.CreateParameter("temporary", asset.Temporary)); command.Parameters.Add(m_database.CreateParameter("access_time", now)); command.Parameters.Add(m_database.CreateParameter("create_time", now)); + command.Parameters.Add(m_database.CreateParameter("asset_flags", (int)asset.Flags)); + command.Parameters.Add(m_database.CreateParameter("creatorid", asset.Metadata.CreatorID)); command.Parameters.Add(m_database.CreateParameter("data", asset.Data)); conn.Open(); try @@ -199,57 +195,11 @@ namespace OpenSim.Data.MSSQL } catch(Exception e) { - m_log.Error("[ASSET DB]: Error inserting item :" + e.Message); + m_log.Error("[ASSET DB]: Error storing item :" + e.Message); } } } - /// - /// Update asset in m_database - /// - /// the asset - private void UpdateAsset(AssetBase asset) - { - string sql = @"UPDATE assets set id = @id, name = @name, description = @description, assetType = @assetType, - local = @local, temporary = @temporary, data = @data - WHERE id = @keyId;"; - - string assetName = asset.Name; - if (asset.Name.Length > 64) - { - assetName = asset.Name.Substring(0, 64); - m_log.Warn("[ASSET DB]: Name field truncated from " + asset.Name.Length + " to " + assetName.Length + " characters on update"); - } - - string assetDescription = asset.Description; - if (asset.Description.Length > 64) - { - assetDescription = asset.Description.Substring(0, 64); - m_log.Warn("[ASSET DB]: Description field truncated from " + asset.Description.Length + " to " + assetDescription.Length + " characters on update"); - } - - using (SqlConnection conn = new SqlConnection(m_connectionString)) - using (SqlCommand command = new SqlCommand(sql, conn)) - { - command.Parameters.Add(m_database.CreateParameter("id", asset.FullID)); - command.Parameters.Add(m_database.CreateParameter("name", assetName)); - command.Parameters.Add(m_database.CreateParameter("description", assetDescription)); - command.Parameters.Add(m_database.CreateParameter("assetType", asset.Type)); - command.Parameters.Add(m_database.CreateParameter("local", asset.Local)); - command.Parameters.Add(m_database.CreateParameter("temporary", asset.Temporary)); - command.Parameters.Add(m_database.CreateParameter("data", asset.Data)); - command.Parameters.Add(m_database.CreateParameter("@keyId", asset.FullID)); - conn.Open(); - try - { - command.ExecuteNonQuery(); - } - catch (Exception e) - { - m_log.Error(e.ToString()); - } - } - } // Commented out since currently unused - this probably should be called in GetAsset() // private void UpdateAccessTime(AssetBase asset) @@ -295,26 +245,34 @@ namespace OpenSim.Data.MSSQL public override List FetchAssetMetadataSet(int start, int count) { List retList = new List(count); - string sql = @"SELECT (name,description,assetType,temporary,id), Row = ROW_NUMBER() - OVER (ORDER BY (some column to order by)) - WHERE Row >= @Start AND Row < @Start + @Count"; + string sql = @"WITH OrderedAssets AS + ( + SELECT id, name, description, assetType, temporary, creatorid, + RowNumber = ROW_NUMBER() OVER (ORDER BY id) + FROM assets + ) + SELECT * + FROM OrderedAssets + WHERE RowNumber BETWEEN @start AND @stop;"; using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.Add(m_database.CreateParameter("start", start)); - cmd.Parameters.Add(m_database.CreateParameter("count", count)); + cmd.Parameters.Add(m_database.CreateParameter("stop", start + count - 1)); conn.Open(); using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { AssetMetadata metadata = new AssetMetadata(); - metadata.FullID = new UUID((Guid)reader["id"]); + metadata.FullID = DBGuid.FromDB(reader["id"]); metadata.Name = (string)reader["name"]; metadata.Description = (string)reader["description"]; metadata.Type = Convert.ToSByte(reader["assetType"]); metadata.Temporary = Convert.ToBoolean(reader["temporary"]); + metadata.CreatorID = (string)reader["creatorid"]; + retList.Add(metadata); } } } @@ -322,6 +280,10 @@ namespace OpenSim.Data.MSSQL return retList; } + public override bool Delete(string id) + { + return false; + } #endregion } } diff --git a/OpenSim/Data/MSSQL/MSSQLEstateData.cs b/OpenSim/Data/MSSQL/MSSQLEstateData.cs index 474f706ed3..80bf10638d 100644 --- a/OpenSim/Data/MSSQL/MSSQLEstateData.cs +++ b/OpenSim/Data/MSSQL/MSSQLEstateData.cs @@ -37,7 +37,7 @@ using OpenSim.Region.Framework.Interfaces; namespace OpenSim.Data.MSSQL { - public class MSSQLEstateData : IEstateDataStore + public class MSSQLEstateStore : IEstateDataStore { private const string _migrationStore = "EstateStore"; @@ -101,22 +101,30 @@ namespace OpenSim.Data.MSSQL { foreach (string name in FieldList) { - if (_FieldMap[name].GetValue(es) is bool) + FieldInfo f = _FieldMap[name]; + object v = reader[name]; + if (f.FieldType == typeof(bool) ) { - int v = Convert.ToInt32(reader[name]); - if (v != 0) - _FieldMap[name].SetValue(es, true); - else - _FieldMap[name].SetValue(es, false); + f.SetValue(es, Convert.ToInt32(v) != 0); } - else if (_FieldMap[name].GetValue(es) is UUID) + else if (f.FieldType == typeof(UUID) ) { - _FieldMap[name].SetValue(es, new UUID((Guid)reader[name])); // uuid); + f.SetValue(es, new UUID((Guid)v)); // uuid); + } + else if (f.FieldType == typeof(string)) + { + f.SetValue(es, v.ToString()); + } + else if (f.FieldType == typeof(UInt32)) + { + f.SetValue(es, Convert.ToUInt32(v)); + } + else if (f.FieldType == typeof(Single)) + { + f.SetValue(es, Convert.ToSingle(v)); } else - { - es.EstateID = Convert.ToUInt32(reader["EstateID"].ToString()); - } + f.SetValue(es, v); } } else @@ -288,61 +296,45 @@ namespace OpenSim.Data.MSSQL private void SaveBanList(EstateSettings es) { //Delete first - string sql = "delete from estateban where EstateID = @EstateID"; using (SqlConnection conn = new SqlConnection(m_connectionString)) - using (SqlCommand cmd = new SqlCommand(sql, conn)) { - cmd.Parameters.Add(_Database.CreateParameter("@EstateID", es.EstateID)); conn.Open(); - cmd.ExecuteNonQuery(); - } - - //Insert after - sql = "insert into estateban (EstateID, bannedUUID) values ( @EstateID, @bannedUUID )"; - using (SqlConnection conn = new SqlConnection(m_connectionString)) - using (SqlCommand cmd = new SqlCommand(sql, conn)) - { - foreach (EstateBan b in es.EstateBans) + using (SqlCommand cmd = conn.CreateCommand()) { - cmd.Parameters.Add(_Database.CreateParameter("@EstateID", es.EstateID)); - cmd.Parameters.Add(_Database.CreateParameter("@bannedUUID", b.BannedUserID)); - conn.Open(); + cmd.CommandText = "delete from estateban where EstateID = @EstateID"; + cmd.Parameters.AddWithValue("@EstateID", (int)es.EstateID); cmd.ExecuteNonQuery(); - cmd.Parameters.Clear(); + + //Insert after + cmd.CommandText = "insert into estateban (EstateID, bannedUUID) values ( @EstateID, @bannedUUID )"; + cmd.Parameters.AddWithValue("@bannedUUID", Guid.Empty); + foreach (EstateBan b in es.EstateBans) + { + cmd.Parameters["@bannedUUID"].Value = b.BannedUserID.Guid; + cmd.ExecuteNonQuery(); + } } } } private void SaveUUIDList(uint estateID, string table, UUID[] data) { - //Delete first - string sql = string.Format("delete from {0} where EstateID = @EstateID", table); using (SqlConnection conn = new SqlConnection(m_connectionString)) - using (SqlCommand cmd = new SqlCommand(sql, conn)) { - cmd.Parameters.Add(_Database.CreateParameter("@EstateID", estateID)); - cmd.ExecuteNonQuery(); - } - - sql = string.Format("insert into {0} (EstateID, uuid) values ( @EstateID, @uuid )", table); - using (SqlConnection conn = new SqlConnection(m_connectionString)) - using (SqlCommand cmd = new SqlCommand(sql, conn)) - { - cmd.Parameters.Add(_Database.CreateParameter("@EstateID", estateID)); - - bool createParamOnce = true; - - foreach (UUID uuid in data) + conn.Open(); + using (SqlCommand cmd = conn.CreateCommand()) { - if (createParamOnce) - { - cmd.Parameters.Add(_Database.CreateParameter("@uuid", uuid)); - createParamOnce = false; - } - else - cmd.Parameters["@uuid"].Value = uuid.Guid; //.ToString(); //TODO check if this works - conn.Open(); + cmd.Parameters.AddWithValue("@EstateID", (int)estateID); + cmd.CommandText = string.Format("delete from {0} where EstateID = @EstateID", table); cmd.ExecuteNonQuery(); + + cmd.CommandText = string.Format("insert into {0} (EstateID, uuid) values ( @EstateID, @uuid )", table); + cmd.Parameters.AddWithValue("@uuid", Guid.Empty); + foreach (UUID uuid in data) + { + cmd.Parameters["@uuid"].Value = uuid.Guid; //.ToString(); //TODO check if this works + cmd.ExecuteNonQuery(); + } } } } diff --git a/OpenSim/Data/MSSQL/MSSQLGridUserData.cs b/OpenSim/Data/MSSQL/MSSQLGridUserData.cs index 9993720a04..1870273616 100644 --- a/OpenSim/Data/MSSQL/MSSQLGridUserData.cs +++ b/OpenSim/Data/MSSQL/MSSQLGridUserData.cs @@ -46,11 +46,11 @@ namespace OpenSim.Data.MSSQL private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public MSSQLGridUserData(string connectionString, string realm) : - base(connectionString, realm, "UserGrid") + base(connectionString, realm, "GridUserStore") { } - public GridUserData GetGridUserData(string userID) + public GridUserData Get(string userID) { GridUserData[] ret = Get("UserID", userID); @@ -60,9 +60,5 @@ namespace OpenSim.Data.MSSQL return ret[0]; } - public bool StoreGridUserData(GridUserData data) - { - return Store(data); - } } } diff --git a/OpenSim/Data/MSSQL/MSSQLInventoryData.cs b/OpenSim/Data/MSSQL/MSSQLInventoryData.cs index 4815700c2b..4d06377452 100644 --- a/OpenSim/Data/MSSQL/MSSQLInventoryData.cs +++ b/OpenSim/Data/MSSQL/MSSQLInventoryData.cs @@ -111,6 +111,9 @@ namespace OpenSim.Data.MSSQL /// A list of folder objects public List getUserRootFolders(UUID user) { + if (user == UUID.Zero) + return new List(); + return getInventoryFolders(UUID.Zero, user); } @@ -184,7 +187,19 @@ namespace OpenSim.Data.MSSQL //Note maybe change this to use a Dataset that loading in all folders of a user and then go throw it that way. //Note this is changed so it opens only one connection to the database and not everytime it wants to get data. + /* NOTE: the implementation below is very inefficient (makes a separate request to get subfolders for + * every found folder, recursively). Inventory code for other DBs has been already rewritten to get ALL + * inventory for a specific user at once. + * + * Meanwhile, one little thing is corrected: getFolderHierarchy(UUID.Zero) doesn't make sense and should never + * be used, so check for that and return an empty list. + */ + List folders = new List(); + + if (parentID == UUID.Zero) + return folders; + string sql = "SELECT * FROM inventoryfolders WHERE parentFolderID = @parentID"; using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand cmd = new SqlCommand(sql, conn)) @@ -249,13 +264,12 @@ namespace OpenSim.Data.MSSQL /// Folder to update public void updateInventoryFolder(InventoryFolderBase folder) { - string sql = @"UPDATE inventoryfolders SET folderID = @folderID, - agentID = @agentID, + string sql = @"UPDATE inventoryfolders SET agentID = @agentID, parentFolderID = @parentFolderID, folderName = @folderName, type = @type, version = @version - WHERE folderID = @keyFolderID"; + WHERE folderID = @folderID"; string folderName = folder.Name; if (folderName.Length > 64) @@ -272,7 +286,6 @@ namespace OpenSim.Data.MSSQL cmd.Parameters.Add(database.CreateParameter("folderName", folderName)); cmd.Parameters.Add(database.CreateParameter("type", folder.Type)); cmd.Parameters.Add(database.CreateParameter("version", folder.Version)); - cmd.Parameters.Add(database.CreateParameter("@keyFolderID", folder.ID)); conn.Open(); try { @@ -296,7 +309,7 @@ namespace OpenSim.Data.MSSQL using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.Add(database.CreateParameter("parentFolderID", folder.ParentID)); - cmd.Parameters.Add(database.CreateParameter("@folderID", folder.ID)); + cmd.Parameters.Add(database.CreateParameter("folderID", folder.ID)); conn.Open(); try { @@ -489,8 +502,7 @@ namespace OpenSim.Data.MSSQL /// Inventory item to update public void updateInventoryItem(InventoryItemBase item) { - string sql = @"UPDATE inventoryitems SET inventoryID = @inventoryID, - assetID = @assetID, + string sql = @"UPDATE inventoryitems SET assetID = @assetID, assetType = @assetType, parentFolderID = @parentFolderID, avatarID = @avatarID, @@ -502,13 +514,14 @@ namespace OpenSim.Data.MSSQL creatorID = @creatorID, inventoryBasePermissions = @inventoryBasePermissions, inventoryEveryOnePermissions = @inventoryEveryOnePermissions, + inventoryGroupPermissions = @inventoryGroupPermissions, salePrice = @salePrice, saleType = @saleType, creationDate = @creationDate, groupID = @groupID, groupOwned = @groupOwned, flags = @flags - WHERE inventoryID = @keyInventoryID"; + WHERE inventoryID = @inventoryID"; string itemName = item.Name; if (item.Name.Length > 64) @@ -537,16 +550,16 @@ namespace OpenSim.Data.MSSQL command.Parameters.Add(database.CreateParameter("inventoryNextPermissions", item.NextPermissions)); command.Parameters.Add(database.CreateParameter("inventoryCurrentPermissions", item.CurrentPermissions)); command.Parameters.Add(database.CreateParameter("invType", item.InvType)); - command.Parameters.Add(database.CreateParameter("creatorID", item.CreatorIdAsUuid)); + command.Parameters.Add(database.CreateParameter("creatorID", item.CreatorId)); command.Parameters.Add(database.CreateParameter("inventoryBasePermissions", item.BasePermissions)); command.Parameters.Add(database.CreateParameter("inventoryEveryOnePermissions", item.EveryOnePermissions)); + command.Parameters.Add(database.CreateParameter("inventoryGroupPermissions", item.GroupPermissions)); command.Parameters.Add(database.CreateParameter("salePrice", item.SalePrice)); command.Parameters.Add(database.CreateParameter("saleType", item.SaleType)); command.Parameters.Add(database.CreateParameter("creationDate", item.CreationDate)); command.Parameters.Add(database.CreateParameter("groupID", item.GroupID)); command.Parameters.Add(database.CreateParameter("groupOwned", item.GroupOwned)); command.Parameters.Add(database.CreateParameter("flags", item.Flags)); - command.Parameters.Add(database.CreateParameter("keyInventoryID", item.ID)); conn.Open(); try { @@ -732,9 +745,9 @@ namespace OpenSim.Data.MSSQL try { InventoryFolderBase folder = new InventoryFolderBase(); - folder.Owner = new UUID((Guid)reader["agentID"]); - folder.ParentID = new UUID((Guid)reader["parentFolderID"]); - folder.ID = new UUID((Guid)reader["folderID"]); + folder.Owner = DBGuid.FromDB(reader["agentID"]); + folder.ParentID = DBGuid.FromDB(reader["parentFolderID"]); + folder.ID = DBGuid.FromDB(reader["folderID"]); folder.Name = (string)reader["folderName"]; folder.Type = (short)reader["type"]; folder.Version = Convert.ToUInt16(reader["version"]); @@ -760,24 +773,24 @@ namespace OpenSim.Data.MSSQL { InventoryItemBase item = new InventoryItemBase(); - item.ID = new UUID((Guid)reader["inventoryID"]); - item.AssetID = new UUID((Guid)reader["assetID"]); + item.ID = DBGuid.FromDB(reader["inventoryID"]); + item.AssetID = DBGuid.FromDB(reader["assetID"]); item.AssetType = Convert.ToInt32(reader["assetType"].ToString()); - item.Folder = new UUID((Guid)reader["parentFolderID"]); - item.Owner = new UUID((Guid)reader["avatarID"]); + item.Folder = DBGuid.FromDB(reader["parentFolderID"]); + item.Owner = DBGuid.FromDB(reader["avatarID"]); item.Name = reader["inventoryName"].ToString(); item.Description = reader["inventoryDescription"].ToString(); item.NextPermissions = Convert.ToUInt32(reader["inventoryNextPermissions"]); item.CurrentPermissions = Convert.ToUInt32(reader["inventoryCurrentPermissions"]); item.InvType = Convert.ToInt32(reader["invType"].ToString()); - item.CreatorId = ((Guid)reader["creatorID"]).ToString(); + item.CreatorId = reader["creatorID"].ToString(); item.BasePermissions = Convert.ToUInt32(reader["inventoryBasePermissions"]); item.EveryOnePermissions = Convert.ToUInt32(reader["inventoryEveryOnePermissions"]); item.GroupPermissions = Convert.ToUInt32(reader["inventoryGroupPermissions"]); item.SalePrice = Convert.ToInt32(reader["salePrice"]); item.SaleType = Convert.ToByte(reader["saleType"]); item.CreationDate = Convert.ToInt32(reader["creationDate"]); - item.GroupID = new UUID((Guid)reader["groupID"]); + item.GroupID = DBGuid.FromDB(reader["groupID"]); item.GroupOwned = Convert.ToBoolean(reader["groupOwned"]); item.Flags = Convert.ToUInt32(reader["flags"]); diff --git a/OpenSim/Data/MSSQL/MSSQLPresenceData.cs b/OpenSim/Data/MSSQL/MSSQLPresenceData.cs index 5a4ad3a358..e7b3d9c367 100644 --- a/OpenSim/Data/MSSQL/MSSQLPresenceData.cs +++ b/OpenSim/Data/MSSQL/MSSQLPresenceData.cs @@ -67,7 +67,7 @@ namespace OpenSim.Data.MSSQL using (SqlCommand cmd = new SqlCommand()) { - cmd.CommandText = String.Format("UPDATE {0} SET Online='false' WHERE [RegionID]=@RegionID", m_Realm); + cmd.CommandText = String.Format("DELETE FROM {0} WHERE [RegionID]=@RegionID", m_Realm); cmd.Parameters.Add(m_database.CreateParameter("@RegionID", regionID.ToString())); cmd.Connection = conn; @@ -76,8 +76,7 @@ namespace OpenSim.Data.MSSQL } } - public bool ReportAgent(UUID sessionID, UUID regionID, string position, - string lookAt) + public bool ReportAgent(UUID sessionID, UUID regionID) { PresenceData[] pd = Get("SessionID", sessionID.ToString()); if (pd.Length == 0) @@ -88,16 +87,11 @@ namespace OpenSim.Data.MSSQL { cmd.CommandText = String.Format(@"UPDATE {0} SET - [RegionID] = @RegionID, - [Position] = @Position, - [LookAt] = @LookAt, - [Online] = 'true' + [RegionID] = @RegionID WHERE [SessionID] = @SessionID", m_Realm); cmd.Parameters.Add(m_database.CreateParameter("@SessionID", sessionID.ToString())); cmd.Parameters.Add(m_database.CreateParameter("@RegionID", regionID.ToString())); - cmd.Parameters.Add(m_database.CreateParameter("@Position", position.ToString())); - cmd.Parameters.Add(m_database.CreateParameter("@LookAt", lookAt.ToString())); cmd.Connection = conn; conn.Open(); if (cmd.ExecuteNonQuery() == 0) @@ -106,65 +100,5 @@ namespace OpenSim.Data.MSSQL return true; } - public bool SetHomeLocation(string userID, UUID regionID, Vector3 position, Vector3 lookAt) - { - PresenceData[] pd = Get("UserID", userID); - if (pd.Length == 0) - return false; - - using (SqlConnection conn = new SqlConnection(m_ConnectionString)) - using (SqlCommand cmd = new SqlCommand()) - { - - cmd.CommandText = String.Format(@"UPDATE {0} SET - [HomeRegionID] = @HomeRegionID, - [HomePosition] = @HomePosition, - [HomeLookAt] = @HomeLookAt - WHERE [UserID] = @UserID", m_Realm); - - cmd.Parameters.Add(m_database.CreateParameter("@UserID", userID)); - cmd.Parameters.Add(m_database.CreateParameter("@HomeRegionID", regionID.ToString())); - cmd.Parameters.Add(m_database.CreateParameter("@HomePosition", position)); - cmd.Parameters.Add(m_database.CreateParameter("@HomeLookAt", lookAt)); - cmd.Connection = conn; - conn.Open(); - if (cmd.ExecuteNonQuery() == 0) - return false; - } - return true; - } - - public void Prune(string userID) - { - using (SqlConnection conn = new SqlConnection(m_ConnectionString)) - using (SqlCommand cmd = new SqlCommand()) - { - cmd.CommandText = String.Format("SELECT * from {0} WHERE [UserID] = @UserID", m_Realm); - - cmd.Parameters.Add(m_database.CreateParameter("@UserID", userID)); - cmd.Connection = conn; - conn.Open(); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - List deleteSessions = new List(); - int online = 0; - - while (reader.Read()) - { - if (bool.Parse(reader["Online"].ToString())) - online++; - else - deleteSessions.Add(new UUID(reader["SessionID"].ToString())); - } - - if (online == 0 && deleteSessions.Count > 0) - deleteSessions.RemoveAt(0); - - foreach (UUID s in deleteSessions) - Delete("SessionID", s.ToString()); - } - } - } } } diff --git a/OpenSim/Data/MSSQL/Resources/001_AssetStore.sql b/OpenSim/Data/MSSQL/Resources/001_AssetStore.sql deleted file mode 100644 index 2b293c7636..0000000000 --- a/OpenSim/Data/MSSQL/Resources/001_AssetStore.sql +++ /dev/null @@ -1,13 +0,0 @@ -CREATE TABLE [assets] ( - [id] [varchar](36) NOT NULL, - [name] [varchar](64) NOT NULL, - [description] [varchar](64) NOT NULL, - [assetType] [tinyint] NOT NULL, - [local] [tinyint] NOT NULL, - [temporary] [tinyint] NOT NULL, - [data] [image] NOT NULL, -PRIMARY KEY CLUSTERED -( - [id] ASC -)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] -) ON [PRIMARY] diff --git a/OpenSim/Data/MSSQL/Resources/001_EstateStore.sql b/OpenSim/Data/MSSQL/Resources/001_EstateStore.sql deleted file mode 100644 index 9bb2f75965..0000000000 --- a/OpenSim/Data/MSSQL/Resources/001_EstateStore.sql +++ /dev/null @@ -1,85 +0,0 @@ -BEGIN TRANSACTION - -CREATE TABLE [dbo].[estate_managers]( - [EstateID] [int] NOT NULL, - [uuid] [varchar](36) NOT NULL, - CONSTRAINT [PK_estate_managers] PRIMARY KEY CLUSTERED -( - [EstateID] ASC -)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY] -) ON [PRIMARY]; - -CREATE TABLE [dbo].[estate_groups]( - [EstateID] [int] NOT NULL, - [uuid] [varchar](36) NOT NULL, - CONSTRAINT [PK_estate_groups] PRIMARY KEY CLUSTERED -( - [EstateID] ASC -)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY] -) ON [PRIMARY]; - - -CREATE TABLE [dbo].[estate_users]( - [EstateID] [int] NOT NULL, - [uuid] [varchar](36) NOT NULL, - CONSTRAINT [PK_estate_users] PRIMARY KEY CLUSTERED -( - [EstateID] ASC -)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY] -) ON [PRIMARY]; - - -CREATE TABLE [dbo].[estateban]( - [EstateID] [int] NOT NULL, - [bannedUUID] [varchar](36) NOT NULL, - [bannedIp] [varchar](16) NOT NULL, - [bannedIpHostMask] [varchar](16) NOT NULL, - [bannedNameMask] [varchar](64) NULL DEFAULT (NULL), - CONSTRAINT [PK_estateban] PRIMARY KEY CLUSTERED -( - [EstateID] ASC -)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY] -) ON [PRIMARY]; - -CREATE TABLE [dbo].[estate_settings]( - [EstateID] [int] IDENTITY(1,100) NOT NULL, - [EstateName] [varchar](64) NULL DEFAULT (NULL), - [AbuseEmailToEstateOwner] [bit] NOT NULL, - [DenyAnonymous] [bit] NOT NULL, - [ResetHomeOnTeleport] [bit] NOT NULL, - [FixedSun] [bit] NOT NULL, - [DenyTransacted] [bit] NOT NULL, - [BlockDwell] [bit] NOT NULL, - [DenyIdentified] [bit] NOT NULL, - [AllowVoice] [bit] NOT NULL, - [UseGlobalTime] [bit] NOT NULL, - [PricePerMeter] [int] NOT NULL, - [TaxFree] [bit] NOT NULL, - [AllowDirectTeleport] [bit] NOT NULL, - [RedirectGridX] [int] NOT NULL, - [RedirectGridY] [int] NOT NULL, - [ParentEstateID] [int] NOT NULL, - [SunPosition] [float] NOT NULL, - [EstateSkipScripts] [bit] NOT NULL, - [BillableFactor] [float] NOT NULL, - [PublicAccess] [bit] NOT NULL, - [AbuseEmail] [varchar](255) NOT NULL, - [EstateOwner] [varchar](36) NOT NULL, - [DenyMinors] [bit] NOT NULL, - CONSTRAINT [PK_estate_settings] PRIMARY KEY CLUSTERED -( - [EstateID] ASC -)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY] -) ON [PRIMARY]; - - -CREATE TABLE [dbo].[estate_map]( - [RegionID] [varchar](36) NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000'), - [EstateID] [int] NOT NULL, - CONSTRAINT [PK_estate_map] PRIMARY KEY CLUSTERED -( - [RegionID] ASC -)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY] -) ON [PRIMARY]; - -COMMIT \ No newline at end of file diff --git a/OpenSim/Data/MSSQL/Resources/001_GridStore.sql b/OpenSim/Data/MSSQL/Resources/001_GridStore.sql deleted file mode 100644 index ff15f54c07..0000000000 --- a/OpenSim/Data/MSSQL/Resources/001_GridStore.sql +++ /dev/null @@ -1,37 +0,0 @@ -BEGIN TRANSACTION - -CREATE TABLE [dbo].[regions]( - [regionHandle] [varchar](255) COLLATE Latin1_General_CI_AS NULL, - [regionName] [varchar](255) COLLATE Latin1_General_CI_AS NULL, - [uuid] [varchar](255) COLLATE Latin1_General_CI_AS NOT NULL, - [regionRecvKey] [varchar](255) COLLATE Latin1_General_CI_AS NULL, - [regionSecret] [varchar](255) COLLATE Latin1_General_CI_AS NULL, - [regionSendKey] [varchar](255) COLLATE Latin1_General_CI_AS NULL, - [regionDataURI] [varchar](255) COLLATE Latin1_General_CI_AS NULL, - [serverIP] [varchar](255) COLLATE Latin1_General_CI_AS NULL, - [serverPort] [varchar](255) COLLATE Latin1_General_CI_AS NULL, - [serverURI] [varchar](255) COLLATE Latin1_General_CI_AS NULL, - [locX] [varchar](255) COLLATE Latin1_General_CI_AS NULL, - [locY] [varchar](255) COLLATE Latin1_General_CI_AS NULL, - [locZ] [varchar](255) COLLATE Latin1_General_CI_AS NULL, - [eastOverrideHandle] [varchar](255) COLLATE Latin1_General_CI_AS NULL, - [westOverrideHandle] [varchar](255) COLLATE Latin1_General_CI_AS NULL, - [southOverrideHandle] [varchar](255) COLLATE Latin1_General_CI_AS NULL, - [northOverrideHandle] [varchar](255) COLLATE Latin1_General_CI_AS NULL, - [regionAssetURI] [varchar](255) COLLATE Latin1_General_CI_AS NULL, - [regionAssetRecvKey] [varchar](255) COLLATE Latin1_General_CI_AS NULL, - [regionAssetSendKey] [varchar](255) COLLATE Latin1_General_CI_AS NULL, - [regionUserURI] [varchar](255) COLLATE Latin1_General_CI_AS NULL, - [regionUserRecvKey] [varchar](255) COLLATE Latin1_General_CI_AS NULL, - [regionUserSendKey] [varchar](255) COLLATE Latin1_General_CI_AS NULL, - [regionMapTexture] [varchar](255) COLLATE Latin1_General_CI_AS NULL, - [serverHttpPort] [varchar](255) COLLATE Latin1_General_CI_AS NULL, - [serverRemotingPort] [varchar](255) COLLATE Latin1_General_CI_AS NULL, - [owner_uuid] [varchar](36) COLLATE Latin1_General_CI_AS NULL, -PRIMARY KEY CLUSTERED -( - [uuid] ASC -)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY] -) ON [PRIMARY] - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/001_InventoryStore.sql b/OpenSim/Data/MSSQL/Resources/001_InventoryStore.sql deleted file mode 100644 index 836d2d1e2b..0000000000 --- a/OpenSim/Data/MSSQL/Resources/001_InventoryStore.sql +++ /dev/null @@ -1,64 +0,0 @@ -BEGIN TRANSACTION - -CREATE TABLE [inventoryfolders] ( - [folderID] [varchar](36) NOT NULL default '', - [agentID] [varchar](36) default NULL, - [parentFolderID] [varchar](36) default NULL, - [folderName] [varchar](64) default NULL, - [type] [smallint] NOT NULL default 0, - [version] [int] NOT NULL default 0, - PRIMARY KEY CLUSTERED -( - [folderID] ASC -)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] -) ON [PRIMARY] - -CREATE NONCLUSTERED INDEX [owner] ON [inventoryfolders] -( - [agentID] ASC -)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -CREATE NONCLUSTERED INDEX [parent] ON [inventoryfolders] -( - [parentFolderID] ASC -)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - - -CREATE TABLE [inventoryitems] ( - [inventoryID] [varchar](36) NOT NULL default '', - [assetID] [varchar](36) default NULL, - [assetType] [int] default NULL, - [parentFolderID] [varchar](36) default NULL, - [avatarID] [varchar](36) default NULL, - [inventoryName] [varchar](64) default NULL, - [inventoryDescription] [varchar](128) default NULL, - [inventoryNextPermissions] [int] default NULL, - [inventoryCurrentPermissions] [int] default NULL, - [invType] [int] default NULL, - [creatorID] [varchar](36) default NULL, - [inventoryBasePermissions] [int] NOT NULL default 0, - [inventoryEveryOnePermissions] [int] NOT NULL default 0, - [salePrice] [int] default NULL, - [saleType] [tinyint] default NULL, - [creationDate] [int] default NULL, - [groupID] [varchar](36) default NULL, - [groupOwned] [bit] default NULL, - [flags] [int] default NULL, - PRIMARY KEY CLUSTERED -( - [inventoryID] ASC -)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] -) ON [PRIMARY] - - -CREATE NONCLUSTERED INDEX [owner] ON [inventoryitems] -( - [avatarID] ASC -)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -CREATE NONCLUSTERED INDEX [folder] ON [inventoryitems] -( - [parentFolderID] ASC -)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/001_RegionStore.sql b/OpenSim/Data/MSSQL/Resources/001_RegionStore.sql deleted file mode 100644 index fe7c58f8ed..0000000000 --- a/OpenSim/Data/MSSQL/Resources/001_RegionStore.sql +++ /dev/null @@ -1,161 +0,0 @@ -CREATE TABLE [dbo].[prims]( - [UUID] [varchar](255) NOT NULL, - [RegionUUID] [varchar](255) NULL, - [ParentID] [int] NULL, - [CreationDate] [int] NULL, - [Name] [varchar](255) NULL, - [SceneGroupID] [varchar](255) NULL, - [Text] [varchar](255) NULL, - [Description] [varchar](255) NULL, - [SitName] [varchar](255) NULL, - [TouchName] [varchar](255) NULL, - [ObjectFlags] [int] NULL, - [CreatorID] [varchar](255) NULL, - [OwnerID] [varchar](255) NULL, - [GroupID] [varchar](255) NULL, - [LastOwnerID] [varchar](255) NULL, - [OwnerMask] [int] NULL, - [NextOwnerMask] [int] NULL, - [GroupMask] [int] NULL, - [EveryoneMask] [int] NULL, - [BaseMask] [int] NULL, - [PositionX] [float] NULL, - [PositionY] [float] NULL, - [PositionZ] [float] NULL, - [GroupPositionX] [float] NULL, - [GroupPositionY] [float] NULL, - [GroupPositionZ] [float] NULL, - [VelocityX] [float] NULL, - [VelocityY] [float] NULL, - [VelocityZ] [float] NULL, - [AngularVelocityX] [float] NULL, - [AngularVelocityY] [float] NULL, - [AngularVelocityZ] [float] NULL, - [AccelerationX] [float] NULL, - [AccelerationY] [float] NULL, - [AccelerationZ] [float] NULL, - [RotationX] [float] NULL, - [RotationY] [float] NULL, - [RotationZ] [float] NULL, - [RotationW] [float] NULL, - [SitTargetOffsetX] [float] NULL, - [SitTargetOffsetY] [float] NULL, - [SitTargetOffsetZ] [float] NULL, - [SitTargetOrientW] [float] NULL, - [SitTargetOrientX] [float] NULL, - [SitTargetOrientY] [float] NULL, - [SitTargetOrientZ] [float] NULL, -PRIMARY KEY CLUSTERED -( - [UUID] ASC -)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY] -) ON [PRIMARY] - -CREATE TABLE [dbo].[primshapes]( - [UUID] [varchar](255) NOT NULL, - [Shape] [int] NULL, - [ScaleX] [float] NULL, - [ScaleY] [float] NULL, - [ScaleZ] [float] NULL, - [PCode] [int] NULL, - [PathBegin] [int] NULL, - [PathEnd] [int] NULL, - [PathScaleX] [int] NULL, - [PathScaleY] [int] NULL, - [PathShearX] [int] NULL, - [PathShearY] [int] NULL, - [PathSkew] [int] NULL, - [PathCurve] [int] NULL, - [PathRadiusOffset] [int] NULL, - [PathRevolutions] [int] NULL, - [PathTaperX] [int] NULL, - [PathTaperY] [int] NULL, - [PathTwist] [int] NULL, - [PathTwistBegin] [int] NULL, - [ProfileBegin] [int] NULL, - [ProfileEnd] [int] NULL, - [ProfileCurve] [int] NULL, - [ProfileHollow] [int] NULL, - [State] [int] NULL, - [Texture] [image] NULL, - [ExtraParams] [image] NULL, -PRIMARY KEY CLUSTERED -( - [UUID] ASC -)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY] -) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] - -CREATE TABLE [dbo].[primitems]( - [itemID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, - [primID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, - [assetID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, - [parentFolderID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, - [invType] [int] NULL, - [assetType] [int] NULL, - [name] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, - [description] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, - [creationDate] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, - [creatorID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, - [ownerID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, - [lastOwnerID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, - [groupID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, - [nextPermissions] [int] NULL, - [currentPermissions] [int] NULL, - [basePermissions] [int] NULL, - [everyonePermissions] [int] NULL, - [groupPermissions] [int] NULL, -PRIMARY KEY CLUSTERED -( - [itemID] ASC -)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY] -) ON [PRIMARY] - -CREATE TABLE [dbo].[terrain]( - [RegionUUID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, - [Revision] [int] NULL, - [Heightfield] [image] NULL -) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] - -CREATE TABLE [dbo].[land]( - [UUID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, - [RegionUUID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, - [LocalLandID] [int] NULL, - [Bitmap] [image] NULL, - [Name] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, - [Description] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, - [OwnerUUID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, - [IsGroupOwned] [int] NULL, - [Area] [int] NULL, - [AuctionID] [int] NULL, - [Category] [int] NULL, - [ClaimDate] [int] NULL, - [ClaimPrice] [int] NULL, - [GroupUUID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, - [SalePrice] [int] NULL, - [LandStatus] [int] NULL, - [LandFlags] [int] NULL, - [LandingType] [int] NULL, - [MediaAutoScale] [int] NULL, - [MediaTextureUUID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, - [MediaURL] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, - [MusicURL] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, - [PassHours] [float] NULL, - [PassPrice] [int] NULL, - [SnapshotUUID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, - [UserLocationX] [float] NULL, - [UserLocationY] [float] NULL, - [UserLocationZ] [float] NULL, - [UserLookAtX] [float] NULL, - [UserLookAtY] [float] NULL, - [UserLookAtZ] [float] NULL, -PRIMARY KEY CLUSTERED -( - [UUID] ASC -)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY] -) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] - -CREATE TABLE [dbo].[landaccesslist]( - [LandUUID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, - [AccessUUID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, - [Flags] [int] NULL -) ON [PRIMARY] \ No newline at end of file diff --git a/OpenSim/Data/MSSQL/Resources/001_UserAccount.sql b/OpenSim/Data/MSSQL/Resources/001_UserAccount.sql deleted file mode 100644 index 3dbf8a4925..0000000000 --- a/OpenSim/Data/MSSQL/Resources/001_UserAccount.sql +++ /dev/null @@ -1,14 +0,0 @@ -CREATE TABLE [UserAccounts] ( - [PrincipalID] uniqueidentifier NOT NULL, - [ScopeID] uniqueidentifier NOT NULL, - [FirstName] [varchar](64) NOT NULL, - [LastName] [varchar](64) NOT NULL, - [Email] [varchar](64) NULL, - [ServiceURLs] [text] NULL, - [Created] [int] default NULL, - - PRIMARY KEY CLUSTERED -( - [PrincipalID] ASC -)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] -) ON [PRIMARY] diff --git a/OpenSim/Data/MSSQL/Resources/001_UserStore.sql b/OpenSim/Data/MSSQL/Resources/001_UserStore.sql deleted file mode 100644 index 160c457dad..0000000000 --- a/OpenSim/Data/MSSQL/Resources/001_UserStore.sql +++ /dev/null @@ -1,112 +0,0 @@ -CREATE TABLE [users] ( - [UUID] [varchar](36) NOT NULL default '', - [username] [varchar](32) NOT NULL, - [lastname] [varchar](32) NOT NULL, - [passwordHash] [varchar](32) NOT NULL, - [passwordSalt] [varchar](32) NOT NULL, - [homeRegion] [bigint] default NULL, - [homeLocationX] [float] default NULL, - [homeLocationY] [float] default NULL, - [homeLocationZ] [float] default NULL, - [homeLookAtX] [float] default NULL, - [homeLookAtY] [float] default NULL, - [homeLookAtZ] [float] default NULL, - [created] [int] NOT NULL, - [lastLogin] [int] NOT NULL, - [userInventoryURI] [varchar](255) default NULL, - [userAssetURI] [varchar](255) default NULL, - [profileCanDoMask] [int] default NULL, - [profileWantDoMask] [int] default NULL, - [profileAboutText] [ntext], - [profileFirstText] [ntext], - [profileImage] [varchar](36) default NULL, - [profileFirstImage] [varchar](36) default NULL, - [webLoginKey] [varchar](36) default NULL, - PRIMARY KEY CLUSTERED -( - [UUID] ASC -)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] -) ON [PRIMARY] - - -CREATE NONCLUSTERED INDEX [usernames] ON [users] -( - [username] ASC, - [lastname] ASC -)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - - -CREATE TABLE [agents] ( - [UUID] [varchar](36) NOT NULL, - [sessionID] [varchar](36) NOT NULL, - [secureSessionID] [varchar](36) NOT NULL, - [agentIP] [varchar](16) NOT NULL, - [agentPort] [int] NOT NULL, - [agentOnline] [tinyint] NOT NULL, - [loginTime] [int] NOT NULL, - [logoutTime] [int] NOT NULL, - [currentRegion] [varchar](36) NOT NULL, - [currentHandle] [bigint] NOT NULL, - [currentPos] [varchar](64) NOT NULL, - PRIMARY KEY CLUSTERED -( - [UUID] ASC -)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] -) ON [PRIMARY] - - -CREATE NONCLUSTERED INDEX [session] ON [agents] -( - [sessionID] ASC -)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -CREATE NONCLUSTERED INDEX [ssession] ON [agents] -( - [secureSessionID] ASC -)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - - -CREATE TABLE [dbo].[userfriends]( - [ownerID] [varchar](50) COLLATE Latin1_General_CI_AS NOT NULL, - [friendID] [varchar](50) COLLATE Latin1_General_CI_AS NOT NULL, - [friendPerms] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, - [datetimestamp] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL -) ON [PRIMARY] - -CREATE TABLE [avatarappearance] ( - [Owner] [varchar](36) NOT NULL, - [Serial] int NOT NULL, - [Visual_Params] [image] NOT NULL, - [Texture] [image] NOT NULL, - [Avatar_Height] float NOT NULL, - [Body_Item] [varchar](36) NOT NULL, - [Body_Asset] [varchar](36) NOT NULL, - [Skin_Item] [varchar](36) NOT NULL, - [Skin_Asset] [varchar](36) NOT NULL, - [Hair_Item] [varchar](36) NOT NULL, - [Hair_Asset] [varchar](36) NOT NULL, - [Eyes_Item] [varchar](36) NOT NULL, - [Eyes_Asset] [varchar](36) NOT NULL, - [Shirt_Item] [varchar](36) NOT NULL, - [Shirt_Asset] [varchar](36) NOT NULL, - [Pants_Item] [varchar](36) NOT NULL, - [Pants_Asset] [varchar](36) NOT NULL, - [Shoes_Item] [varchar](36) NOT NULL, - [Shoes_Asset] [varchar](36) NOT NULL, - [Socks_Item] [varchar](36) NOT NULL, - [Socks_Asset] [varchar](36) NOT NULL, - [Jacket_Item] [varchar](36) NOT NULL, - [Jacket_Asset] [varchar](36) NOT NULL, - [Gloves_Item] [varchar](36) NOT NULL, - [Gloves_Asset] [varchar](36) NOT NULL, - [Undershirt_Item] [varchar](36) NOT NULL, - [Undershirt_Asset] [varchar](36) NOT NULL, - [Underpants_Item] [varchar](36) NOT NULL, - [Underpants_Asset] [varchar](36) NOT NULL, - [Skirt_Item] [varchar](36) NOT NULL, - [Skirt_Asset] [varchar](36) NOT NULL, - - PRIMARY KEY CLUSTERED ( - [Owner] - ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] -) ON [PRIMARY] diff --git a/OpenSim/Data/MSSQL/Resources/002_AssetStore.sql b/OpenSim/Data/MSSQL/Resources/002_AssetStore.sql deleted file mode 100644 index 3e245432bf..0000000000 --- a/OpenSim/Data/MSSQL/Resources/002_AssetStore.sql +++ /dev/null @@ -1,29 +0,0 @@ -BEGIN TRANSACTION - -CREATE TABLE Tmp_assets - ( - id varchar(36) NOT NULL, - name varchar(64) NOT NULL, - description varchar(64) NOT NULL, - assetType tinyint NOT NULL, - local bit NOT NULL, - temporary bit NOT NULL, - data image NOT NULL - ) ON [PRIMARY] - TEXTIMAGE_ON [PRIMARY] - -IF EXISTS(SELECT * FROM assets) - EXEC('INSERT INTO Tmp_assets (id, name, description, assetType, local, temporary, data) - SELECT id, name, description, assetType, CONVERT(bit, local), CONVERT(bit, temporary), data FROM assets WITH (HOLDLOCK TABLOCKX)') - -DROP TABLE assets - -EXECUTE sp_rename N'Tmp_assets', N'assets', 'OBJECT' - -ALTER TABLE dbo.assets ADD CONSTRAINT - PK__assets__id PRIMARY KEY CLUSTERED - ( - id - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/002_AuthStore.sql b/OpenSim/Data/MSSQL/Resources/002_AuthStore.sql deleted file mode 100644 index daed955932..0000000000 --- a/OpenSim/Data/MSSQL/Resources/002_AuthStore.sql +++ /dev/null @@ -1,6 +0,0 @@ -BEGIN TRANSACTION - -INSERT INTO auth (UUID, passwordHash, passwordSalt, webLoginKey, accountType) SELECT [UUID] AS UUID, [passwordHash] AS passwordHash, [passwordSalt] AS passwordSalt, [webLoginKey] AS webLoginKey, 'UserAccount' as [accountType] FROM users; - - -COMMIT \ No newline at end of file diff --git a/OpenSim/Data/MSSQL/Resources/002_EstateStore.sql b/OpenSim/Data/MSSQL/Resources/002_EstateStore.sql deleted file mode 100644 index 18c12c097c..0000000000 --- a/OpenSim/Data/MSSQL/Resources/002_EstateStore.sql +++ /dev/null @@ -1,25 +0,0 @@ -BEGIN TRANSACTION - -ALTER TABLE dbo.estate_managers DROP CONSTRAINT PK_estate_managers - -CREATE NONCLUSTERED INDEX IX_estate_managers ON dbo.estate_managers - ( - EstateID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -ALTER TABLE dbo.estate_groups DROP CONSTRAINT PK_estate_groups - -CREATE NONCLUSTERED INDEX IX_estate_groups ON dbo.estate_groups - ( - EstateID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - - -ALTER TABLE dbo.estate_users DROP CONSTRAINT PK_estate_users - -CREATE NONCLUSTERED INDEX IX_estate_users ON dbo.estate_users - ( - EstateID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/002_FriendsStore.sql b/OpenSim/Data/MSSQL/Resources/002_FriendsStore.sql deleted file mode 100644 index e67d20e4b7..0000000000 --- a/OpenSim/Data/MSSQL/Resources/002_FriendsStore.sql +++ /dev/null @@ -1,6 +0,0 @@ -BEGIN TRANSACTION - -INSERT INTO Friends (PrincipalID, Friend, Flags, Offered) SELECT [ownerID], [friendID], [friendPerms], 0 FROM userfriends; - - -COMMIT \ No newline at end of file diff --git a/OpenSim/Data/MSSQL/Resources/002_GridStore.sql b/OpenSim/Data/MSSQL/Resources/002_GridStore.sql deleted file mode 100644 index f5901cb527..0000000000 --- a/OpenSim/Data/MSSQL/Resources/002_GridStore.sql +++ /dev/null @@ -1,49 +0,0 @@ -BEGIN TRANSACTION - -CREATE TABLE Tmp_regions - ( - uuid varchar(36) COLLATE Latin1_General_CI_AS NOT NULL, - regionHandle bigint NULL, - regionName varchar(20) NULL, - regionRecvKey varchar(128) NULL, - regionSendKey varchar(128) NULL, - regionSecret varchar(128) NULL, - regionDataURI varchar(128) NULL, - serverIP varchar(64) NULL, - serverPort int NULL, - serverURI varchar(255) NULL, - locX int NULL, - locY int NULL, - locZ int NULL, - eastOverrideHandle bigint NULL, - westOverrideHandle bigint NULL, - southOverrideHandle bigint NULL, - northOverrideHandle bigint NULL, - regionAssetURI varchar(255) NULL, - regionAssetRecvKey varchar(128) NULL, - regionAssetSendKey varchar(128) NULL, - regionUserURI varchar(255) NULL, - regionUserRecvKey varchar(128) NULL, - regionUserSendKey varchar(128) NULL, - regionMapTexture varchar(36) NULL, - serverHttpPort int NULL, - serverRemotingPort int NULL, - owner_uuid varchar(36) NULL, - originUUID varchar(36) NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000') - ) ON [PRIMARY] - -IF EXISTS(SELECT * FROM regions) - EXEC('INSERT INTO Tmp_regions (uuid, regionHandle, regionName, regionRecvKey, regionSendKey, regionSecret, regionDataURI, serverIP, serverPort, serverURI, locX, locY, locZ, eastOverrideHandle, westOverrideHandle, southOverrideHandle, northOverrideHandle, regionAssetURI, regionAssetRecvKey, regionAssetSendKey, regionUserURI, regionUserRecvKey, regionUserSendKey, regionMapTexture, serverHttpPort, serverRemotingPort, owner_uuid) - SELECT CONVERT(varchar(36), uuid), CONVERT(bigint, regionHandle), CONVERT(varchar(20), regionName), CONVERT(varchar(128), regionRecvKey), CONVERT(varchar(128), regionSendKey), CONVERT(varchar(128), regionSecret), CONVERT(varchar(128), regionDataURI), CONVERT(varchar(64), serverIP), CONVERT(int, serverPort), serverURI, CONVERT(int, locX), CONVERT(int, locY), CONVERT(int, locZ), CONVERT(bigint, eastOverrideHandle), CONVERT(bigint, westOverrideHandle), CONVERT(bigint, southOverrideHandle), CONVERT(bigint, northOverrideHandle), regionAssetURI, CONVERT(varchar(128), regionAssetRecvKey), CONVERT(varchar(128), regionAssetSendKey), regionUserURI, CONVERT(varchar(128), regionUserRecvKey), CONVERT(varchar(128), regionUserSendKey), CONVERT(varchar(36), regionMapTexture), CONVERT(int, serverHttpPort), CONVERT(int, serverRemotingPort), owner_uuid FROM regions') - -DROP TABLE regions - -EXECUTE sp_rename N'Tmp_regions', N'regions', 'OBJECT' - -ALTER TABLE regions ADD CONSTRAINT - PK__regions__uuid PRIMARY KEY CLUSTERED - ( - uuid - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -COMMIT \ No newline at end of file diff --git a/OpenSim/Data/MSSQL/Resources/002_InventoryStore.sql b/OpenSim/Data/MSSQL/Resources/002_InventoryStore.sql deleted file mode 100644 index bcc26b88c8..0000000000 --- a/OpenSim/Data/MSSQL/Resources/002_InventoryStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN TRANSACTION - -ALTER TABLE inventoryitems ADD inventoryGroupPermissions INTEGER NOT NULL default 0 - -COMMIT \ No newline at end of file diff --git a/OpenSim/Data/MSSQL/Resources/002_Presence.sql b/OpenSim/Data/MSSQL/Resources/002_Presence.sql deleted file mode 100644 index a67671ddf6..0000000000 --- a/OpenSim/Data/MSSQL/Resources/002_Presence.sql +++ /dev/null @@ -1,6 +0,0 @@ -BEGIN TRANSACTION - -CREATE UNIQUE INDEX SessionID ON Presence(SessionID); -CREATE INDEX UserID ON Presence(UserID); - -COMMIT \ No newline at end of file diff --git a/OpenSim/Data/MSSQL/Resources/002_RegionStore.sql b/OpenSim/Data/MSSQL/Resources/002_RegionStore.sql deleted file mode 100644 index 1801035206..0000000000 --- a/OpenSim/Data/MSSQL/Resources/002_RegionStore.sql +++ /dev/null @@ -1,50 +0,0 @@ -BEGIN TRANSACTION - -CREATE TABLE regionban ( - [regionUUID] VARCHAR(36) NOT NULL, - [bannedUUID] VARCHAR(36) NOT NULL, - [bannedIp] VARCHAR(16) NOT NULL, - [bannedIpHostMask] VARCHAR(16) NOT NULL) - -create table [dbo].[regionsettings] ( - [regionUUID] [varchar](36) not null, - [block_terraform] [bit] not null, - [block_fly] [bit] not null, - [allow_damage] [bit] not null, - [restrict_pushing] [bit] not null, - [allow_land_resell] [bit] not null, - [allow_land_join_divide] [bit] not null, - [block_show_in_search] [bit] not null, - [agent_limit] [int] not null, - [object_bonus] [float] not null, - [maturity] [int] not null, - [disable_scripts] [bit] not null, - [disable_collisions] [bit] not null, - [disable_physics] [bit] not null, - [terrain_texture_1] [varchar](36) not null, - [terrain_texture_2] [varchar](36) not null, - [terrain_texture_3] [varchar](36) not null, - [terrain_texture_4] [varchar](36) not null, - [elevation_1_nw] [float] not null, - [elevation_2_nw] [float] not null, - [elevation_1_ne] [float] not null, - [elevation_2_ne] [float] not null, - [elevation_1_se] [float] not null, - [elevation_2_se] [float] not null, - [elevation_1_sw] [float] not null, - [elevation_2_sw] [float] not null, - [water_height] [float] not null, - [terrain_raise_limit] [float] not null, - [terrain_lower_limit] [float] not null, - [use_estate_sun] [bit] not null, - [fixed_sun] [bit] not null, - [sun_position] [float] not null, - [covenant] [varchar](36) default NULL, - [Sandbox] [bit] NOT NULL, -PRIMARY KEY CLUSTERED -( - [regionUUID] ASC -)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY] -) ON [PRIMARY] - -COMMIT \ No newline at end of file diff --git a/OpenSim/Data/MSSQL/Resources/002_UserAccount.sql b/OpenSim/Data/MSSQL/Resources/002_UserAccount.sql deleted file mode 100644 index 89d1f3495a..0000000000 --- a/OpenSim/Data/MSSQL/Resources/002_UserAccount.sql +++ /dev/null @@ -1,12 +0,0 @@ -BEGIN TRANSACTION - -INSERT INTO UserAccounts (PrincipalID, ScopeID, FirstName, LastName, Email, ServiceURLs, Created) SELECT [UUID] AS PrincipalID, '00000000-0000-0000-0000-000000000000' AS ScopeID, -username AS FirstName, -lastname AS LastName, -email as Email, ( -'AssetServerURI=' + -userAssetURI + ' InventoryServerURI=' + userInventoryURI + ' GatewayURI= HomeURI=') AS ServiceURLs, -created as Created FROM users; - - -COMMIT \ No newline at end of file diff --git a/OpenSim/Data/MSSQL/Resources/002_UserStore.sql b/OpenSim/Data/MSSQL/Resources/002_UserStore.sql deleted file mode 100644 index 402eddf15c..0000000000 --- a/OpenSim/Data/MSSQL/Resources/002_UserStore.sql +++ /dev/null @@ -1,9 +0,0 @@ -BEGIN TRANSACTION - -ALTER TABLE users ADD homeRegionID varchar(36) NOT NULL default '00000000-0000-0000-0000-000000000000'; -ALTER TABLE users ADD userFlags int NOT NULL default 0; -ALTER TABLE users ADD godLevel int NOT NULL default 0; -ALTER TABLE users ADD customType varchar(32) not null default ''; -ALTER TABLE users ADD partner varchar(36) not null default '00000000-0000-0000-0000-000000000000'; - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/003_AssetStore.sql b/OpenSim/Data/MSSQL/Resources/003_AssetStore.sql deleted file mode 100644 index 1434330739..0000000000 --- a/OpenSim/Data/MSSQL/Resources/003_AssetStore.sql +++ /dev/null @@ -1,6 +0,0 @@ -BEGIN TRANSACTION - -ALTER TABLE assets add create_time integer default 0 -ALTER TABLE assets add access_time integer default 0 - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/003_EstateStore.sql b/OpenSim/Data/MSSQL/Resources/003_EstateStore.sql deleted file mode 100644 index 120966ae1d..0000000000 --- a/OpenSim/Data/MSSQL/Resources/003_EstateStore.sql +++ /dev/null @@ -1,25 +0,0 @@ -BEGIN TRANSACTION - -CREATE TABLE dbo.Tmp_estateban - ( - EstateID int NOT NULL, - bannedUUID varchar(36) NOT NULL, - bannedIp varchar(16) NULL, - bannedIpHostMask varchar(16) NULL, - bannedNameMask varchar(64) NULL - ) ON [PRIMARY] - -IF EXISTS(SELECT * FROM dbo.estateban) - EXEC('INSERT INTO dbo.Tmp_estateban (EstateID, bannedUUID, bannedIp, bannedIpHostMask, bannedNameMask) - SELECT EstateID, bannedUUID, bannedIp, bannedIpHostMask, bannedNameMask FROM dbo.estateban') - -DROP TABLE dbo.estateban - -EXECUTE sp_rename N'dbo.Tmp_estateban', N'estateban', 'OBJECT' - -CREATE NONCLUSTERED INDEX IX_estateban ON dbo.estateban - ( - EstateID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/003_GridStore.sql b/OpenSim/Data/MSSQL/Resources/003_GridStore.sql deleted file mode 100644 index e080947665..0000000000 --- a/OpenSim/Data/MSSQL/Resources/003_GridStore.sql +++ /dev/null @@ -1,22 +0,0 @@ -BEGIN TRANSACTION - -CREATE NONCLUSTERED INDEX IX_regions_name ON dbo.regions - ( - regionName - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -CREATE NONCLUSTERED INDEX IX_regions_handle ON dbo.regions - ( - regionHandle - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - - -CREATE NONCLUSTERED INDEX IX_regions_override ON dbo.regions - ( - eastOverrideHandle, - westOverrideHandle, - southOverrideHandle, - northOverrideHandle - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/003_InventoryStore.sql b/OpenSim/Data/MSSQL/Resources/003_InventoryStore.sql deleted file mode 100644 index 2f623ec911..0000000000 --- a/OpenSim/Data/MSSQL/Resources/003_InventoryStore.sql +++ /dev/null @@ -1,38 +0,0 @@ -/* To prevent any potential data loss issues, you should review this script in detail before running it outside the context of the database designer.*/ -BEGIN TRANSACTION - -CREATE TABLE dbo.Tmp_inventoryfolders - ( - folderID uniqueidentifier NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000'), - agentID uniqueidentifier NULL DEFAULT (NULL), - parentFolderID uniqueidentifier NULL DEFAULT (NULL), - folderName varchar(64) NULL DEFAULT (NULL), - type smallint NOT NULL DEFAULT ((0)), - version int NOT NULL DEFAULT ((0)) - ) ON [PRIMARY] - -IF EXISTS(SELECT * FROM dbo.inventoryfolders) - EXEC('INSERT INTO dbo.Tmp_inventoryfolders (folderID, agentID, parentFolderID, folderName, type, version) - SELECT CONVERT(uniqueidentifier, folderID), CONVERT(uniqueidentifier, agentID), CONVERT(uniqueidentifier, parentFolderID), folderName, type, version FROM dbo.inventoryfolders WITH (HOLDLOCK TABLOCKX)') - -DROP TABLE dbo.inventoryfolders - -EXECUTE sp_rename N'dbo.Tmp_inventoryfolders', N'inventoryfolders', 'OBJECT' - -ALTER TABLE dbo.inventoryfolders ADD CONSTRAINT - PK__inventor__C2FABFB3173876EA PRIMARY KEY CLUSTERED - ( - folderID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -CREATE NONCLUSTERED INDEX owner ON dbo.inventoryfolders - ( - agentID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -CREATE NONCLUSTERED INDEX parent ON dbo.inventoryfolders - ( - parentFolderID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/003_RegionStore.sql b/OpenSim/Data/MSSQL/Resources/003_RegionStore.sql deleted file mode 100644 index a8f40c2a86..0000000000 --- a/OpenSim/Data/MSSQL/Resources/003_RegionStore.sql +++ /dev/null @@ -1,67 +0,0 @@ -BEGIN TRANSACTION - -CREATE TABLE dbo.Tmp_prims - ( - UUID varchar(36) NOT NULL, - RegionUUID varchar(36) NULL, - ParentID int NULL, - CreationDate int NULL, - Name varchar(255) NULL, - SceneGroupID varchar(36) NULL, - Text varchar(255) NULL, - Description varchar(255) NULL, - SitName varchar(255) NULL, - TouchName varchar(255) NULL, - ObjectFlags int NULL, - CreatorID varchar(36) NULL, - OwnerID varchar(36) NULL, - GroupID varchar(36) NULL, - LastOwnerID varchar(36) NULL, - OwnerMask int NULL, - NextOwnerMask int NULL, - GroupMask int NULL, - EveryoneMask int NULL, - BaseMask int NULL, - PositionX float(53) NULL, - PositionY float(53) NULL, - PositionZ float(53) NULL, - GroupPositionX float(53) NULL, - GroupPositionY float(53) NULL, - GroupPositionZ float(53) NULL, - VelocityX float(53) NULL, - VelocityY float(53) NULL, - VelocityZ float(53) NULL, - AngularVelocityX float(53) NULL, - AngularVelocityY float(53) NULL, - AngularVelocityZ float(53) NULL, - AccelerationX float(53) NULL, - AccelerationY float(53) NULL, - AccelerationZ float(53) NULL, - RotationX float(53) NULL, - RotationY float(53) NULL, - RotationZ float(53) NULL, - RotationW float(53) NULL, - SitTargetOffsetX float(53) NULL, - SitTargetOffsetY float(53) NULL, - SitTargetOffsetZ float(53) NULL, - SitTargetOrientW float(53) NULL, - SitTargetOrientX float(53) NULL, - SitTargetOrientY float(53) NULL, - SitTargetOrientZ float(53) NULL - ) ON [PRIMARY] - -IF EXISTS(SELECT * FROM dbo.prims) - EXEC('INSERT INTO dbo.Tmp_prims (UUID, RegionUUID, ParentID, CreationDate, Name, SceneGroupID, Text, Description, SitName, TouchName, ObjectFlags, CreatorID, OwnerID, GroupID, LastOwnerID, OwnerMask, NextOwnerMask, GroupMask, EveryoneMask, BaseMask, PositionX, PositionY, PositionZ, GroupPositionX, GroupPositionY, GroupPositionZ, VelocityX, VelocityY, VelocityZ, AngularVelocityX, AngularVelocityY, AngularVelocityZ, AccelerationX, AccelerationY, AccelerationZ, RotationX, RotationY, RotationZ, RotationW, SitTargetOffsetX, SitTargetOffsetY, SitTargetOffsetZ, SitTargetOrientW, SitTargetOrientX, SitTargetOrientY, SitTargetOrientZ) - SELECT CONVERT(varchar(36), UUID), CONVERT(varchar(36), RegionUUID), ParentID, CreationDate, Name, CONVERT(varchar(36), SceneGroupID), Text, Description, SitName, TouchName, ObjectFlags, CONVERT(varchar(36), CreatorID), CONVERT(varchar(36), OwnerID), CONVERT(varchar(36), GroupID), CONVERT(varchar(36), LastOwnerID), OwnerMask, NextOwnerMask, GroupMask, EveryoneMask, BaseMask, PositionX, PositionY, PositionZ, GroupPositionX, GroupPositionY, GroupPositionZ, VelocityX, VelocityY, VelocityZ, AngularVelocityX, AngularVelocityY, AngularVelocityZ, AccelerationX, AccelerationY, AccelerationZ, RotationX, RotationY, RotationZ, RotationW, SitTargetOffsetX, SitTargetOffsetY, SitTargetOffsetZ, SitTargetOrientW, SitTargetOrientX, SitTargetOrientY, SitTargetOrientZ FROM dbo.prims WITH (HOLDLOCK TABLOCKX)') - -DROP TABLE dbo.prims - -EXECUTE sp_rename N'dbo.Tmp_prims', N'prims', 'OBJECT' - -ALTER TABLE dbo.prims ADD CONSTRAINT - PK__prims__10566F31 PRIMARY KEY CLUSTERED - ( - UUID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -COMMIT \ No newline at end of file diff --git a/OpenSim/Data/MSSQL/Resources/003_UserAccount.sql b/OpenSim/Data/MSSQL/Resources/003_UserAccount.sql deleted file mode 100644 index da0395b49c..0000000000 --- a/OpenSim/Data/MSSQL/Resources/003_UserAccount.sql +++ /dev/null @@ -1,9 +0,0 @@ -BEGIN TRANSACTION - -CREATE UNIQUE INDEX PrincipalID ON UserAccounts(PrincipalID); -CREATE INDEX Email ON UserAccounts(Email); -CREATE INDEX FirstName ON UserAccounts(FirstName); -CREATE INDEX LastName ON UserAccounts(LastName); -CREATE INDEX Name ON UserAccounts(FirstName,LastName); - -COMMIT \ No newline at end of file diff --git a/OpenSim/Data/MSSQL/Resources/003_UserStore.sql b/OpenSim/Data/MSSQL/Resources/003_UserStore.sql deleted file mode 100644 index cb507c9630..0000000000 --- a/OpenSim/Data/MSSQL/Resources/003_UserStore.sql +++ /dev/null @@ -1,15 +0,0 @@ -BEGIN TRANSACTION - -CREATE TABLE [avatarattachments] ( - [UUID] varchar(36) NOT NULL - , [attachpoint] int NOT NULL - , [item] varchar(36) NOT NULL - , [asset] varchar(36) NOT NULL) - -CREATE NONCLUSTERED INDEX IX_avatarattachments ON dbo.avatarattachments - ( - UUID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/004_AssetStore.sql b/OpenSim/Data/MSSQL/Resources/004_AssetStore.sql deleted file mode 100644 index 215cf3a14e..0000000000 --- a/OpenSim/Data/MSSQL/Resources/004_AssetStore.sql +++ /dev/null @@ -1,31 +0,0 @@ -BEGIN TRANSACTION - -CREATE TABLE dbo.Tmp_assets - ( - id uniqueidentifier NOT NULL, - name varchar(64) NOT NULL, - description varchar(64) NOT NULL, - assetType tinyint NOT NULL, - local bit NOT NULL, - temporary bit NOT NULL, - data image NOT NULL, - create_time int NULL, - access_time int NULL - ) ON [PRIMARY] - TEXTIMAGE_ON [PRIMARY] - -IF EXISTS(SELECT * FROM dbo.assets) - EXEC('INSERT INTO dbo.Tmp_assets (id, name, description, assetType, local, temporary, data, create_time, access_time) - SELECT CONVERT(uniqueidentifier, id), name, description, assetType, local, temporary, data, create_time, access_time FROM dbo.assets WITH (HOLDLOCK TABLOCKX)') - -DROP TABLE assets - -EXECUTE sp_rename N'Tmp_assets', N'assets', 'OBJECT' - -ALTER TABLE dbo.assets ADD CONSTRAINT - PK__assets__id PRIMARY KEY CLUSTERED - ( - id - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/004_EstateStore.sql b/OpenSim/Data/MSSQL/Resources/004_EstateStore.sql deleted file mode 100644 index 0a132c110e..0000000000 --- a/OpenSim/Data/MSSQL/Resources/004_EstateStore.sql +++ /dev/null @@ -1,22 +0,0 @@ -BEGIN TRANSACTION - -CREATE TABLE dbo.Tmp_estate_managers - ( - EstateID int NOT NULL, - uuid uniqueidentifier NOT NULL - ) ON [PRIMARY] - -IF EXISTS(SELECT * FROM dbo.estate_managers) - EXEC('INSERT INTO dbo.Tmp_estate_managers (EstateID, uuid) - SELECT EstateID, CONVERT(uniqueidentifier, uuid) FROM dbo.estate_managers WITH (HOLDLOCK TABLOCKX)') - -DROP TABLE dbo.estate_managers - -EXECUTE sp_rename N'dbo.Tmp_estate_managers', N'estate_managers', 'OBJECT' - -CREATE NONCLUSTERED INDEX IX_estate_managers ON dbo.estate_managers - ( - EstateID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/004_GridStore.sql b/OpenSim/Data/MSSQL/Resources/004_GridStore.sql deleted file mode 100644 index 6456c95f83..0000000000 --- a/OpenSim/Data/MSSQL/Resources/004_GridStore.sql +++ /dev/null @@ -1,68 +0,0 @@ -/* To prevent any potential data loss issues, you should review this script in detail before running it outside the context of the database designer.*/ -BEGIN TRANSACTION - -CREATE TABLE dbo.Tmp_regions - ( - uuid uniqueidentifier NOT NULL, - regionHandle bigint NULL, - regionName varchar(20) NULL, - regionRecvKey varchar(128) NULL, - regionSendKey varchar(128) NULL, - regionSecret varchar(128) NULL, - regionDataURI varchar(128) NULL, - serverIP varchar(64) NULL, - serverPort int NULL, - serverURI varchar(255) NULL, - locX int NULL, - locY int NULL, - locZ int NULL, - eastOverrideHandle bigint NULL, - westOverrideHandle bigint NULL, - southOverrideHandle bigint NULL, - northOverrideHandle bigint NULL, - regionAssetURI varchar(255) NULL, - regionAssetRecvKey varchar(128) NULL, - regionAssetSendKey varchar(128) NULL, - regionUserURI varchar(255) NULL, - regionUserRecvKey varchar(128) NULL, - regionUserSendKey varchar(128) NULL, - regionMapTexture uniqueidentifier NULL, - serverHttpPort int NULL, - serverRemotingPort int NULL, - owner_uuid uniqueidentifier NOT NULL, - originUUID uniqueidentifier NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000') - ) ON [PRIMARY] - -IF EXISTS(SELECT * FROM dbo.regions) - EXEC('INSERT INTO dbo.Tmp_regions (uuid, regionHandle, regionName, regionRecvKey, regionSendKey, regionSecret, regionDataURI, serverIP, serverPort, serverURI, locX, locY, locZ, eastOverrideHandle, westOverrideHandle, southOverrideHandle, northOverrideHandle, regionAssetURI, regionAssetRecvKey, regionAssetSendKey, regionUserURI, regionUserRecvKey, regionUserSendKey, regionMapTexture, serverHttpPort, serverRemotingPort, owner_uuid, originUUID) - SELECT CONVERT(uniqueidentifier, uuid), regionHandle, regionName, regionRecvKey, regionSendKey, regionSecret, regionDataURI, serverIP, serverPort, serverURI, locX, locY, locZ, eastOverrideHandle, westOverrideHandle, southOverrideHandle, northOverrideHandle, regionAssetURI, regionAssetRecvKey, regionAssetSendKey, regionUserURI, regionUserRecvKey, regionUserSendKey, CONVERT(uniqueidentifier, regionMapTexture), serverHttpPort, serverRemotingPort, CONVERT(uniqueidentifier, owner_uuid), CONVERT(uniqueidentifier, originUUID) FROM dbo.regions WITH (HOLDLOCK TABLOCKX)') - -DROP TABLE dbo.regions - -EXECUTE sp_rename N'dbo.Tmp_regions', N'regions', 'OBJECT' - -ALTER TABLE dbo.regions ADD CONSTRAINT - PK__regions__uuid PRIMARY KEY CLUSTERED - ( - uuid - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -CREATE NONCLUSTERED INDEX IX_regions_name ON dbo.regions - ( - regionName - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -CREATE NONCLUSTERED INDEX IX_regions_handle ON dbo.regions - ( - regionHandle - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -CREATE NONCLUSTERED INDEX IX_regions_override ON dbo.regions - ( - eastOverrideHandle, - westOverrideHandle, - southOverrideHandle, - northOverrideHandle - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/004_InventoryStore.sql b/OpenSim/Data/MSSQL/Resources/004_InventoryStore.sql deleted file mode 100644 index 96ef1c0c90..0000000000 --- a/OpenSim/Data/MSSQL/Resources/004_InventoryStore.sql +++ /dev/null @@ -1,52 +0,0 @@ -BEGIN TRANSACTION - -CREATE TABLE dbo.Tmp_inventoryitems - ( - inventoryID uniqueidentifier NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000'), - assetID uniqueidentifier NULL DEFAULT (NULL), - assetType int NULL DEFAULT (NULL), - parentFolderID uniqueidentifier NULL DEFAULT (NULL), - avatarID uniqueidentifier NULL DEFAULT (NULL), - inventoryName varchar(64) NULL DEFAULT (NULL), - inventoryDescription varchar(128) NULL DEFAULT (NULL), - inventoryNextPermissions int NULL DEFAULT (NULL), - inventoryCurrentPermissions int NULL DEFAULT (NULL), - invType int NULL DEFAULT (NULL), - creatorID uniqueidentifier NULL DEFAULT (NULL), - inventoryBasePermissions int NOT NULL DEFAULT ((0)), - inventoryEveryOnePermissions int NOT NULL DEFAULT ((0)), - salePrice int NULL DEFAULT (NULL), - saleType tinyint NULL DEFAULT (NULL), - creationDate int NULL DEFAULT (NULL), - groupID uniqueidentifier NULL DEFAULT (NULL), - groupOwned bit NULL DEFAULT (NULL), - flags int NULL DEFAULT (NULL), - inventoryGroupPermissions int NOT NULL DEFAULT ((0)) - ) ON [PRIMARY] - -IF EXISTS(SELECT * FROM dbo.inventoryitems) - EXEC('INSERT INTO dbo.Tmp_inventoryitems (inventoryID, assetID, assetType, parentFolderID, avatarID, inventoryName, inventoryDescription, inventoryNextPermissions, inventoryCurrentPermissions, invType, creatorID, inventoryBasePermissions, inventoryEveryOnePermissions, salePrice, saleType, creationDate, groupID, groupOwned, flags, inventoryGroupPermissions) - SELECT CONVERT(uniqueidentifier, inventoryID), CONVERT(uniqueidentifier, assetID), assetType, CONVERT(uniqueidentifier, parentFolderID), CONVERT(uniqueidentifier, avatarID), inventoryName, inventoryDescription, inventoryNextPermissions, inventoryCurrentPermissions, invType, CONVERT(uniqueidentifier, creatorID), inventoryBasePermissions, inventoryEveryOnePermissions, salePrice, saleType, creationDate, CONVERT(uniqueidentifier, groupID), groupOwned, flags, inventoryGroupPermissions FROM dbo.inventoryitems WITH (HOLDLOCK TABLOCKX)') - -DROP TABLE dbo.inventoryitems - -EXECUTE sp_rename N'dbo.Tmp_inventoryitems', N'inventoryitems', 'OBJECT' - -ALTER TABLE dbo.inventoryitems ADD CONSTRAINT - PK__inventor__C4B7BC2220C1E124 PRIMARY KEY CLUSTERED - ( - inventoryID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - - -CREATE NONCLUSTERED INDEX owner ON dbo.inventoryitems - ( - avatarID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -CREATE NONCLUSTERED INDEX folder ON dbo.inventoryitems - ( - parentFolderID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/004_RegionStore.sql b/OpenSim/Data/MSSQL/Resources/004_RegionStore.sql deleted file mode 100644 index 15b39a7fcf..0000000000 --- a/OpenSim/Data/MSSQL/Resources/004_RegionStore.sql +++ /dev/null @@ -1,40 +0,0 @@ -BEGIN TRANSACTION - -CREATE TABLE Tmp_primitems - ( - itemID varchar(36) NOT NULL, - primID varchar(36) NULL, - assetID varchar(36) NULL, - parentFolderID varchar(36) NULL, - invType int NULL, - assetType int NULL, - name varchar(255) NULL, - description varchar(255) NULL, - creationDate varchar(255) NULL, - creatorID varchar(36) NULL, - ownerID varchar(36) NULL, - lastOwnerID varchar(36) NULL, - groupID varchar(36) NULL, - nextPermissions int NULL, - currentPermissions int NULL, - basePermissions int NULL, - everyonePermissions int NULL, - groupPermissions int NULL - ) ON [PRIMARY] - -IF EXISTS(SELECT * FROM primitems) - EXEC('INSERT INTO Tmp_primitems (itemID, primID, assetID, parentFolderID, invType, assetType, name, description, creationDate, creatorID, ownerID, lastOwnerID, groupID, nextPermissions, currentPermissions, basePermissions, everyonePermissions, groupPermissions) - SELECT CONVERT(varchar(36), itemID), CONVERT(varchar(36), primID), CONVERT(varchar(36), assetID), CONVERT(varchar(36), parentFolderID), invType, assetType, name, description, creationDate, CONVERT(varchar(36), creatorID), CONVERT(varchar(36), ownerID), CONVERT(varchar(36), lastOwnerID), CONVERT(varchar(36), groupID), nextPermissions, currentPermissions, basePermissions, everyonePermissions, groupPermissions') - -DROP TABLE primitems - -EXECUTE sp_rename N'Tmp_primitems', N'primitems', 'OBJECT' - -ALTER TABLE primitems ADD CONSTRAINT - PK__primitems__0A688BB1 PRIMARY KEY CLUSTERED - ( - itemID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/004_UserAccount.sql b/OpenSim/Data/MSSQL/Resources/004_UserAccount.sql deleted file mode 100644 index a9a9021cc7..0000000000 --- a/OpenSim/Data/MSSQL/Resources/004_UserAccount.sql +++ /dev/null @@ -1,7 +0,0 @@ -BEGIN TRANSACTION - -ALTER TABLE UserAccounts ADD UserLevel integer NOT NULL DEFAULT 0; -ALTER TABLE UserAccounts ADD UserFlags integer NOT NULL DEFAULT 0; -ALTER TABLE UserAccounts ADD UserTitle varchar(64) NOT NULL DEFAULT ''; - -COMMIT \ No newline at end of file diff --git a/OpenSim/Data/MSSQL/Resources/004_UserStore.sql b/OpenSim/Data/MSSQL/Resources/004_UserStore.sql deleted file mode 100644 index 08f1a1d182..0000000000 --- a/OpenSim/Data/MSSQL/Resources/004_UserStore.sql +++ /dev/null @@ -1,29 +0,0 @@ -BEGIN TRANSACTION - -CREATE TABLE Tmp_userfriends - ( - ownerID varchar(36) NOT NULL, - friendID varchar(36) NOT NULL, - friendPerms int NOT NULL, - datetimestamp int NOT NULL - ) ON [PRIMARY] - -IF EXISTS(SELECT * FROM userfriends) - EXEC('INSERT INTO dbo.Tmp_userfriends (ownerID, friendID, friendPerms, datetimestamp) - SELECT CONVERT(varchar(36), ownerID), CONVERT(varchar(36), friendID), CONVERT(int, friendPerms), CONVERT(int, datetimestamp) FROM dbo.userfriends WITH (HOLDLOCK TABLOCKX)') - -DROP TABLE dbo.userfriends - -EXECUTE sp_rename N'Tmp_userfriends', N'userfriends', 'OBJECT' - -CREATE NONCLUSTERED INDEX IX_userfriends_ownerID ON userfriends - ( - ownerID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -CREATE NONCLUSTERED INDEX IX_userfriends_friendID ON userfriends - ( - friendID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/005_AssetStore.sql b/OpenSim/Data/MSSQL/Resources/005_AssetStore.sql deleted file mode 100644 index 4e95b2b693..0000000000 --- a/OpenSim/Data/MSSQL/Resources/005_AssetStore.sql +++ /dev/null @@ -1 +0,0 @@ -DELETE FROM assets WHERE id = 'dc4b9f0b-d008-45c6-96a4-01dd947ac621'; diff --git a/OpenSim/Data/MSSQL/Resources/005_EstateStore.sql b/OpenSim/Data/MSSQL/Resources/005_EstateStore.sql deleted file mode 100644 index ba93b39ff4..0000000000 --- a/OpenSim/Data/MSSQL/Resources/005_EstateStore.sql +++ /dev/null @@ -1,22 +0,0 @@ -BEGIN TRANSACTION - -CREATE TABLE dbo.Tmp_estate_groups - ( - EstateID int NOT NULL, - uuid uniqueidentifier NOT NULL - ) ON [PRIMARY] - -IF EXISTS(SELECT * FROM dbo.estate_groups) - EXEC('INSERT INTO dbo.Tmp_estate_groups (EstateID, uuid) - SELECT EstateID, CONVERT(uniqueidentifier, uuid) FROM dbo.estate_groups WITH (HOLDLOCK TABLOCKX)') - -DROP TABLE dbo.estate_groups - -EXECUTE sp_rename N'dbo.Tmp_estate_groups', N'estate_groups', 'OBJECT' - -CREATE NONCLUSTERED INDEX IX_estate_groups ON dbo.estate_groups - ( - EstateID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/005_GridStore.sql b/OpenSim/Data/MSSQL/Resources/005_GridStore.sql deleted file mode 100644 index aa04a33019..0000000000 --- a/OpenSim/Data/MSSQL/Resources/005_GridStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN TRANSACTION - -ALTER TABLE regions ADD access int default 0; - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/005_RegionStore.sql b/OpenSim/Data/MSSQL/Resources/005_RegionStore.sql deleted file mode 100644 index eb0862c9bd..0000000000 --- a/OpenSim/Data/MSSQL/Resources/005_RegionStore.sql +++ /dev/null @@ -1,49 +0,0 @@ -BEGIN TRANSACTION - -CREATE TABLE Tmp_primshapes - ( - UUID varchar(36) NOT NULL, - Shape int NULL, - ScaleX float(53) NULL, - ScaleY float(53) NULL, - ScaleZ float(53) NULL, - PCode int NULL, - PathBegin int NULL, - PathEnd int NULL, - PathScaleX int NULL, - PathScaleY int NULL, - PathShearX int NULL, - PathShearY int NULL, - PathSkew int NULL, - PathCurve int NULL, - PathRadiusOffset int NULL, - PathRevolutions int NULL, - PathTaperX int NULL, - PathTaperY int NULL, - PathTwist int NULL, - PathTwistBegin int NULL, - ProfileBegin int NULL, - ProfileEnd int NULL, - ProfileCurve int NULL, - ProfileHollow int NULL, - State int NULL, - Texture image NULL, - ExtraParams image NULL - ) ON [PRIMARY] - TEXTIMAGE_ON [PRIMARY] - -IF EXISTS(SELECT * FROM primshapes) - EXEC('INSERT INTO Tmp_primshapes (UUID, Shape, ScaleX, ScaleY, ScaleZ, PCode, PathBegin, PathEnd, PathScaleX, PathScaleY, PathShearX, PathShearY, PathSkew, PathCurve, PathRadiusOffset, PathRevolutions, PathTaperX, PathTaperY, PathTwist, PathTwistBegin, ProfileBegin, ProfileEnd, ProfileCurve, ProfileHollow, State, Texture, ExtraParams) - SELECT CONVERT(varchar(36), UUID), Shape, ScaleX, ScaleY, ScaleZ, PCode, PathBegin, PathEnd, PathScaleX, PathScaleY, PathShearX, PathShearY, PathSkew, PathCurve, PathRadiusOffset, PathRevolutions, PathTaperX, PathTaperY, PathTwist, PathTwistBegin, ProfileBegin, ProfileEnd, ProfileCurve, ProfileHollow, State, Texture, ExtraParams FROM primshapes WITH (HOLDLOCK TABLOCKX)') - -DROP TABLE primshapes - -EXECUTE sp_rename N'Tmp_primshapes', N'primshapes', 'OBJECT' - -ALTER TABLE primshapes ADD CONSTRAINT - PK__primshapes__0880433F PRIMARY KEY CLUSTERED - ( - UUID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/005_UserStore.sql b/OpenSim/Data/MSSQL/Resources/005_UserStore.sql deleted file mode 100644 index 1b6ab8f7da..0000000000 --- a/OpenSim/Data/MSSQL/Resources/005_UserStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN TRANSACTION - - ALTER TABLE users add email varchar(250); - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/006_EstateStore.sql b/OpenSim/Data/MSSQL/Resources/006_EstateStore.sql deleted file mode 100644 index f7df8fda18..0000000000 --- a/OpenSim/Data/MSSQL/Resources/006_EstateStore.sql +++ /dev/null @@ -1,22 +0,0 @@ -BEGIN TRANSACTION - -CREATE TABLE dbo.Tmp_estate_users - ( - EstateID int NOT NULL, - uuid uniqueidentifier NOT NULL - ) ON [PRIMARY] - -IF EXISTS(SELECT * FROM dbo.estate_users) - EXEC('INSERT INTO dbo.Tmp_estate_users (EstateID, uuid) - SELECT EstateID, CONVERT(uniqueidentifier, uuid) FROM dbo.estate_users WITH (HOLDLOCK TABLOCKX)') - -DROP TABLE dbo.estate_users - -EXECUTE sp_rename N'dbo.Tmp_estate_users', N'estate_users', 'OBJECT' - -CREATE NONCLUSTERED INDEX IX_estate_users ON dbo.estate_users - ( - EstateID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/006_GridStore.sql b/OpenSim/Data/MSSQL/Resources/006_GridStore.sql deleted file mode 100644 index 42010ce657..0000000000 --- a/OpenSim/Data/MSSQL/Resources/006_GridStore.sql +++ /dev/null @@ -1,8 +0,0 @@ -BEGIN TRANSACTION - -ALTER TABLE regions ADD scopeid uniqueidentifier default '00000000-0000-0000-0000-000000000000'; -ALTER TABLE regions ADD DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [owner_uuid]; -ALTER TABLE regions ADD sizeX integer not null default 0; -ALTER TABLE regions ADD sizeY integer not null default 0; - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/006_RegionStore.sql b/OpenSim/Data/MSSQL/Resources/006_RegionStore.sql deleted file mode 100644 index 0419c0c8a6..0000000000 --- a/OpenSim/Data/MSSQL/Resources/006_RegionStore.sql +++ /dev/null @@ -1,36 +0,0 @@ -BEGIN TRANSACTION - -ALTER TABLE prims ADD PayPrice int not null default 0 -ALTER TABLE prims ADD PayButton1 int not null default 0 -ALTER TABLE prims ADD PayButton2 int not null default 0 -ALTER TABLE prims ADD PayButton3 int not null default 0 -ALTER TABLE prims ADD PayButton4 int not null default 0 -ALTER TABLE prims ADD LoopedSound varchar(36) not null default '00000000-0000-0000-0000-000000000000'; -ALTER TABLE prims ADD LoopedSoundGain float not null default 0.0; -ALTER TABLE prims ADD TextureAnimation image -ALTER TABLE prims ADD OmegaX float not null default 0.0 -ALTER TABLE prims ADD OmegaY float not null default 0.0 -ALTER TABLE prims ADD OmegaZ float not null default 0.0 -ALTER TABLE prims ADD CameraEyeOffsetX float not null default 0.0 -ALTER TABLE prims ADD CameraEyeOffsetY float not null default 0.0 -ALTER TABLE prims ADD CameraEyeOffsetZ float not null default 0.0 -ALTER TABLE prims ADD CameraAtOffsetX float not null default 0.0 -ALTER TABLE prims ADD CameraAtOffsetY float not null default 0.0 -ALTER TABLE prims ADD CameraAtOffsetZ float not null default 0.0 -ALTER TABLE prims ADD ForceMouselook tinyint not null default 0 -ALTER TABLE prims ADD ScriptAccessPin int not null default 0 -ALTER TABLE prims ADD AllowedDrop tinyint not null default 0 -ALTER TABLE prims ADD DieAtEdge tinyint not null default 0 -ALTER TABLE prims ADD SalePrice int not null default 10 -ALTER TABLE prims ADD SaleType tinyint not null default 0 - -ALTER TABLE primitems add flags integer not null default 0 - -ALTER TABLE land ADD AuthbuyerID varchar(36) NOT NULL default '00000000-0000-0000-0000-000000000000' - -CREATE index prims_regionuuid on prims(RegionUUID) -CREATE index prims_parentid on prims(ParentID) - -CREATE index primitems_primid on primitems(primID) - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/006_UserStore.sql b/OpenSim/Data/MSSQL/Resources/006_UserStore.sql deleted file mode 100644 index 67fe5818a8..0000000000 --- a/OpenSim/Data/MSSQL/Resources/006_UserStore.sql +++ /dev/null @@ -1,57 +0,0 @@ -BEGIN TRANSACTION - -CREATE TABLE dbo.Tmp_users - ( - UUID uniqueidentifier NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000'), - username varchar(32) NOT NULL, - lastname varchar(32) NOT NULL, - passwordHash varchar(32) NOT NULL, - passwordSalt varchar(32) NOT NULL, - homeRegion bigint NULL DEFAULT (NULL), - homeLocationX float(53) NULL DEFAULT (NULL), - homeLocationY float(53) NULL DEFAULT (NULL), - homeLocationZ float(53) NULL DEFAULT (NULL), - homeLookAtX float(53) NULL DEFAULT (NULL), - homeLookAtY float(53) NULL DEFAULT (NULL), - homeLookAtZ float(53) NULL DEFAULT (NULL), - created int NOT NULL, - lastLogin int NOT NULL, - userInventoryURI varchar(255) NULL DEFAULT (NULL), - userAssetURI varchar(255) NULL DEFAULT (NULL), - profileCanDoMask int NULL DEFAULT (NULL), - profileWantDoMask int NULL DEFAULT (NULL), - profileAboutText ntext NULL, - profileFirstText ntext NULL, - profileImage uniqueidentifier NULL DEFAULT (NULL), - profileFirstImage uniqueidentifier NULL DEFAULT (NULL), - webLoginKey uniqueidentifier NULL DEFAULT (NULL), - homeRegionID uniqueidentifier NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000'), - userFlags int NOT NULL DEFAULT ((0)), - godLevel int NOT NULL DEFAULT ((0)), - customType varchar(32) NOT NULL DEFAULT (''), - partner uniqueidentifier NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000'), - email varchar(250) NULL - ) ON [PRIMARY] - TEXTIMAGE_ON [PRIMARY] - -IF EXISTS(SELECT * FROM dbo.users) - EXEC('INSERT INTO dbo.Tmp_users (UUID, username, lastname, passwordHash, passwordSalt, homeRegion, homeLocationX, homeLocationY, homeLocationZ, homeLookAtX, homeLookAtY, homeLookAtZ, created, lastLogin, userInventoryURI, userAssetURI, profileCanDoMask, profileWantDoMask, profileAboutText, profileFirstText, profileImage, profileFirstImage, webLoginKey, homeRegionID, userFlags, godLevel, customType, partner, email) - SELECT CONVERT(uniqueidentifier, UUID), username, lastname, passwordHash, passwordSalt, homeRegion, homeLocationX, homeLocationY, homeLocationZ, homeLookAtX, homeLookAtY, homeLookAtZ, created, lastLogin, userInventoryURI, userAssetURI, profileCanDoMask, profileWantDoMask, profileAboutText, profileFirstText, CONVERT(uniqueidentifier, profileImage), CONVERT(uniqueidentifier, profileFirstImage), CONVERT(uniqueidentifier, webLoginKey), CONVERT(uniqueidentifier, homeRegionID), userFlags, godLevel, customType, CONVERT(uniqueidentifier, partner), email FROM dbo.users WITH (HOLDLOCK TABLOCKX)') - -DROP TABLE dbo.users - -EXECUTE sp_rename N'dbo.Tmp_users', N'users', 'OBJECT' - -ALTER TABLE dbo.users ADD CONSTRAINT - PK__users__65A475E737A5467C PRIMARY KEY CLUSTERED - ( - UUID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -CREATE NONCLUSTERED INDEX usernames ON dbo.users - ( - username, - lastname - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/007_EstateStore.sql b/OpenSim/Data/MSSQL/Resources/007_EstateStore.sql deleted file mode 100644 index c9165b0c6d..0000000000 --- a/OpenSim/Data/MSSQL/Resources/007_EstateStore.sql +++ /dev/null @@ -1,25 +0,0 @@ -BEGIN TRANSACTION - -CREATE TABLE dbo.Tmp_estateban - ( - EstateID int NOT NULL, - bannedUUID uniqueidentifier NOT NULL, - bannedIp varchar(16) NULL, - bannedIpHostMask varchar(16) NULL, - bannedNameMask varchar(64) NULL - ) ON [PRIMARY] - -IF EXISTS(SELECT * FROM dbo.estateban) - EXEC('INSERT INTO dbo.Tmp_estateban (EstateID, bannedUUID, bannedIp, bannedIpHostMask, bannedNameMask) - SELECT EstateID, CONVERT(uniqueidentifier, bannedUUID), bannedIp, bannedIpHostMask, bannedNameMask FROM dbo.estateban WITH (HOLDLOCK TABLOCKX)') - -DROP TABLE dbo.estateban - -EXECUTE sp_rename N'dbo.Tmp_estateban', N'estateban', 'OBJECT' - -CREATE NONCLUSTERED INDEX IX_estateban ON dbo.estateban - ( - EstateID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/007_GridStore.sql b/OpenSim/Data/MSSQL/Resources/007_GridStore.sql deleted file mode 100644 index 0b66d40b47..0000000000 --- a/OpenSim/Data/MSSQL/Resources/007_GridStore.sql +++ /dev/null @@ -1,9 +0,0 @@ -BEGIN TRANSACTION - -ALTER TABLE regions ADD [flags] integer NOT NULL DEFAULT 0; -CREATE INDEX [flags] ON regions(flags); -ALTER TABLE [regions] ADD [last_seen] integer NOT NULL DEFAULT 0; -ALTER TABLE [regions] ADD [PrincipalID] uniqueidentifier NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000'; -ALTER TABLE [regions] ADD [Token] varchar(255) NOT NULL DEFAULT 0; - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/007_RegionStore.sql b/OpenSim/Data/MSSQL/Resources/007_RegionStore.sql deleted file mode 100644 index 684f937334..0000000000 --- a/OpenSim/Data/MSSQL/Resources/007_RegionStore.sql +++ /dev/null @@ -1,10 +0,0 @@ -BEGIN TRANSACTION - -ALTER TABLE prims ADD ColorR int not null default 0; -ALTER TABLE prims ADD ColorG int not null default 0; -ALTER TABLE prims ADD ColorB int not null default 0; -ALTER TABLE prims ADD ColorA int not null default 0; -ALTER TABLE prims ADD ParticleSystem IMAGE; -ALTER TABLE prims ADD ClickAction tinyint NOT NULL default 0; - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/007_UserStore.sql b/OpenSim/Data/MSSQL/Resources/007_UserStore.sql deleted file mode 100644 index 92a8fc572a..0000000000 --- a/OpenSim/Data/MSSQL/Resources/007_UserStore.sql +++ /dev/null @@ -1,42 +0,0 @@ -BEGIN TRANSACTION - -CREATE TABLE dbo.Tmp_agents - ( - UUID uniqueidentifier NOT NULL, - sessionID uniqueidentifier NOT NULL, - secureSessionID uniqueidentifier NOT NULL, - agentIP varchar(16) NOT NULL, - agentPort int NOT NULL, - agentOnline tinyint NOT NULL, - loginTime int NOT NULL, - logoutTime int NOT NULL, - currentRegion uniqueidentifier NOT NULL, - currentHandle bigint NOT NULL, - currentPos varchar(64) NOT NULL - ) ON [PRIMARY] - -IF EXISTS(SELECT * FROM dbo.agents) - EXEC('INSERT INTO dbo.Tmp_agents (UUID, sessionID, secureSessionID, agentIP, agentPort, agentOnline, loginTime, logoutTime, currentRegion, currentHandle, currentPos) - SELECT CONVERT(uniqueidentifier, UUID), CONVERT(uniqueidentifier, sessionID), CONVERT(uniqueidentifier, secureSessionID), agentIP, agentPort, agentOnline, loginTime, logoutTime, CONVERT(uniqueidentifier, currentRegion), currentHandle, currentPos FROM dbo.agents WITH (HOLDLOCK TABLOCKX)') - -DROP TABLE dbo.agents - -EXECUTE sp_rename N'dbo.Tmp_agents', N'agents', 'OBJECT' - -ALTER TABLE dbo.agents ADD CONSTRAINT - PK__agents__65A475E749C3F6B7 PRIMARY KEY CLUSTERED - ( - UUID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -CREATE NONCLUSTERED INDEX session ON dbo.agents - ( - sessionID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -CREATE NONCLUSTERED INDEX ssession ON dbo.agents - ( - secureSessionID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/008_EstateStore.sql b/OpenSim/Data/MSSQL/Resources/008_EstateStore.sql deleted file mode 100644 index 9c5355eac7..0000000000 --- a/OpenSim/Data/MSSQL/Resources/008_EstateStore.sql +++ /dev/null @@ -1,49 +0,0 @@ -BEGIN TRANSACTION - -CREATE TABLE dbo.Tmp_estate_settings - ( - EstateID int NOT NULL IDENTITY (1, 100), - EstateName varchar(64) NULL DEFAULT (NULL), - AbuseEmailToEstateOwner bit NOT NULL, - DenyAnonymous bit NOT NULL, - ResetHomeOnTeleport bit NOT NULL, - FixedSun bit NOT NULL, - DenyTransacted bit NOT NULL, - BlockDwell bit NOT NULL, - DenyIdentified bit NOT NULL, - AllowVoice bit NOT NULL, - UseGlobalTime bit NOT NULL, - PricePerMeter int NOT NULL, - TaxFree bit NOT NULL, - AllowDirectTeleport bit NOT NULL, - RedirectGridX int NOT NULL, - RedirectGridY int NOT NULL, - ParentEstateID int NOT NULL, - SunPosition float(53) NOT NULL, - EstateSkipScripts bit NOT NULL, - BillableFactor float(53) NOT NULL, - PublicAccess bit NOT NULL, - AbuseEmail varchar(255) NOT NULL, - EstateOwner uniqueidentifier NOT NULL, - DenyMinors bit NOT NULL - ) ON [PRIMARY] - -SET IDENTITY_INSERT dbo.Tmp_estate_settings ON - -IF EXISTS(SELECT * FROM dbo.estate_settings) - EXEC('INSERT INTO dbo.Tmp_estate_settings (EstateID, EstateName, AbuseEmailToEstateOwner, DenyAnonymous, ResetHomeOnTeleport, FixedSun, DenyTransacted, BlockDwell, DenyIdentified, AllowVoice, UseGlobalTime, PricePerMeter, TaxFree, AllowDirectTeleport, RedirectGridX, RedirectGridY, ParentEstateID, SunPosition, EstateSkipScripts, BillableFactor, PublicAccess, AbuseEmail, EstateOwner, DenyMinors) - SELECT EstateID, EstateName, AbuseEmailToEstateOwner, DenyAnonymous, ResetHomeOnTeleport, FixedSun, DenyTransacted, BlockDwell, DenyIdentified, AllowVoice, UseGlobalTime, PricePerMeter, TaxFree, AllowDirectTeleport, RedirectGridX, RedirectGridY, ParentEstateID, SunPosition, EstateSkipScripts, BillableFactor, PublicAccess, AbuseEmail, CONVERT(uniqueidentifier, EstateOwner), DenyMinors FROM dbo.estate_settings WITH (HOLDLOCK TABLOCKX)') - -SET IDENTITY_INSERT dbo.Tmp_estate_settings OFF - -DROP TABLE dbo.estate_settings - -EXECUTE sp_rename N'dbo.Tmp_estate_settings', N'estate_settings', 'OBJECT' - -ALTER TABLE dbo.estate_settings ADD CONSTRAINT - PK_estate_settings PRIMARY KEY CLUSTERED - ( - EstateID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/008_RegionStore.sql b/OpenSim/Data/MSSQL/Resources/008_RegionStore.sql deleted file mode 100644 index 87d6d80005..0000000000 --- a/OpenSim/Data/MSSQL/Resources/008_RegionStore.sql +++ /dev/null @@ -1,7 +0,0 @@ -BEGIN TRANSACTION - -ALTER TABLE land ADD OtherCleanTime integer NOT NULL default 0; -ALTER TABLE land ADD Dwell integer NOT NULL default 0; - -COMMIT - diff --git a/OpenSim/Data/MSSQL/Resources/008_UserStore.sql b/OpenSim/Data/MSSQL/Resources/008_UserStore.sql deleted file mode 100644 index 505252ba42..0000000000 --- a/OpenSim/Data/MSSQL/Resources/008_UserStore.sql +++ /dev/null @@ -1,29 +0,0 @@ -BEGIN TRANSACTION - -CREATE TABLE dbo.Tmp_userfriends - ( - ownerID uniqueidentifier NOT NULL, - friendID uniqueidentifier NOT NULL, - friendPerms int NOT NULL, - datetimestamp int NOT NULL - ) ON [PRIMARY] - -IF EXISTS(SELECT * FROM dbo.userfriends) - EXEC('INSERT INTO dbo.Tmp_userfriends (ownerID, friendID, friendPerms, datetimestamp) - SELECT CONVERT(uniqueidentifier, ownerID), CONVERT(uniqueidentifier, friendID), friendPerms, datetimestamp FROM dbo.userfriends WITH (HOLDLOCK TABLOCKX)') - -DROP TABLE dbo.userfriends - -EXECUTE sp_rename N'dbo.Tmp_userfriends', N'userfriends', 'OBJECT' - -CREATE NONCLUSTERED INDEX IX_userfriends_ownerID ON dbo.userfriends - ( - ownerID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -CREATE NONCLUSTERED INDEX IX_userfriends_friendID ON dbo.userfriends - ( - friendID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/009_EstateStore.sql b/OpenSim/Data/MSSQL/Resources/009_EstateStore.sql deleted file mode 100644 index f91557c805..0000000000 --- a/OpenSim/Data/MSSQL/Resources/009_EstateStore.sql +++ /dev/null @@ -1,24 +0,0 @@ -BEGIN TRANSACTION - -CREATE TABLE dbo.Tmp_estate_map - ( - RegionID uniqueidentifier NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000'), - EstateID int NOT NULL - ) ON [PRIMARY] - -IF EXISTS(SELECT * FROM dbo.estate_map) - EXEC('INSERT INTO dbo.Tmp_estate_map (RegionID, EstateID) - SELECT CONVERT(uniqueidentifier, RegionID), EstateID FROM dbo.estate_map WITH (HOLDLOCK TABLOCKX)') - -DROP TABLE dbo.estate_map - -EXECUTE sp_rename N'dbo.Tmp_estate_map', N'estate_map', 'OBJECT' - -ALTER TABLE dbo.estate_map ADD CONSTRAINT - PK_estate_map PRIMARY KEY CLUSTERED - ( - RegionID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/009_RegionStore.sql b/OpenSim/Data/MSSQL/Resources/009_RegionStore.sql deleted file mode 100644 index 4ef3b3f125..0000000000 --- a/OpenSim/Data/MSSQL/Resources/009_RegionStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN TRANSACTION - -ALTER TABLE prims ADD Material tinyint NOT NULL default 3 - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/009_UserStore.sql b/OpenSim/Data/MSSQL/Resources/009_UserStore.sql deleted file mode 100644 index b1ab8ba69b..0000000000 --- a/OpenSim/Data/MSSQL/Resources/009_UserStore.sql +++ /dev/null @@ -1,53 +0,0 @@ -BEGIN TRANSACTION - -CREATE TABLE dbo.Tmp_avatarappearance - ( - Owner uniqueidentifier NOT NULL, - Serial int NOT NULL, - Visual_Params image NOT NULL, - Texture image NOT NULL, - Avatar_Height float(53) NOT NULL, - Body_Item uniqueidentifier NOT NULL, - Body_Asset uniqueidentifier NOT NULL, - Skin_Item uniqueidentifier NOT NULL, - Skin_Asset uniqueidentifier NOT NULL, - Hair_Item uniqueidentifier NOT NULL, - Hair_Asset uniqueidentifier NOT NULL, - Eyes_Item uniqueidentifier NOT NULL, - Eyes_Asset uniqueidentifier NOT NULL, - Shirt_Item uniqueidentifier NOT NULL, - Shirt_Asset uniqueidentifier NOT NULL, - Pants_Item uniqueidentifier NOT NULL, - Pants_Asset uniqueidentifier NOT NULL, - Shoes_Item uniqueidentifier NOT NULL, - Shoes_Asset uniqueidentifier NOT NULL, - Socks_Item uniqueidentifier NOT NULL, - Socks_Asset uniqueidentifier NOT NULL, - Jacket_Item uniqueidentifier NOT NULL, - Jacket_Asset uniqueidentifier NOT NULL, - Gloves_Item uniqueidentifier NOT NULL, - Gloves_Asset uniqueidentifier NOT NULL, - Undershirt_Item uniqueidentifier NOT NULL, - Undershirt_Asset uniqueidentifier NOT NULL, - Underpants_Item uniqueidentifier NOT NULL, - Underpants_Asset uniqueidentifier NOT NULL, - Skirt_Item uniqueidentifier NOT NULL, - Skirt_Asset uniqueidentifier NOT NULL - ) ON [PRIMARY] - TEXTIMAGE_ON [PRIMARY] - -IF EXISTS(SELECT * FROM dbo.avatarappearance) - EXEC('INSERT INTO dbo.Tmp_avatarappearance (Owner, Serial, Visual_Params, Texture, Avatar_Height, Body_Item, Body_Asset, Skin_Item, Skin_Asset, Hair_Item, Hair_Asset, Eyes_Item, Eyes_Asset, Shirt_Item, Shirt_Asset, Pants_Item, Pants_Asset, Shoes_Item, Shoes_Asset, Socks_Item, Socks_Asset, Jacket_Item, Jacket_Asset, Gloves_Item, Gloves_Asset, Undershirt_Item, Undershirt_Asset, Underpants_Item, Underpants_Asset, Skirt_Item, Skirt_Asset) - SELECT CONVERT(uniqueidentifier, Owner), Serial, Visual_Params, Texture, Avatar_Height, CONVERT(uniqueidentifier, Body_Item), CONVERT(uniqueidentifier, Body_Asset), CONVERT(uniqueidentifier, Skin_Item), CONVERT(uniqueidentifier, Skin_Asset), CONVERT(uniqueidentifier, Hair_Item), CONVERT(uniqueidentifier, Hair_Asset), CONVERT(uniqueidentifier, Eyes_Item), CONVERT(uniqueidentifier, Eyes_Asset), CONVERT(uniqueidentifier, Shirt_Item), CONVERT(uniqueidentifier, Shirt_Asset), CONVERT(uniqueidentifier, Pants_Item), CONVERT(uniqueidentifier, Pants_Asset), CONVERT(uniqueidentifier, Shoes_Item), CONVERT(uniqueidentifier, Shoes_Asset), CONVERT(uniqueidentifier, Socks_Item), CONVERT(uniqueidentifier, Socks_Asset), CONVERT(uniqueidentifier, Jacket_Item), CONVERT(uniqueidentifier, Jacket_Asset), CONVERT(uniqueidentifier, Gloves_Item), CONVERT(uniqueidentifier, Gloves_Asset), CONVERT(uniqueidentifier, Undershirt_Item), CONVERT(uniqueidentifier, Undershirt_Asset), CONVERT(uniqueidentifier, Underpants_Item), CONVERT(uniqueidentifier, Underpants_Asset), CONVERT(uniqueidentifier, Skirt_Item), CONVERT(uniqueidentifier, Skirt_Asset) FROM dbo.avatarappearance WITH (HOLDLOCK TABLOCKX)') - -DROP TABLE dbo.avatarappearance - -EXECUTE sp_rename N'dbo.Tmp_avatarappearance', N'avatarappearance', 'OBJECT' - -ALTER TABLE dbo.avatarappearance ADD CONSTRAINT - PK__avatarap__7DD115CC4E88ABD4 PRIMARY KEY CLUSTERED - ( - Owner - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/010_RegionStore.sql b/OpenSim/Data/MSSQL/Resources/010_RegionStore.sql deleted file mode 100644 index 74ad9c2e28..0000000000 --- a/OpenSim/Data/MSSQL/Resources/010_RegionStore.sql +++ /dev/null @@ -1,7 +0,0 @@ -BEGIN TRANSACTION - -ALTER TABLE regionsettings ADD sunvectorx float NOT NULL default 0; -ALTER TABLE regionsettings ADD sunvectory float NOT NULL default 0; -ALTER TABLE regionsettings ADD sunvectorz float NOT NULL default 0; - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/010_UserStore.sql b/OpenSim/Data/MSSQL/Resources/010_UserStore.sql deleted file mode 100644 index 0af008aa13..0000000000 --- a/OpenSim/Data/MSSQL/Resources/010_UserStore.sql +++ /dev/null @@ -1,24 +0,0 @@ -BEGIN TRANSACTION - -CREATE TABLE dbo.Tmp_avatarattachments - ( - UUID uniqueidentifier NOT NULL, - attachpoint int NOT NULL, - item uniqueidentifier NOT NULL, - asset uniqueidentifier NOT NULL - ) ON [PRIMARY] - -IF EXISTS(SELECT * FROM dbo.avatarattachments) - EXEC('INSERT INTO dbo.Tmp_avatarattachments (UUID, attachpoint, item, asset) - SELECT CONVERT(uniqueidentifier, UUID), attachpoint, CONVERT(uniqueidentifier, item), CONVERT(uniqueidentifier, asset) FROM dbo.avatarattachments WITH (HOLDLOCK TABLOCKX)') - -DROP TABLE dbo.avatarattachments - -EXECUTE sp_rename N'dbo.Tmp_avatarattachments', N'avatarattachments', 'OBJECT' - -CREATE NONCLUSTERED INDEX IX_avatarattachments ON dbo.avatarattachments - ( - UUID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/011_RegionStore.sql b/OpenSim/Data/MSSQL/Resources/011_RegionStore.sql deleted file mode 100644 index 14c71a3737..0000000000 --- a/OpenSim/Data/MSSQL/Resources/011_RegionStore.sql +++ /dev/null @@ -1,6 +0,0 @@ -BEGIN TRANSACTION - -ALTER TABLE prims ADD CollisionSound char(36) not null default '00000000-0000-0000-0000-000000000000' -ALTER TABLE prims ADD CollisionSoundVolume float not null default 0.0 - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/011_UserStore.sql b/OpenSim/Data/MSSQL/Resources/011_UserStore.sql deleted file mode 100644 index 5aa064fac8..0000000000 --- a/OpenSim/Data/MSSQL/Resources/011_UserStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN TRANSACTION - -ALTER TABLE users ADD scopeID uniqueidentifier not null default '00000000-0000-0000-0000-000000000000' - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/012_RegionStore.sql b/OpenSim/Data/MSSQL/Resources/012_RegionStore.sql deleted file mode 100644 index eef8d9075c..0000000000 --- a/OpenSim/Data/MSSQL/Resources/012_RegionStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN TRANSACTION - -ALTER TABLE prims ADD LinkNumber integer not null default 0 - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/013_RegionStore.sql b/OpenSim/Data/MSSQL/Resources/013_RegionStore.sql deleted file mode 100644 index ef5d4c035c..0000000000 --- a/OpenSim/Data/MSSQL/Resources/013_RegionStore.sql +++ /dev/null @@ -1,112 +0,0 @@ -BEGIN TRANSACTION - -CREATE TABLE dbo.Tmp_prims - ( - UUID uniqueidentifier NOT NULL, - RegionUUID uniqueidentifier NULL, - ParentID int NULL, - CreationDate int NULL, - Name varchar(255) NULL, - SceneGroupID uniqueidentifier NULL, - Text varchar(255) NULL, - Description varchar(255) NULL, - SitName varchar(255) NULL, - TouchName varchar(255) NULL, - ObjectFlags int NULL, - CreatorID uniqueidentifier NULL, - OwnerID uniqueidentifier NULL, - GroupID uniqueidentifier NULL, - LastOwnerID uniqueidentifier NULL, - OwnerMask int NULL, - NextOwnerMask int NULL, - GroupMask int NULL, - EveryoneMask int NULL, - BaseMask int NULL, - PositionX float(53) NULL, - PositionY float(53) NULL, - PositionZ float(53) NULL, - GroupPositionX float(53) NULL, - GroupPositionY float(53) NULL, - GroupPositionZ float(53) NULL, - VelocityX float(53) NULL, - VelocityY float(53) NULL, - VelocityZ float(53) NULL, - AngularVelocityX float(53) NULL, - AngularVelocityY float(53) NULL, - AngularVelocityZ float(53) NULL, - AccelerationX float(53) NULL, - AccelerationY float(53) NULL, - AccelerationZ float(53) NULL, - RotationX float(53) NULL, - RotationY float(53) NULL, - RotationZ float(53) NULL, - RotationW float(53) NULL, - SitTargetOffsetX float(53) NULL, - SitTargetOffsetY float(53) NULL, - SitTargetOffsetZ float(53) NULL, - SitTargetOrientW float(53) NULL, - SitTargetOrientX float(53) NULL, - SitTargetOrientY float(53) NULL, - SitTargetOrientZ float(53) NULL, - PayPrice int NOT NULL DEFAULT ((0)), - PayButton1 int NOT NULL DEFAULT ((0)), - PayButton2 int NOT NULL DEFAULT ((0)), - PayButton3 int NOT NULL DEFAULT ((0)), - PayButton4 int NOT NULL DEFAULT ((0)), - LoopedSound uniqueidentifier NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000'), - LoopedSoundGain float(53) NOT NULL DEFAULT ((0.0)), - TextureAnimation image NULL, - OmegaX float(53) NOT NULL DEFAULT ((0.0)), - OmegaY float(53) NOT NULL DEFAULT ((0.0)), - OmegaZ float(53) NOT NULL DEFAULT ((0.0)), - CameraEyeOffsetX float(53) NOT NULL DEFAULT ((0.0)), - CameraEyeOffsetY float(53) NOT NULL DEFAULT ((0.0)), - CameraEyeOffsetZ float(53) NOT NULL DEFAULT ((0.0)), - CameraAtOffsetX float(53) NOT NULL DEFAULT ((0.0)), - CameraAtOffsetY float(53) NOT NULL DEFAULT ((0.0)), - CameraAtOffsetZ float(53) NOT NULL DEFAULT ((0.0)), - ForceMouselook tinyint NOT NULL DEFAULT ((0)), - ScriptAccessPin int NOT NULL DEFAULT ((0)), - AllowedDrop tinyint NOT NULL DEFAULT ((0)), - DieAtEdge tinyint NOT NULL DEFAULT ((0)), - SalePrice int NOT NULL DEFAULT ((10)), - SaleType tinyint NOT NULL DEFAULT ((0)), - ColorR int NOT NULL DEFAULT ((0)), - ColorG int NOT NULL DEFAULT ((0)), - ColorB int NOT NULL DEFAULT ((0)), - ColorA int NOT NULL DEFAULT ((0)), - ParticleSystem image NULL, - ClickAction tinyint NOT NULL DEFAULT ((0)), - Material tinyint NOT NULL DEFAULT ((3)), - CollisionSound uniqueidentifier NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000'), - CollisionSoundVolume float(53) NOT NULL DEFAULT ((0.0)), - LinkNumber int NOT NULL DEFAULT ((0)) - ) ON [PRIMARY] - TEXTIMAGE_ON [PRIMARY] - -IF EXISTS(SELECT * FROM dbo.prims) - EXEC('INSERT INTO dbo.Tmp_prims (UUID, RegionUUID, ParentID, CreationDate, Name, SceneGroupID, Text, Description, SitName, TouchName, ObjectFlags, CreatorID, OwnerID, GroupID, LastOwnerID, OwnerMask, NextOwnerMask, GroupMask, EveryoneMask, BaseMask, PositionX, PositionY, PositionZ, GroupPositionX, GroupPositionY, GroupPositionZ, VelocityX, VelocityY, VelocityZ, AngularVelocityX, AngularVelocityY, AngularVelocityZ, AccelerationX, AccelerationY, AccelerationZ, RotationX, RotationY, RotationZ, RotationW, SitTargetOffsetX, SitTargetOffsetY, SitTargetOffsetZ, SitTargetOrientW, SitTargetOrientX, SitTargetOrientY, SitTargetOrientZ, PayPrice, PayButton1, PayButton2, PayButton3, PayButton4, LoopedSound, LoopedSoundGain, TextureAnimation, OmegaX, OmegaY, OmegaZ, CameraEyeOffsetX, CameraEyeOffsetY, CameraEyeOffsetZ, CameraAtOffsetX, CameraAtOffsetY, CameraAtOffsetZ, ForceMouselook, ScriptAccessPin, AllowedDrop, DieAtEdge, SalePrice, SaleType, ColorR, ColorG, ColorB, ColorA, ParticleSystem, ClickAction, Material, CollisionSound, CollisionSoundVolume, LinkNumber) - SELECT CONVERT(uniqueidentifier, UUID), CONVERT(uniqueidentifier, RegionUUID), ParentID, CreationDate, Name, CONVERT(uniqueidentifier, SceneGroupID), Text, Description, SitName, TouchName, ObjectFlags, CONVERT(uniqueidentifier, CreatorID), CONVERT(uniqueidentifier, OwnerID), CONVERT(uniqueidentifier, GroupID), CONVERT(uniqueidentifier, LastOwnerID), OwnerMask, NextOwnerMask, GroupMask, EveryoneMask, BaseMask, PositionX, PositionY, PositionZ, GroupPositionX, GroupPositionY, GroupPositionZ, VelocityX, VelocityY, VelocityZ, AngularVelocityX, AngularVelocityY, AngularVelocityZ, AccelerationX, AccelerationY, AccelerationZ, RotationX, RotationY, RotationZ, RotationW, SitTargetOffsetX, SitTargetOffsetY, SitTargetOffsetZ, SitTargetOrientW, SitTargetOrientX, SitTargetOrientY, SitTargetOrientZ, PayPrice, PayButton1, PayButton2, PayButton3, PayButton4, CONVERT(uniqueidentifier, LoopedSound), LoopedSoundGain, TextureAnimation, OmegaX, OmegaY, OmegaZ, CameraEyeOffsetX, CameraEyeOffsetY, CameraEyeOffsetZ, CameraAtOffsetX, CameraAtOffsetY, CameraAtOffsetZ, ForceMouselook, ScriptAccessPin, AllowedDrop, DieAtEdge, SalePrice, SaleType, ColorR, ColorG, ColorB, ColorA, ParticleSystem, ClickAction, Material, CONVERT(uniqueidentifier, CollisionSound), CollisionSoundVolume, LinkNumber FROM dbo.prims WITH (HOLDLOCK TABLOCKX)') - -DROP TABLE dbo.prims - -EXECUTE sp_rename N'dbo.Tmp_prims', N'prims', 'OBJECT' - -ALTER TABLE dbo.prims ADD CONSTRAINT - PK__prims__10566F31 PRIMARY KEY CLUSTERED - ( - UUID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - - -CREATE NONCLUSTERED INDEX prims_regionuuid ON dbo.prims - ( - RegionUUID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -CREATE NONCLUSTERED INDEX prims_parentid ON dbo.prims - ( - ParentID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/014_RegionStore.sql b/OpenSim/Data/MSSQL/Resources/014_RegionStore.sql deleted file mode 100644 index 02f6f55b86..0000000000 --- a/OpenSim/Data/MSSQL/Resources/014_RegionStore.sql +++ /dev/null @@ -1,49 +0,0 @@ -BEGIN TRANSACTION - -CREATE TABLE dbo.Tmp_primshapes - ( - UUID uniqueidentifier NOT NULL, - Shape int NULL, - ScaleX float(53) NULL, - ScaleY float(53) NULL, - ScaleZ float(53) NULL, - PCode int NULL, - PathBegin int NULL, - PathEnd int NULL, - PathScaleX int NULL, - PathScaleY int NULL, - PathShearX int NULL, - PathShearY int NULL, - PathSkew int NULL, - PathCurve int NULL, - PathRadiusOffset int NULL, - PathRevolutions int NULL, - PathTaperX int NULL, - PathTaperY int NULL, - PathTwist int NULL, - PathTwistBegin int NULL, - ProfileBegin int NULL, - ProfileEnd int NULL, - ProfileCurve int NULL, - ProfileHollow int NULL, - State int NULL, - Texture image NULL, - ExtraParams image NULL - ) ON [PRIMARY] - TEXTIMAGE_ON [PRIMARY] - -IF EXISTS(SELECT * FROM dbo.primshapes) - EXEC('INSERT INTO dbo.Tmp_primshapes (UUID, Shape, ScaleX, ScaleY, ScaleZ, PCode, PathBegin, PathEnd, PathScaleX, PathScaleY, PathShearX, PathShearY, PathSkew, PathCurve, PathRadiusOffset, PathRevolutions, PathTaperX, PathTaperY, PathTwist, PathTwistBegin, ProfileBegin, ProfileEnd, ProfileCurve, ProfileHollow, State, Texture, ExtraParams) - SELECT CONVERT(uniqueidentifier, UUID), Shape, ScaleX, ScaleY, ScaleZ, PCode, PathBegin, PathEnd, PathScaleX, PathScaleY, PathShearX, PathShearY, PathSkew, PathCurve, PathRadiusOffset, PathRevolutions, PathTaperX, PathTaperY, PathTwist, PathTwistBegin, ProfileBegin, ProfileEnd, ProfileCurve, ProfileHollow, State, Texture, ExtraParams FROM dbo.primshapes WITH (HOLDLOCK TABLOCKX)') - -DROP TABLE dbo.primshapes - -EXECUTE sp_rename N'dbo.Tmp_primshapes', N'primshapes', 'OBJECT' - -ALTER TABLE dbo.primshapes ADD CONSTRAINT - PK__primshapes__0880433F PRIMARY KEY CLUSTERED - ( - UUID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/015_RegionStore.sql b/OpenSim/Data/MSSQL/Resources/015_RegionStore.sql deleted file mode 100644 index cbaaf88bb9..0000000000 --- a/OpenSim/Data/MSSQL/Resources/015_RegionStore.sql +++ /dev/null @@ -1,45 +0,0 @@ -BEGIN TRANSACTION - -CREATE TABLE dbo.Tmp_primitems - ( - itemID uniqueidentifier NOT NULL, - primID uniqueidentifier NULL, - assetID uniqueidentifier NULL, - parentFolderID uniqueidentifier NULL, - invType int NULL, - assetType int NULL, - name varchar(255) NULL, - description varchar(255) NULL, - creationDate varchar(255) NULL, - creatorID uniqueidentifier NULL, - ownerID uniqueidentifier NULL, - lastOwnerID uniqueidentifier NULL, - groupID uniqueidentifier NULL, - nextPermissions int NULL, - currentPermissions int NULL, - basePermissions int NULL, - everyonePermissions int NULL, - groupPermissions int NULL, - flags int NOT NULL DEFAULT ((0)) - ) ON [PRIMARY] - -IF EXISTS(SELECT * FROM dbo.primitems) - EXEC('INSERT INTO dbo.Tmp_primitems (itemID, primID, assetID, parentFolderID, invType, assetType, name, description, creationDate, creatorID, ownerID, lastOwnerID, groupID, nextPermissions, currentPermissions, basePermissions, everyonePermissions, groupPermissions, flags) - SELECT CONVERT(uniqueidentifier, itemID), CONVERT(uniqueidentifier, primID), CONVERT(uniqueidentifier, assetID), CONVERT(uniqueidentifier, parentFolderID), invType, assetType, name, description, creationDate, CONVERT(uniqueidentifier, creatorID), CONVERT(uniqueidentifier, ownerID), CONVERT(uniqueidentifier, lastOwnerID), CONVERT(uniqueidentifier, groupID), nextPermissions, currentPermissions, basePermissions, everyonePermissions, groupPermissions, flags FROM dbo.primitems WITH (HOLDLOCK TABLOCKX)') - -DROP TABLE dbo.primitems - -EXECUTE sp_rename N'dbo.Tmp_primitems', N'primitems', 'OBJECT' - -ALTER TABLE dbo.primitems ADD CONSTRAINT - PK__primitems__0A688BB1 PRIMARY KEY CLUSTERED - ( - itemID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -CREATE NONCLUSTERED INDEX primitems_primid ON dbo.primitems - ( - primID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/016_RegionStore.sql b/OpenSim/Data/MSSQL/Resources/016_RegionStore.sql deleted file mode 100644 index e91da19b12..0000000000 --- a/OpenSim/Data/MSSQL/Resources/016_RegionStore.sql +++ /dev/null @@ -1,19 +0,0 @@ -BEGIN TRANSACTION - -CREATE TABLE dbo.Tmp_terrain - ( - RegionUUID uniqueidentifier NULL, - Revision int NULL, - Heightfield image NULL - ) ON [PRIMARY] - TEXTIMAGE_ON [PRIMARY] - -IF EXISTS(SELECT * FROM dbo.terrain) - EXEC('INSERT INTO dbo.Tmp_terrain (RegionUUID, Revision, Heightfield) - SELECT CONVERT(uniqueidentifier, RegionUUID), Revision, Heightfield FROM dbo.terrain WITH (HOLDLOCK TABLOCKX)') - -DROP TABLE dbo.terrain - -EXECUTE sp_rename N'dbo.Tmp_terrain', N'terrain', 'OBJECT' - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/017_RegionStore.sql b/OpenSim/Data/MSSQL/Resources/017_RegionStore.sql deleted file mode 100644 index 3d3dbc0ee7..0000000000 --- a/OpenSim/Data/MSSQL/Resources/017_RegionStore.sql +++ /dev/null @@ -1,56 +0,0 @@ -BEGIN TRANSACTION - -CREATE TABLE dbo.Tmp_land - ( - UUID uniqueidentifier NOT NULL, - RegionUUID uniqueidentifier NULL, - LocalLandID int NULL, - Bitmap image NULL, - Name varchar(255) NULL, - Description varchar(255) NULL, - OwnerUUID uniqueidentifier NULL, - IsGroupOwned int NULL, - Area int NULL, - AuctionID int NULL, - Category int NULL, - ClaimDate int NULL, - ClaimPrice int NULL, - GroupUUID uniqueidentifier NULL, - SalePrice int NULL, - LandStatus int NULL, - LandFlags int NULL, - LandingType int NULL, - MediaAutoScale int NULL, - MediaTextureUUID uniqueidentifier NULL, - MediaURL varchar(255) NULL, - MusicURL varchar(255) NULL, - PassHours float(53) NULL, - PassPrice int NULL, - SnapshotUUID uniqueidentifier NULL, - UserLocationX float(53) NULL, - UserLocationY float(53) NULL, - UserLocationZ float(53) NULL, - UserLookAtX float(53) NULL, - UserLookAtY float(53) NULL, - UserLookAtZ float(53) NULL, - AuthbuyerID uniqueidentifier NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000'), - OtherCleanTime int NOT NULL DEFAULT ((0)), - Dwell int NOT NULL DEFAULT ((0)) - ) ON [PRIMARY] - TEXTIMAGE_ON [PRIMARY] - -IF EXISTS(SELECT * FROM dbo.land) - EXEC('INSERT INTO dbo.Tmp_land (UUID, RegionUUID, LocalLandID, Bitmap, Name, Description, OwnerUUID, IsGroupOwned, Area, AuctionID, Category, ClaimDate, ClaimPrice, GroupUUID, SalePrice, LandStatus, LandFlags, LandingType, MediaAutoScale, MediaTextureUUID, MediaURL, MusicURL, PassHours, PassPrice, SnapshotUUID, UserLocationX, UserLocationY, UserLocationZ, UserLookAtX, UserLookAtY, UserLookAtZ, AuthbuyerID, OtherCleanTime, Dwell) - SELECT CONVERT(uniqueidentifier, UUID), CONVERT(uniqueidentifier, RegionUUID), LocalLandID, Bitmap, Name, Description, CONVERT(uniqueidentifier, OwnerUUID), IsGroupOwned, Area, AuctionID, Category, ClaimDate, ClaimPrice, CONVERT(uniqueidentifier, GroupUUID), SalePrice, LandStatus, LandFlags, LandingType, MediaAutoScale, CONVERT(uniqueidentifier, MediaTextureUUID), MediaURL, MusicURL, PassHours, PassPrice, CONVERT(uniqueidentifier, SnapshotUUID), UserLocationX, UserLocationY, UserLocationZ, UserLookAtX, UserLookAtY, UserLookAtZ, CONVERT(uniqueidentifier, AuthbuyerID), OtherCleanTime, Dwell FROM dbo.land WITH (HOLDLOCK TABLOCKX)') - -DROP TABLE dbo.land - -EXECUTE sp_rename N'dbo.Tmp_land', N'land', 'OBJECT' - -ALTER TABLE dbo.land ADD CONSTRAINT - PK__land__65A475E71BFD2C07 PRIMARY KEY CLUSTERED - ( - UUID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/018_RegionStore.sql b/OpenSim/Data/MSSQL/Resources/018_RegionStore.sql deleted file mode 100644 index 6157e3536e..0000000000 --- a/OpenSim/Data/MSSQL/Resources/018_RegionStore.sql +++ /dev/null @@ -1,18 +0,0 @@ -BEGIN TRANSACTION - -CREATE TABLE dbo.Tmp_landaccesslist - ( - LandUUID uniqueidentifier NULL, - AccessUUID uniqueidentifier NULL, - Flags int NULL - ) ON [PRIMARY] - -IF EXISTS(SELECT * FROM dbo.landaccesslist) - EXEC('INSERT INTO dbo.Tmp_landaccesslist (LandUUID, AccessUUID, Flags) - SELECT CONVERT(uniqueidentifier, LandUUID), CONVERT(uniqueidentifier, AccessUUID), Flags FROM dbo.landaccesslist WITH (HOLDLOCK TABLOCKX)') - -DROP TABLE dbo.landaccesslist - -EXECUTE sp_rename N'dbo.Tmp_landaccesslist', N'landaccesslist', 'OBJECT' - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/019_RegionStore.sql b/OpenSim/Data/MSSQL/Resources/019_RegionStore.sql deleted file mode 100644 index 8e613b9d09..0000000000 --- a/OpenSim/Data/MSSQL/Resources/019_RegionStore.sql +++ /dev/null @@ -1,19 +0,0 @@ -BEGIN TRANSACTION - -CREATE TABLE dbo.Tmp_regionban - ( - regionUUID uniqueidentifier NOT NULL, - bannedUUID uniqueidentifier NOT NULL, - bannedIp varchar(16) NOT NULL, - bannedIpHostMask varchar(16) NOT NULL - ) ON [PRIMARY] - -IF EXISTS(SELECT * FROM dbo.regionban) - EXEC('INSERT INTO dbo.Tmp_regionban (regionUUID, bannedUUID, bannedIp, bannedIpHostMask) - SELECT CONVERT(uniqueidentifier, regionUUID), CONVERT(uniqueidentifier, bannedUUID), bannedIp, bannedIpHostMask FROM dbo.regionban WITH (HOLDLOCK TABLOCKX)') - -DROP TABLE dbo.regionban - -EXECUTE sp_rename N'dbo.Tmp_regionban', N'regionban', 'OBJECT' - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/020_RegionStore.sql b/OpenSim/Data/MSSQL/Resources/020_RegionStore.sql deleted file mode 100644 index 2ce91f6dca..0000000000 --- a/OpenSim/Data/MSSQL/Resources/020_RegionStore.sql +++ /dev/null @@ -1,58 +0,0 @@ -BEGIN TRANSACTION - -CREATE TABLE dbo.Tmp_regionsettings - ( - regionUUID uniqueidentifier NOT NULL, - block_terraform bit NOT NULL, - block_fly bit NOT NULL, - allow_damage bit NOT NULL, - restrict_pushing bit NOT NULL, - allow_land_resell bit NOT NULL, - allow_land_join_divide bit NOT NULL, - block_show_in_search bit NOT NULL, - agent_limit int NOT NULL, - object_bonus float(53) NOT NULL, - maturity int NOT NULL, - disable_scripts bit NOT NULL, - disable_collisions bit NOT NULL, - disable_physics bit NOT NULL, - terrain_texture_1 uniqueidentifier NOT NULL, - terrain_texture_2 uniqueidentifier NOT NULL, - terrain_texture_3 uniqueidentifier NOT NULL, - terrain_texture_4 uniqueidentifier NOT NULL, - elevation_1_nw float(53) NOT NULL, - elevation_2_nw float(53) NOT NULL, - elevation_1_ne float(53) NOT NULL, - elevation_2_ne float(53) NOT NULL, - elevation_1_se float(53) NOT NULL, - elevation_2_se float(53) NOT NULL, - elevation_1_sw float(53) NOT NULL, - elevation_2_sw float(53) NOT NULL, - water_height float(53) NOT NULL, - terrain_raise_limit float(53) NOT NULL, - terrain_lower_limit float(53) NOT NULL, - use_estate_sun bit NOT NULL, - fixed_sun bit NOT NULL, - sun_position float(53) NOT NULL, - covenant uniqueidentifier NULL DEFAULT (NULL), - Sandbox bit NOT NULL, - sunvectorx float(53) NOT NULL DEFAULT ((0)), - sunvectory float(53) NOT NULL DEFAULT ((0)), - sunvectorz float(53) NOT NULL DEFAULT ((0)) - ) ON [PRIMARY] - -IF EXISTS(SELECT * FROM dbo.regionsettings) - EXEC('INSERT INTO dbo.Tmp_regionsettings (regionUUID, block_terraform, block_fly, allow_damage, restrict_pushing, allow_land_resell, allow_land_join_divide, block_show_in_search, agent_limit, object_bonus, maturity, disable_scripts, disable_collisions, disable_physics, terrain_texture_1, terrain_texture_2, terrain_texture_3, terrain_texture_4, elevation_1_nw, elevation_2_nw, elevation_1_ne, elevation_2_ne, elevation_1_se, elevation_2_se, elevation_1_sw, elevation_2_sw, water_height, terrain_raise_limit, terrain_lower_limit, use_estate_sun, fixed_sun, sun_position, covenant, Sandbox, sunvectorx, sunvectory, sunvectorz) - SELECT CONVERT(uniqueidentifier, regionUUID), block_terraform, block_fly, allow_damage, restrict_pushing, allow_land_resell, allow_land_join_divide, block_show_in_search, agent_limit, object_bonus, maturity, disable_scripts, disable_collisions, disable_physics, CONVERT(uniqueidentifier, terrain_texture_1), CONVERT(uniqueidentifier, terrain_texture_2), CONVERT(uniqueidentifier, terrain_texture_3), CONVERT(uniqueidentifier, terrain_texture_4), elevation_1_nw, elevation_2_nw, elevation_1_ne, elevation_2_ne, elevation_1_se, elevation_2_se, elevation_1_sw, elevation_2_sw, water_height, terrain_raise_limit, terrain_lower_limit, use_estate_sun, fixed_sun, sun_position, CONVERT(uniqueidentifier, covenant), Sandbox, sunvectorx, sunvectory, sunvectorz FROM dbo.regionsettings WITH (HOLDLOCK TABLOCKX)') - -DROP TABLE dbo.regionsettings - -EXECUTE sp_rename N'dbo.Tmp_regionsettings', N'regionsettings', 'OBJECT' - -ALTER TABLE dbo.regionsettings ADD CONSTRAINT - PK__regionse__5B35159D21B6055D PRIMARY KEY CLUSTERED - ( - regionUUID - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/021_RegionStore.sql b/OpenSim/Data/MSSQL/Resources/021_RegionStore.sql deleted file mode 100644 index ac59182abc..0000000000 --- a/OpenSim/Data/MSSQL/Resources/021_RegionStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN TRANSACTION - -ALTER TABLE prims ADD PassTouches bit not null default 0 - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/022_RegionStore.sql b/OpenSim/Data/MSSQL/Resources/022_RegionStore.sql deleted file mode 100644 index 421e8d3dc7..0000000000 --- a/OpenSim/Data/MSSQL/Resources/022_RegionStore.sql +++ /dev/null @@ -1,7 +0,0 @@ -BEGIN TRANSACTION - -ALTER TABLE regionsettings ADD loaded_creation_date varchar(20) -ALTER TABLE regionsettings ADD loaded_creation_time varchar(20) -ALTER TABLE regionsettings ADD loaded_creation_id varchar(64) - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/023_RegionStore.sql b/OpenSim/Data/MSSQL/Resources/023_RegionStore.sql deleted file mode 100644 index 75a16f3fb0..0000000000 --- a/OpenSim/Data/MSSQL/Resources/023_RegionStore.sql +++ /dev/null @@ -1,7 +0,0 @@ -BEGIN TRANSACTION - -ALTER TABLE regionsettings DROP COLUMN loaded_creation_date -ALTER TABLE regionsettings DROP COLUMN loaded_creation_time -ALTER TABLE regionsettings ADD loaded_creation_datetime int NOT NULL default 0 - -COMMIT diff --git a/OpenSim/Data/MSSQL/Resources/AssetStore.migrations b/OpenSim/Data/MSSQL/Resources/AssetStore.migrations new file mode 100644 index 0000000000..8664ce985b --- /dev/null +++ b/OpenSim/Data/MSSQL/Resources/AssetStore.migrations @@ -0,0 +1,106 @@ +:VERSION 1 + +CREATE TABLE [assets] ( + [id] [varchar](36) NOT NULL, + [name] [varchar](64) NOT NULL, + [description] [varchar](64) NOT NULL, + [assetType] [tinyint] NOT NULL, + [local] [tinyint] NOT NULL, + [temporary] [tinyint] NOT NULL, + [data] [image] NOT NULL, +PRIMARY KEY CLUSTERED +( + [id] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] +) ON [PRIMARY] + + +:VERSION 2 + +BEGIN TRANSACTION + +CREATE TABLE Tmp_assets + ( + id varchar(36) NOT NULL, + name varchar(64) NOT NULL, + description varchar(64) NOT NULL, + assetType tinyint NOT NULL, + local bit NOT NULL, + temporary bit NOT NULL, + data image NOT NULL + ) ON [PRIMARY] + TEXTIMAGE_ON [PRIMARY] + +IF EXISTS(SELECT * FROM assets) + EXEC('INSERT INTO Tmp_assets (id, name, description, assetType, local, temporary, data) + SELECT id, name, description, assetType, CONVERT(bit, local), CONVERT(bit, temporary), data FROM assets WITH (HOLDLOCK TABLOCKX)') + +DROP TABLE assets + +EXECUTE sp_rename N'Tmp_assets', N'assets', 'OBJECT' + +ALTER TABLE dbo.assets ADD CONSTRAINT + PK__assets__id PRIMARY KEY CLUSTERED + ( + id + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +COMMIT + + +:VERSION 3 + +BEGIN TRANSACTION + +ALTER TABLE assets add create_time integer default 0 +ALTER TABLE assets add access_time integer default 0 + +COMMIT + + +:VERSION 4 + +BEGIN TRANSACTION + +CREATE TABLE dbo.Tmp_assets + ( + id uniqueidentifier NOT NULL, + name varchar(64) NOT NULL, + description varchar(64) NOT NULL, + assetType tinyint NOT NULL, + local bit NOT NULL, + temporary bit NOT NULL, + data image NOT NULL, + create_time int NULL, + access_time int NULL + ) ON [PRIMARY] + TEXTIMAGE_ON [PRIMARY] + +IF EXISTS(SELECT * FROM dbo.assets) + EXEC('INSERT INTO dbo.Tmp_assets (id, name, description, assetType, local, temporary, data, create_time, access_time) + SELECT CONVERT(uniqueidentifier, id), name, description, assetType, local, temporary, data, create_time, access_time FROM dbo.assets WITH (HOLDLOCK TABLOCKX)') + +DROP TABLE assets + +EXECUTE sp_rename N'Tmp_assets', N'assets', 'OBJECT' + +ALTER TABLE dbo.assets ADD CONSTRAINT + PK__assets__id PRIMARY KEY CLUSTERED + ( + id + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +COMMIT + + +:VERSION 5 + +DELETE FROM assets WHERE id = 'dc4b9f0b-d008-45c6-96a4-01dd947ac621'; + +:VERSION 6 + +ALTER TABLE assets ADD asset_flags INTEGER NOT NULL DEFAULT 0; + +:VERSION 7 + +alter table assets add creatorid varchar(36) not null default ''; diff --git a/OpenSim/Data/MSSQL/Resources/001_AuthStore.sql b/OpenSim/Data/MSSQL/Resources/AuthStore.migrations similarity index 63% rename from OpenSim/Data/MSSQL/Resources/001_AuthStore.sql rename to OpenSim/Data/MSSQL/Resources/AuthStore.migrations index c70a19319b..5b90ca3d36 100644 --- a/OpenSim/Data/MSSQL/Resources/001_AuthStore.sql +++ b/OpenSim/Data/MSSQL/Resources/AuthStore.migrations @@ -1,3 +1,5 @@ +:VERSION 1 + BEGIN TRANSACTION CREATE TABLE [auth] ( @@ -14,4 +16,13 @@ CREATE TABLE [tokens] ( [validity] [datetime] NOT NULL ) ON [PRIMARY] +COMMIT + +:VERSION 2 + +BEGIN TRANSACTION + +INSERT INTO auth (UUID, passwordHash, passwordSalt, webLoginKey, accountType) SELECT [UUID] AS UUID, [passwordHash] AS passwordHash, [passwordSalt] AS passwordSalt, [webLoginKey] AS webLoginKey, 'UserAccount' as [accountType] FROM users; + + COMMIT \ No newline at end of file diff --git a/OpenSim/Data/MSSQL/Resources/001_Avatar.sql b/OpenSim/Data/MSSQL/Resources/Avatar.migrations similarity index 94% rename from OpenSim/Data/MSSQL/Resources/001_Avatar.sql rename to OpenSim/Data/MSSQL/Resources/Avatar.migrations index 48f4c00669..759e939caf 100644 --- a/OpenSim/Data/MSSQL/Resources/001_Avatar.sql +++ b/OpenSim/Data/MSSQL/Resources/Avatar.migrations @@ -1,3 +1,5 @@ +:VERSION 1 + BEGIN TRANSACTION CREATE TABLE [Avatars] ( diff --git a/OpenSim/Data/MSSQL/Resources/AvatarAppearance.sql b/OpenSim/Data/MSSQL/Resources/AvatarAppearance.sql deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/OpenSim/Data/MSSQL/Resources/CreateAssetsTable.sql b/OpenSim/Data/MSSQL/Resources/CreateAssetsTable.sql deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/OpenSim/Data/MSSQL/Resources/CreateFoldersTable.sql b/OpenSim/Data/MSSQL/Resources/CreateFoldersTable.sql deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/OpenSim/Data/MSSQL/Resources/CreateItemsTable.sql b/OpenSim/Data/MSSQL/Resources/CreateItemsTable.sql deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/OpenSim/Data/MSSQL/Resources/CreateUserFriendsTable.sql b/OpenSim/Data/MSSQL/Resources/CreateUserFriendsTable.sql deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/OpenSim/Data/MSSQL/Resources/EstateStore.migrations b/OpenSim/Data/MSSQL/Resources/EstateStore.migrations new file mode 100644 index 0000000000..64b2d2bdb2 --- /dev/null +++ b/OpenSim/Data/MSSQL/Resources/EstateStore.migrations @@ -0,0 +1,334 @@ +:VERSION 1 + +BEGIN TRANSACTION + +CREATE TABLE [dbo].[estate_managers]( + [EstateID] [int] NOT NULL, + [uuid] [varchar](36) NOT NULL, + CONSTRAINT [PK_estate_managers] PRIMARY KEY CLUSTERED +( + [EstateID] ASC +)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY] +) ON [PRIMARY]; + +CREATE TABLE [dbo].[estate_groups]( + [EstateID] [int] NOT NULL, + [uuid] [varchar](36) NOT NULL, + CONSTRAINT [PK_estate_groups] PRIMARY KEY CLUSTERED +( + [EstateID] ASC +)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY] +) ON [PRIMARY]; + + +CREATE TABLE [dbo].[estate_users]( + [EstateID] [int] NOT NULL, + [uuid] [varchar](36) NOT NULL, + CONSTRAINT [PK_estate_users] PRIMARY KEY CLUSTERED +( + [EstateID] ASC +)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY] +) ON [PRIMARY]; + + +CREATE TABLE [dbo].[estateban]( + [EstateID] [int] NOT NULL, + [bannedUUID] [varchar](36) NOT NULL, + [bannedIp] [varchar](16) NOT NULL, + [bannedIpHostMask] [varchar](16) NOT NULL, + [bannedNameMask] [varchar](64) NULL DEFAULT (NULL), + CONSTRAINT [PK_estateban] PRIMARY KEY CLUSTERED +( + [EstateID] ASC +)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY] +) ON [PRIMARY]; + +CREATE TABLE [dbo].[estate_settings]( + [EstateID] [int] IDENTITY(1,100) NOT NULL, + [EstateName] [varchar](64) NULL DEFAULT (NULL), + [AbuseEmailToEstateOwner] [bit] NOT NULL, + [DenyAnonymous] [bit] NOT NULL, + [ResetHomeOnTeleport] [bit] NOT NULL, + [FixedSun] [bit] NOT NULL, + [DenyTransacted] [bit] NOT NULL, + [BlockDwell] [bit] NOT NULL, + [DenyIdentified] [bit] NOT NULL, + [AllowVoice] [bit] NOT NULL, + [UseGlobalTime] [bit] NOT NULL, + [PricePerMeter] [int] NOT NULL, + [TaxFree] [bit] NOT NULL, + [AllowDirectTeleport] [bit] NOT NULL, + [RedirectGridX] [int] NOT NULL, + [RedirectGridY] [int] NOT NULL, + [ParentEstateID] [int] NOT NULL, + [SunPosition] [float] NOT NULL, + [EstateSkipScripts] [bit] NOT NULL, + [BillableFactor] [float] NOT NULL, + [PublicAccess] [bit] NOT NULL, + [AbuseEmail] [varchar](255) NOT NULL, + [EstateOwner] [varchar](36) NOT NULL, + [DenyMinors] [bit] NOT NULL, + CONSTRAINT [PK_estate_settings] PRIMARY KEY CLUSTERED +( + [EstateID] ASC +)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY] +) ON [PRIMARY]; + + +CREATE TABLE [dbo].[estate_map]( + [RegionID] [varchar](36) NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000'), + [EstateID] [int] NOT NULL, + CONSTRAINT [PK_estate_map] PRIMARY KEY CLUSTERED +( + [RegionID] ASC +)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY] +) ON [PRIMARY]; + +COMMIT + +:VERSION 2 + +BEGIN TRANSACTION + +ALTER TABLE dbo.estate_managers DROP CONSTRAINT PK_estate_managers + +CREATE NONCLUSTERED INDEX IX_estate_managers ON dbo.estate_managers + ( + EstateID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +ALTER TABLE dbo.estate_groups DROP CONSTRAINT PK_estate_groups + +CREATE NONCLUSTERED INDEX IX_estate_groups ON dbo.estate_groups + ( + EstateID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + + +ALTER TABLE dbo.estate_users DROP CONSTRAINT PK_estate_users + +CREATE NONCLUSTERED INDEX IX_estate_users ON dbo.estate_users + ( + EstateID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +COMMIT + + +:VERSION 3 + +BEGIN TRANSACTION + +CREATE TABLE dbo.Tmp_estateban + ( + EstateID int NOT NULL, + bannedUUID varchar(36) NOT NULL, + bannedIp varchar(16) NULL, + bannedIpHostMask varchar(16) NULL, + bannedNameMask varchar(64) NULL + ) ON [PRIMARY] + +IF EXISTS(SELECT * FROM dbo.estateban) + EXEC('INSERT INTO dbo.Tmp_estateban (EstateID, bannedUUID, bannedIp, bannedIpHostMask, bannedNameMask) + SELECT EstateID, bannedUUID, bannedIp, bannedIpHostMask, bannedNameMask FROM dbo.estateban') + +DROP TABLE dbo.estateban + +EXECUTE sp_rename N'dbo.Tmp_estateban', N'estateban', 'OBJECT' + +CREATE NONCLUSTERED INDEX IX_estateban ON dbo.estateban + ( + EstateID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +COMMIT + + +:VERSION 4 + +BEGIN TRANSACTION + +CREATE TABLE dbo.Tmp_estate_managers + ( + EstateID int NOT NULL, + uuid uniqueidentifier NOT NULL + ) ON [PRIMARY] + +IF EXISTS(SELECT * FROM dbo.estate_managers) + EXEC('INSERT INTO dbo.Tmp_estate_managers (EstateID, uuid) + SELECT EstateID, CONVERT(uniqueidentifier, uuid) FROM dbo.estate_managers WITH (HOLDLOCK TABLOCKX)') + +DROP TABLE dbo.estate_managers + +EXECUTE sp_rename N'dbo.Tmp_estate_managers', N'estate_managers', 'OBJECT' + +CREATE NONCLUSTERED INDEX IX_estate_managers ON dbo.estate_managers + ( + EstateID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +COMMIT + + +:VERSION 5 + +BEGIN TRANSACTION + +CREATE TABLE dbo.Tmp_estate_groups + ( + EstateID int NOT NULL, + uuid uniqueidentifier NOT NULL + ) ON [PRIMARY] + +IF EXISTS(SELECT * FROM dbo.estate_groups) + EXEC('INSERT INTO dbo.Tmp_estate_groups (EstateID, uuid) + SELECT EstateID, CONVERT(uniqueidentifier, uuid) FROM dbo.estate_groups WITH (HOLDLOCK TABLOCKX)') + +DROP TABLE dbo.estate_groups + +EXECUTE sp_rename N'dbo.Tmp_estate_groups', N'estate_groups', 'OBJECT' + +CREATE NONCLUSTERED INDEX IX_estate_groups ON dbo.estate_groups + ( + EstateID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +COMMIT + + +:VERSION 6 + +BEGIN TRANSACTION + +CREATE TABLE dbo.Tmp_estate_users + ( + EstateID int NOT NULL, + uuid uniqueidentifier NOT NULL + ) ON [PRIMARY] + +IF EXISTS(SELECT * FROM dbo.estate_users) + EXEC('INSERT INTO dbo.Tmp_estate_users (EstateID, uuid) + SELECT EstateID, CONVERT(uniqueidentifier, uuid) FROM dbo.estate_users WITH (HOLDLOCK TABLOCKX)') + +DROP TABLE dbo.estate_users + +EXECUTE sp_rename N'dbo.Tmp_estate_users', N'estate_users', 'OBJECT' + +CREATE NONCLUSTERED INDEX IX_estate_users ON dbo.estate_users + ( + EstateID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +COMMIT + + +:VERSION 7 + +BEGIN TRANSACTION + +CREATE TABLE dbo.Tmp_estateban + ( + EstateID int NOT NULL, + bannedUUID uniqueidentifier NOT NULL, + bannedIp varchar(16) NULL, + bannedIpHostMask varchar(16) NULL, + bannedNameMask varchar(64) NULL + ) ON [PRIMARY] + +IF EXISTS(SELECT * FROM dbo.estateban) + EXEC('INSERT INTO dbo.Tmp_estateban (EstateID, bannedUUID, bannedIp, bannedIpHostMask, bannedNameMask) + SELECT EstateID, CONVERT(uniqueidentifier, bannedUUID), bannedIp, bannedIpHostMask, bannedNameMask FROM dbo.estateban WITH (HOLDLOCK TABLOCKX)') + +DROP TABLE dbo.estateban + +EXECUTE sp_rename N'dbo.Tmp_estateban', N'estateban', 'OBJECT' + +CREATE NONCLUSTERED INDEX IX_estateban ON dbo.estateban + ( + EstateID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +COMMIT + + +:VERSION 8 + +BEGIN TRANSACTION + +CREATE TABLE dbo.Tmp_estate_settings + ( + EstateID int NOT NULL IDENTITY (1, 100), + EstateName varchar(64) NULL DEFAULT (NULL), + AbuseEmailToEstateOwner bit NOT NULL, + DenyAnonymous bit NOT NULL, + ResetHomeOnTeleport bit NOT NULL, + FixedSun bit NOT NULL, + DenyTransacted bit NOT NULL, + BlockDwell bit NOT NULL, + DenyIdentified bit NOT NULL, + AllowVoice bit NOT NULL, + UseGlobalTime bit NOT NULL, + PricePerMeter int NOT NULL, + TaxFree bit NOT NULL, + AllowDirectTeleport bit NOT NULL, + RedirectGridX int NOT NULL, + RedirectGridY int NOT NULL, + ParentEstateID int NOT NULL, + SunPosition float(53) NOT NULL, + EstateSkipScripts bit NOT NULL, + BillableFactor float(53) NOT NULL, + PublicAccess bit NOT NULL, + AbuseEmail varchar(255) NOT NULL, + EstateOwner uniqueidentifier NOT NULL, + DenyMinors bit NOT NULL + ) ON [PRIMARY] + +SET IDENTITY_INSERT dbo.Tmp_estate_settings ON + +IF EXISTS(SELECT * FROM dbo.estate_settings) + EXEC('INSERT INTO dbo.Tmp_estate_settings (EstateID, EstateName, AbuseEmailToEstateOwner, DenyAnonymous, ResetHomeOnTeleport, FixedSun, DenyTransacted, BlockDwell, DenyIdentified, AllowVoice, UseGlobalTime, PricePerMeter, TaxFree, AllowDirectTeleport, RedirectGridX, RedirectGridY, ParentEstateID, SunPosition, EstateSkipScripts, BillableFactor, PublicAccess, AbuseEmail, EstateOwner, DenyMinors) + SELECT EstateID, EstateName, AbuseEmailToEstateOwner, DenyAnonymous, ResetHomeOnTeleport, FixedSun, DenyTransacted, BlockDwell, DenyIdentified, AllowVoice, UseGlobalTime, PricePerMeter, TaxFree, AllowDirectTeleport, RedirectGridX, RedirectGridY, ParentEstateID, SunPosition, EstateSkipScripts, BillableFactor, PublicAccess, AbuseEmail, CONVERT(uniqueidentifier, EstateOwner), DenyMinors FROM dbo.estate_settings WITH (HOLDLOCK TABLOCKX)') + +SET IDENTITY_INSERT dbo.Tmp_estate_settings OFF + +DROP TABLE dbo.estate_settings + +EXECUTE sp_rename N'dbo.Tmp_estate_settings', N'estate_settings', 'OBJECT' + +ALTER TABLE dbo.estate_settings ADD CONSTRAINT + PK_estate_settings PRIMARY KEY CLUSTERED + ( + EstateID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +COMMIT + + +:VERSION 9 + +BEGIN TRANSACTION + +CREATE TABLE dbo.Tmp_estate_map + ( + RegionID uniqueidentifier NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000'), + EstateID int NOT NULL + ) ON [PRIMARY] + +IF EXISTS(SELECT * FROM dbo.estate_map) + EXEC('INSERT INTO dbo.Tmp_estate_map (RegionID, EstateID) + SELECT CONVERT(uniqueidentifier, RegionID), EstateID FROM dbo.estate_map WITH (HOLDLOCK TABLOCKX)') + +DROP TABLE dbo.estate_map + +EXECUTE sp_rename N'dbo.Tmp_estate_map', N'estate_map', 'OBJECT' + +ALTER TABLE dbo.estate_map ADD CONSTRAINT + PK_estate_map PRIMARY KEY CLUSTERED + ( + RegionID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + + +COMMIT + + diff --git a/OpenSim/Data/MSSQL/Resources/001_FriendsStore.sql b/OpenSim/Data/MSSQL/Resources/FriendsStore.migrations similarity index 54% rename from OpenSim/Data/MSSQL/Resources/001_FriendsStore.sql rename to OpenSim/Data/MSSQL/Resources/FriendsStore.migrations index 94d240b512..f981a91999 100644 --- a/OpenSim/Data/MSSQL/Resources/001_FriendsStore.sql +++ b/OpenSim/Data/MSSQL/Resources/FriendsStore.migrations @@ -1,3 +1,5 @@ +:VERSION 1 + BEGIN TRANSACTION CREATE TABLE [Friends] ( @@ -7,5 +9,12 @@ CREATE TABLE [Friends] ( [Offered] varchar(32) NOT NULL DEFAULT 0) ON [PRIMARY] +COMMIT + +:VERSION 2 + +BEGIN TRANSACTION + +INSERT INTO Friends (PrincipalID, Friend, Flags, Offered) SELECT [ownerID], [friendID], [friendPerms], 0 FROM userfriends; COMMIT \ No newline at end of file diff --git a/OpenSim/Data/MSSQL/Resources/GridStore.migrations b/OpenSim/Data/MSSQL/Resources/GridStore.migrations new file mode 100644 index 0000000000..d2ca27a071 --- /dev/null +++ b/OpenSim/Data/MSSQL/Resources/GridStore.migrations @@ -0,0 +1,225 @@ +:VERSION 1 + +BEGIN TRANSACTION + +CREATE TABLE [dbo].[regions]( + [regionHandle] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [regionName] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [uuid] [varchar](255) COLLATE Latin1_General_CI_AS NOT NULL, + [regionRecvKey] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [regionSecret] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [regionSendKey] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [regionDataURI] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [serverIP] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [serverPort] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [serverURI] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [locX] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [locY] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [locZ] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [eastOverrideHandle] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [westOverrideHandle] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [southOverrideHandle] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [northOverrideHandle] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [regionAssetURI] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [regionAssetRecvKey] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [regionAssetSendKey] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [regionUserURI] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [regionUserRecvKey] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [regionUserSendKey] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [regionMapTexture] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [serverHttpPort] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [serverRemotingPort] [varchar](255) COLLATE Latin1_General_CI_AS NULL, + [owner_uuid] [varchar](36) COLLATE Latin1_General_CI_AS NULL, +PRIMARY KEY CLUSTERED +( + [uuid] ASC +)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY] +) ON [PRIMARY] + +COMMIT + + +:VERSION 2 + +BEGIN TRANSACTION + +CREATE TABLE Tmp_regions + ( + uuid varchar(36) COLLATE Latin1_General_CI_AS NOT NULL, + regionHandle bigint NULL, + regionName varchar(20) NULL, + regionRecvKey varchar(128) NULL, + regionSendKey varchar(128) NULL, + regionSecret varchar(128) NULL, + regionDataURI varchar(128) NULL, + serverIP varchar(64) NULL, + serverPort int NULL, + serverURI varchar(255) NULL, + locX int NULL, + locY int NULL, + locZ int NULL, + eastOverrideHandle bigint NULL, + westOverrideHandle bigint NULL, + southOverrideHandle bigint NULL, + northOverrideHandle bigint NULL, + regionAssetURI varchar(255) NULL, + regionAssetRecvKey varchar(128) NULL, + regionAssetSendKey varchar(128) NULL, + regionUserURI varchar(255) NULL, + regionUserRecvKey varchar(128) NULL, + regionUserSendKey varchar(128) NULL, + regionMapTexture varchar(36) NULL, + serverHttpPort int NULL, + serverRemotingPort int NULL, + owner_uuid varchar(36) NULL, + originUUID varchar(36) NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000') + ) ON [PRIMARY] + +IF EXISTS(SELECT * FROM regions) + EXEC('INSERT INTO Tmp_regions (uuid, regionHandle, regionName, regionRecvKey, regionSendKey, regionSecret, regionDataURI, serverIP, serverPort, serverURI, locX, locY, locZ, eastOverrideHandle, westOverrideHandle, southOverrideHandle, northOverrideHandle, regionAssetURI, regionAssetRecvKey, regionAssetSendKey, regionUserURI, regionUserRecvKey, regionUserSendKey, regionMapTexture, serverHttpPort, serverRemotingPort, owner_uuid) + SELECT CONVERT(varchar(36), uuid), CONVERT(bigint, regionHandle), CONVERT(varchar(20), regionName), CONVERT(varchar(128), regionRecvKey), CONVERT(varchar(128), regionSendKey), CONVERT(varchar(128), regionSecret), CONVERT(varchar(128), regionDataURI), CONVERT(varchar(64), serverIP), CONVERT(int, serverPort), serverURI, CONVERT(int, locX), CONVERT(int, locY), CONVERT(int, locZ), CONVERT(bigint, eastOverrideHandle), CONVERT(bigint, westOverrideHandle), CONVERT(bigint, southOverrideHandle), CONVERT(bigint, northOverrideHandle), regionAssetURI, CONVERT(varchar(128), regionAssetRecvKey), CONVERT(varchar(128), regionAssetSendKey), regionUserURI, CONVERT(varchar(128), regionUserRecvKey), CONVERT(varchar(128), regionUserSendKey), CONVERT(varchar(36), regionMapTexture), CONVERT(int, serverHttpPort), CONVERT(int, serverRemotingPort), owner_uuid FROM regions') + +DROP TABLE regions + +EXECUTE sp_rename N'Tmp_regions', N'regions', 'OBJECT' + +ALTER TABLE regions ADD CONSTRAINT + PK__regions__uuid PRIMARY KEY CLUSTERED + ( + uuid + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +COMMIT + +:VERSION 3 + +BEGIN TRANSACTION + +CREATE NONCLUSTERED INDEX IX_regions_name ON dbo.regions + ( + regionName + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +CREATE NONCLUSTERED INDEX IX_regions_handle ON dbo.regions + ( + regionHandle + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + + +CREATE NONCLUSTERED INDEX IX_regions_override ON dbo.regions + ( + eastOverrideHandle, + westOverrideHandle, + southOverrideHandle, + northOverrideHandle + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +COMMIT + + +:VERSION 4 + +/* To prevent any potential data loss issues, you should review this script in detail before running it outside the context of the database designer.*/ +BEGIN TRANSACTION + +CREATE TABLE dbo.Tmp_regions + ( + uuid uniqueidentifier NOT NULL, + regionHandle bigint NULL, + regionName varchar(20) NULL, + regionRecvKey varchar(128) NULL, + regionSendKey varchar(128) NULL, + regionSecret varchar(128) NULL, + regionDataURI varchar(128) NULL, + serverIP varchar(64) NULL, + serverPort int NULL, + serverURI varchar(255) NULL, + locX int NULL, + locY int NULL, + locZ int NULL, + eastOverrideHandle bigint NULL, + westOverrideHandle bigint NULL, + southOverrideHandle bigint NULL, + northOverrideHandle bigint NULL, + regionAssetURI varchar(255) NULL, + regionAssetRecvKey varchar(128) NULL, + regionAssetSendKey varchar(128) NULL, + regionUserURI varchar(255) NULL, + regionUserRecvKey varchar(128) NULL, + regionUserSendKey varchar(128) NULL, + regionMapTexture uniqueidentifier NULL, + serverHttpPort int NULL, + serverRemotingPort int NULL, + owner_uuid uniqueidentifier NOT NULL, + originUUID uniqueidentifier NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000') + ) ON [PRIMARY] + +IF EXISTS(SELECT * FROM dbo.regions) + EXEC('INSERT INTO dbo.Tmp_regions (uuid, regionHandle, regionName, regionRecvKey, regionSendKey, regionSecret, regionDataURI, serverIP, serverPort, serverURI, locX, locY, locZ, eastOverrideHandle, westOverrideHandle, southOverrideHandle, northOverrideHandle, regionAssetURI, regionAssetRecvKey, regionAssetSendKey, regionUserURI, regionUserRecvKey, regionUserSendKey, regionMapTexture, serverHttpPort, serverRemotingPort, owner_uuid, originUUID) + SELECT CONVERT(uniqueidentifier, uuid), regionHandle, regionName, regionRecvKey, regionSendKey, regionSecret, regionDataURI, serverIP, serverPort, serverURI, locX, locY, locZ, eastOverrideHandle, westOverrideHandle, southOverrideHandle, northOverrideHandle, regionAssetURI, regionAssetRecvKey, regionAssetSendKey, regionUserURI, regionUserRecvKey, regionUserSendKey, CONVERT(uniqueidentifier, regionMapTexture), serverHttpPort, serverRemotingPort, CONVERT(uniqueidentifier, owner_uuid), CONVERT(uniqueidentifier, originUUID) FROM dbo.regions WITH (HOLDLOCK TABLOCKX)') + +DROP TABLE dbo.regions + +EXECUTE sp_rename N'dbo.Tmp_regions', N'regions', 'OBJECT' + +ALTER TABLE dbo.regions ADD CONSTRAINT + PK__regions__uuid PRIMARY KEY CLUSTERED + ( + uuid + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +CREATE NONCLUSTERED INDEX IX_regions_name ON dbo.regions + ( + regionName + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +CREATE NONCLUSTERED INDEX IX_regions_handle ON dbo.regions + ( + regionHandle + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +CREATE NONCLUSTERED INDEX IX_regions_override ON dbo.regions + ( + eastOverrideHandle, + westOverrideHandle, + southOverrideHandle, + northOverrideHandle + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +COMMIT + + +:VERSION 5 + +BEGIN TRANSACTION + +ALTER TABLE regions ADD access int default 0; + +COMMIT + + +:VERSION 6 + +BEGIN TRANSACTION + +ALTER TABLE regions ADD scopeid uniqueidentifier default '00000000-0000-0000-0000-000000000000'; +ALTER TABLE regions ADD DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [owner_uuid]; +ALTER TABLE regions ADD sizeX integer not null default 0; +ALTER TABLE regions ADD sizeY integer not null default 0; + +COMMIT + + +:VERSION 7 + +BEGIN TRANSACTION + +ALTER TABLE regions ADD [flags] integer NOT NULL DEFAULT 0; +CREATE INDEX [flags] ON regions(flags); +ALTER TABLE [regions] ADD [last_seen] integer NOT NULL DEFAULT 0; +ALTER TABLE [regions] ADD [PrincipalID] uniqueidentifier NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000'; +ALTER TABLE [regions] ADD [Token] varchar(255) NOT NULL DEFAULT 0; + +COMMIT + + diff --git a/OpenSim/Data/MSSQL/Resources/InventoryStore.migrations b/OpenSim/Data/MSSQL/Resources/InventoryStore.migrations new file mode 100644 index 0000000000..e2a8d5709b --- /dev/null +++ b/OpenSim/Data/MSSQL/Resources/InventoryStore.migrations @@ -0,0 +1,244 @@ +:VERSION 1 + +BEGIN TRANSACTION + +CREATE TABLE [inventoryfolders] ( + [folderID] [varchar](36) NOT NULL default '', + [agentID] [varchar](36) default NULL, + [parentFolderID] [varchar](36) default NULL, + [folderName] [varchar](64) default NULL, + [type] [smallint] NOT NULL default 0, + [version] [int] NOT NULL default 0, + PRIMARY KEY CLUSTERED +( + [folderID] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] +) ON [PRIMARY] + +CREATE NONCLUSTERED INDEX [owner] ON [inventoryfolders] +( + [agentID] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +CREATE NONCLUSTERED INDEX [parent] ON [inventoryfolders] +( + [parentFolderID] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + + +CREATE TABLE [inventoryitems] ( + [inventoryID] [varchar](36) NOT NULL default '', + [assetID] [varchar](36) default NULL, + [assetType] [int] default NULL, + [parentFolderID] [varchar](36) default NULL, + [avatarID] [varchar](36) default NULL, + [inventoryName] [varchar](64) default NULL, + [inventoryDescription] [varchar](128) default NULL, + [inventoryNextPermissions] [int] default NULL, + [inventoryCurrentPermissions] [int] default NULL, + [invType] [int] default NULL, + [creatorID] [varchar](36) default NULL, + [inventoryBasePermissions] [int] NOT NULL default 0, + [inventoryEveryOnePermissions] [int] NOT NULL default 0, + [salePrice] [int] default NULL, + [saleType] [tinyint] default NULL, + [creationDate] [int] default NULL, + [groupID] [varchar](36) default NULL, + [groupOwned] [bit] default NULL, + [flags] [int] default NULL, + PRIMARY KEY CLUSTERED +( + [inventoryID] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] +) ON [PRIMARY] + + +CREATE NONCLUSTERED INDEX [owner] ON [inventoryitems] +( + [avatarID] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +CREATE NONCLUSTERED INDEX [folder] ON [inventoryitems] +( + [parentFolderID] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +COMMIT + + +:VERSION 2 + +BEGIN TRANSACTION + +ALTER TABLE inventoryitems ADD inventoryGroupPermissions INTEGER NOT NULL default 0 + +COMMIT + +:VERSION 3 + +/* To prevent any potential data loss issues, you should review this script in detail before running it outside the context of the database designer.*/ +BEGIN TRANSACTION + +CREATE TABLE dbo.Tmp_inventoryfolders + ( + folderID uniqueidentifier NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000'), + agentID uniqueidentifier NULL DEFAULT (NULL), + parentFolderID uniqueidentifier NULL DEFAULT (NULL), + folderName varchar(64) NULL DEFAULT (NULL), + type smallint NOT NULL DEFAULT ((0)), + version int NOT NULL DEFAULT ((0)) + ) ON [PRIMARY] + +IF EXISTS(SELECT * FROM dbo.inventoryfolders) + EXEC('INSERT INTO dbo.Tmp_inventoryfolders (folderID, agentID, parentFolderID, folderName, type, version) + SELECT CONVERT(uniqueidentifier, folderID), CONVERT(uniqueidentifier, agentID), CONVERT(uniqueidentifier, parentFolderID), folderName, type, version FROM dbo.inventoryfolders WITH (HOLDLOCK TABLOCKX)') + +DROP TABLE dbo.inventoryfolders + +EXECUTE sp_rename N'dbo.Tmp_inventoryfolders', N'inventoryfolders', 'OBJECT' + +ALTER TABLE dbo.inventoryfolders ADD CONSTRAINT + PK__inventor__C2FABFB3173876EA PRIMARY KEY CLUSTERED + ( + folderID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +CREATE NONCLUSTERED INDEX owner ON dbo.inventoryfolders + ( + agentID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +CREATE NONCLUSTERED INDEX parent ON dbo.inventoryfolders + ( + parentFolderID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +COMMIT + + +:VERSION 4 + +BEGIN TRANSACTION + +CREATE TABLE dbo.Tmp_inventoryitems + ( + inventoryID uniqueidentifier NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000'), + assetID uniqueidentifier NULL DEFAULT (NULL), + assetType int NULL DEFAULT (NULL), + parentFolderID uniqueidentifier NULL DEFAULT (NULL), + avatarID uniqueidentifier NULL DEFAULT (NULL), + inventoryName varchar(64) NULL DEFAULT (NULL), + inventoryDescription varchar(128) NULL DEFAULT (NULL), + inventoryNextPermissions int NULL DEFAULT (NULL), + inventoryCurrentPermissions int NULL DEFAULT (NULL), + invType int NULL DEFAULT (NULL), + creatorID uniqueidentifier NULL DEFAULT (NULL), + inventoryBasePermissions int NOT NULL DEFAULT ((0)), + inventoryEveryOnePermissions int NOT NULL DEFAULT ((0)), + salePrice int NULL DEFAULT (NULL), + saleType tinyint NULL DEFAULT (NULL), + creationDate int NULL DEFAULT (NULL), + groupID uniqueidentifier NULL DEFAULT (NULL), + groupOwned bit NULL DEFAULT (NULL), + flags int NULL DEFAULT (NULL), + inventoryGroupPermissions int NOT NULL DEFAULT ((0)) + ) ON [PRIMARY] + +IF EXISTS(SELECT * FROM dbo.inventoryitems) + EXEC('INSERT INTO dbo.Tmp_inventoryitems (inventoryID, assetID, assetType, parentFolderID, avatarID, inventoryName, inventoryDescription, inventoryNextPermissions, inventoryCurrentPermissions, invType, creatorID, inventoryBasePermissions, inventoryEveryOnePermissions, salePrice, saleType, creationDate, groupID, groupOwned, flags, inventoryGroupPermissions) + SELECT CONVERT(uniqueidentifier, inventoryID), CONVERT(uniqueidentifier, assetID), assetType, CONVERT(uniqueidentifier, parentFolderID), CONVERT(uniqueidentifier, avatarID), inventoryName, inventoryDescription, inventoryNextPermissions, inventoryCurrentPermissions, invType, CONVERT(uniqueidentifier, creatorID), inventoryBasePermissions, inventoryEveryOnePermissions, salePrice, saleType, creationDate, CONVERT(uniqueidentifier, groupID), groupOwned, flags, inventoryGroupPermissions FROM dbo.inventoryitems WITH (HOLDLOCK TABLOCKX)') + +DROP TABLE dbo.inventoryitems + +EXECUTE sp_rename N'dbo.Tmp_inventoryitems', N'inventoryitems', 'OBJECT' + +ALTER TABLE dbo.inventoryitems ADD CONSTRAINT + PK__inventor__C4B7BC2220C1E124 PRIMARY KEY CLUSTERED + ( + inventoryID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + + +CREATE NONCLUSTERED INDEX owner ON dbo.inventoryitems + ( + avatarID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +CREATE NONCLUSTERED INDEX folder ON dbo.inventoryitems + ( + parentFolderID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +COMMIT + +:VERSION 5 + +# It would be totally crazy to have to recreate the whole table just to change one column type, +# just because MS SQL treats each DEFAULT as a constraint object that must be dropped +# before anything can be done to the column. Since all defaults here are unnamed, there is +# no easy way to drop them! The hairy piece of code below removes all DEFAULT constraints +# from InventoryItems. + +# SO: anything that's NULLable is by default NULL, so please don't declare DEFAULT(NULL), +# they do nothing but prevent changes to the columns. If you really +# need to have DEFAULTs or other constraints, give them names so they can be dropped when needed! + +BEGIN TRANSACTION +DECLARE @nm varchar(80); +DECLARE x CURSOR LOCAL FORWARD_ONLY READ_ONLY + FOR SELECT name FROM sys.default_constraints where parent_object_id = OBJECT_ID('inventoryitems'); +OPEN x; +FETCH NEXT FROM x INTO @nm; +WHILE @@FETCH_STATUS = 0 +BEGIN + EXEC('alter table inventoryitems drop ' + @nm); + FETCH NEXT FROM x INTO @nm; +END +CLOSE x +DEALLOCATE x +COMMIT + +# all DEFAULTs dropped! + +:GO + +BEGIN TRANSACTION + +# Restoring defaults: +# NOTE: [inventoryID] does NOT need one: it's NOT NULL PK and a unique Guid must be provided every time anyway! + +alter table inventoryitems + add constraint def_baseperm default 0 for inventoryBasePermissions +alter table inventoryitems + add constraint def_allperm default 0 for inventoryEveryOnePermissions +alter table inventoryitems + add constraint def_grpperm default 0 for inventoryGroupPermissions + +COMMIT + +:VERSION 7 + +BEGIN TRANSACTION + +# CreatorID goes back to VARCHAR(36) (???) + +exec sp_rename 'inventoryitems.CreatorID', 'cr_old', 'COLUMN' + +:GO + +alter table inventoryitems + add creatorID varchar(36) NULL + +:GO + +update inventoryitems set creatorID = CONVERT(VARCHAR(36), cr_old) + +alter table inventoryitems + drop column cr_old + +COMMIT + + + + + diff --git a/OpenSim/Data/MSSQL/Resources/001_LogStore.sql b/OpenSim/Data/MSSQL/Resources/LogStore.migrations similarity index 96% rename from OpenSim/Data/MSSQL/Resources/001_LogStore.sql rename to OpenSim/Data/MSSQL/Resources/LogStore.migrations index 9ece6274dd..1430d8d0ee 100644 --- a/OpenSim/Data/MSSQL/Resources/001_LogStore.sql +++ b/OpenSim/Data/MSSQL/Resources/LogStore.migrations @@ -1,3 +1,5 @@ +:VERSION 1 + BEGIN TRANSACTION CREATE TABLE [logs] ( diff --git a/OpenSim/Data/MSSQL/Resources/Mssql-agents.sql b/OpenSim/Data/MSSQL/Resources/Mssql-agents.sql deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/OpenSim/Data/MSSQL/Resources/Mssql-logs.sql b/OpenSim/Data/MSSQL/Resources/Mssql-logs.sql deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/OpenSim/Data/MSSQL/Resources/Mssql-regions.sql b/OpenSim/Data/MSSQL/Resources/Mssql-regions.sql deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/OpenSim/Data/MSSQL/Resources/Mssql-users.sql b/OpenSim/Data/MSSQL/Resources/Mssql-users.sql deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/OpenSim/Data/MSSQL/Resources/001_Presence.sql b/OpenSim/Data/MSSQL/Resources/Presence.migrations similarity index 81% rename from OpenSim/Data/MSSQL/Resources/001_Presence.sql rename to OpenSim/Data/MSSQL/Resources/Presence.migrations index 877881c859..35f78e1f52 100644 --- a/OpenSim/Data/MSSQL/Resources/001_Presence.sql +++ b/OpenSim/Data/MSSQL/Resources/Presence.migrations @@ -1,3 +1,5 @@ +:VERSION 1 + BEGIN TRANSACTION CREATE TABLE [Presence] ( @@ -16,4 +18,13 @@ CREATE TABLE [Presence] ( ) ON [PRIMARY] +COMMIT + +:VERSION 2 + +BEGIN TRANSACTION + +CREATE UNIQUE INDEX SessionID ON Presence(SessionID); +CREATE INDEX UserID ON Presence(UserID); + COMMIT \ No newline at end of file diff --git a/OpenSim/Data/MSSQL/Resources/RegionStore.migrations b/OpenSim/Data/MSSQL/Resources/RegionStore.migrations new file mode 100644 index 0000000000..e912d646a0 --- /dev/null +++ b/OpenSim/Data/MSSQL/Resources/RegionStore.migrations @@ -0,0 +1,929 @@ + +:VERSION 1 + +CREATE TABLE [dbo].[prims]( + [UUID] [varchar](255) NOT NULL, + [RegionUUID] [varchar](255) NULL, + [ParentID] [int] NULL, + [CreationDate] [int] NULL, + [Name] [varchar](255) NULL, + [SceneGroupID] [varchar](255) NULL, + [Text] [varchar](255) NULL, + [Description] [varchar](255) NULL, + [SitName] [varchar](255) NULL, + [TouchName] [varchar](255) NULL, + [ObjectFlags] [int] NULL, + [CreatorID] [varchar](255) NULL, + [OwnerID] [varchar](255) NULL, + [GroupID] [varchar](255) NULL, + [LastOwnerID] [varchar](255) NULL, + [OwnerMask] [int] NULL, + [NextOwnerMask] [int] NULL, + [GroupMask] [int] NULL, + [EveryoneMask] [int] NULL, + [BaseMask] [int] NULL, + [PositionX] [float] NULL, + [PositionY] [float] NULL, + [PositionZ] [float] NULL, + [GroupPositionX] [float] NULL, + [GroupPositionY] [float] NULL, + [GroupPositionZ] [float] NULL, + [VelocityX] [float] NULL, + [VelocityY] [float] NULL, + [VelocityZ] [float] NULL, + [AngularVelocityX] [float] NULL, + [AngularVelocityY] [float] NULL, + [AngularVelocityZ] [float] NULL, + [AccelerationX] [float] NULL, + [AccelerationY] [float] NULL, + [AccelerationZ] [float] NULL, + [RotationX] [float] NULL, + [RotationY] [float] NULL, + [RotationZ] [float] NULL, + [RotationW] [float] NULL, + [SitTargetOffsetX] [float] NULL, + [SitTargetOffsetY] [float] NULL, + [SitTargetOffsetZ] [float] NULL, + [SitTargetOrientW] [float] NULL, + [SitTargetOrientX] [float] NULL, + [SitTargetOrientY] [float] NULL, + [SitTargetOrientZ] [float] NULL, +PRIMARY KEY CLUSTERED +( + [UUID] ASC +)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY] +) ON [PRIMARY] + +CREATE TABLE [dbo].[primshapes]( + [UUID] [varchar](255) NOT NULL, + [Shape] [int] NULL, + [ScaleX] [float] NULL, + [ScaleY] [float] NULL, + [ScaleZ] [float] NULL, + [PCode] [int] NULL, + [PathBegin] [int] NULL, + [PathEnd] [int] NULL, + [PathScaleX] [int] NULL, + [PathScaleY] [int] NULL, + [PathShearX] [int] NULL, + [PathShearY] [int] NULL, + [PathSkew] [int] NULL, + [PathCurve] [int] NULL, + [PathRadiusOffset] [int] NULL, + [PathRevolutions] [int] NULL, + [PathTaperX] [int] NULL, + [PathTaperY] [int] NULL, + [PathTwist] [int] NULL, + [PathTwistBegin] [int] NULL, + [ProfileBegin] [int] NULL, + [ProfileEnd] [int] NULL, + [ProfileCurve] [int] NULL, + [ProfileHollow] [int] NULL, + [State] [int] NULL, + [Texture] [image] NULL, + [ExtraParams] [image] NULL, +PRIMARY KEY CLUSTERED +( + [UUID] ASC +)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY] +) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] + +CREATE TABLE [dbo].[primitems]( + [itemID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, + [primID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, + [assetID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, + [parentFolderID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, + [invType] [int] NULL, + [assetType] [int] NULL, + [name] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, + [description] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, + [creationDate] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, + [creatorID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, + [ownerID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, + [lastOwnerID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, + [groupID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, + [nextPermissions] [int] NULL, + [currentPermissions] [int] NULL, + [basePermissions] [int] NULL, + [everyonePermissions] [int] NULL, + [groupPermissions] [int] NULL, +PRIMARY KEY CLUSTERED +( + [itemID] ASC +)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY] +) ON [PRIMARY] + +CREATE TABLE [dbo].[terrain]( + [RegionUUID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, + [Revision] [int] NULL, + [Heightfield] [image] NULL +) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] + +CREATE TABLE [dbo].[land]( + [UUID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, + [RegionUUID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, + [LocalLandID] [int] NULL, + [Bitmap] [image] NULL, + [Name] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, + [Description] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, + [OwnerUUID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, + [IsGroupOwned] [int] NULL, + [Area] [int] NULL, + [AuctionID] [int] NULL, + [Category] [int] NULL, + [ClaimDate] [int] NULL, + [ClaimPrice] [int] NULL, + [GroupUUID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, + [SalePrice] [int] NULL, + [LandStatus] [int] NULL, + [LandFlags] [int] NULL, + [LandingType] [int] NULL, + [MediaAutoScale] [int] NULL, + [MediaTextureUUID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, + [MediaURL] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, + [MusicURL] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, + [PassHours] [float] NULL, + [PassPrice] [int] NULL, + [SnapshotUUID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, + [UserLocationX] [float] NULL, + [UserLocationY] [float] NULL, + [UserLocationZ] [float] NULL, + [UserLookAtX] [float] NULL, + [UserLookAtY] [float] NULL, + [UserLookAtZ] [float] NULL, +PRIMARY KEY CLUSTERED +( + [UUID] ASC +)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY] +) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] + +CREATE TABLE [dbo].[landaccesslist]( + [LandUUID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, + [AccessUUID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, + [Flags] [int] NULL +) ON [PRIMARY] + +:VERSION 2 + +BEGIN TRANSACTION + +CREATE TABLE regionban ( + [regionUUID] VARCHAR(36) NOT NULL, + [bannedUUID] VARCHAR(36) NOT NULL, + [bannedIp] VARCHAR(16) NOT NULL, + [bannedIpHostMask] VARCHAR(16) NOT NULL) + +create table [dbo].[regionsettings] ( + [regionUUID] [varchar](36) not null, + [block_terraform] [bit] not null, + [block_fly] [bit] not null, + [allow_damage] [bit] not null, + [restrict_pushing] [bit] not null, + [allow_land_resell] [bit] not null, + [allow_land_join_divide] [bit] not null, + [block_show_in_search] [bit] not null, + [agent_limit] [int] not null, + [object_bonus] [float] not null, + [maturity] [int] not null, + [disable_scripts] [bit] not null, + [disable_collisions] [bit] not null, + [disable_physics] [bit] not null, + [terrain_texture_1] [varchar](36) not null, + [terrain_texture_2] [varchar](36) not null, + [terrain_texture_3] [varchar](36) not null, + [terrain_texture_4] [varchar](36) not null, + [elevation_1_nw] [float] not null, + [elevation_2_nw] [float] not null, + [elevation_1_ne] [float] not null, + [elevation_2_ne] [float] not null, + [elevation_1_se] [float] not null, + [elevation_2_se] [float] not null, + [elevation_1_sw] [float] not null, + [elevation_2_sw] [float] not null, + [water_height] [float] not null, + [terrain_raise_limit] [float] not null, + [terrain_lower_limit] [float] not null, + [use_estate_sun] [bit] not null, + [fixed_sun] [bit] not null, + [sun_position] [float] not null, + [covenant] [varchar](36) default NULL, + [Sandbox] [bit] NOT NULL, +PRIMARY KEY CLUSTERED +( + [regionUUID] ASC +)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY] +) ON [PRIMARY] + +COMMIT + +:VERSION 3 + +BEGIN TRANSACTION + +CREATE TABLE dbo.Tmp_prims + ( + UUID varchar(36) NOT NULL, + RegionUUID varchar(36) NULL, + ParentID int NULL, + CreationDate int NULL, + Name varchar(255) NULL, + SceneGroupID varchar(36) NULL, + Text varchar(255) NULL, + Description varchar(255) NULL, + SitName varchar(255) NULL, + TouchName varchar(255) NULL, + ObjectFlags int NULL, + CreatorID varchar(36) NULL, + OwnerID varchar(36) NULL, + GroupID varchar(36) NULL, + LastOwnerID varchar(36) NULL, + OwnerMask int NULL, + NextOwnerMask int NULL, + GroupMask int NULL, + EveryoneMask int NULL, + BaseMask int NULL, + PositionX float(53) NULL, + PositionY float(53) NULL, + PositionZ float(53) NULL, + GroupPositionX float(53) NULL, + GroupPositionY float(53) NULL, + GroupPositionZ float(53) NULL, + VelocityX float(53) NULL, + VelocityY float(53) NULL, + VelocityZ float(53) NULL, + AngularVelocityX float(53) NULL, + AngularVelocityY float(53) NULL, + AngularVelocityZ float(53) NULL, + AccelerationX float(53) NULL, + AccelerationY float(53) NULL, + AccelerationZ float(53) NULL, + RotationX float(53) NULL, + RotationY float(53) NULL, + RotationZ float(53) NULL, + RotationW float(53) NULL, + SitTargetOffsetX float(53) NULL, + SitTargetOffsetY float(53) NULL, + SitTargetOffsetZ float(53) NULL, + SitTargetOrientW float(53) NULL, + SitTargetOrientX float(53) NULL, + SitTargetOrientY float(53) NULL, + SitTargetOrientZ float(53) NULL + ) ON [PRIMARY] + +IF EXISTS(SELECT * FROM dbo.prims) + EXEC('INSERT INTO dbo.Tmp_prims (UUID, RegionUUID, ParentID, CreationDate, Name, SceneGroupID, Text, Description, SitName, TouchName, ObjectFlags, CreatorID, OwnerID, GroupID, LastOwnerID, OwnerMask, NextOwnerMask, GroupMask, EveryoneMask, BaseMask, PositionX, PositionY, PositionZ, GroupPositionX, GroupPositionY, GroupPositionZ, VelocityX, VelocityY, VelocityZ, AngularVelocityX, AngularVelocityY, AngularVelocityZ, AccelerationX, AccelerationY, AccelerationZ, RotationX, RotationY, RotationZ, RotationW, SitTargetOffsetX, SitTargetOffsetY, SitTargetOffsetZ, SitTargetOrientW, SitTargetOrientX, SitTargetOrientY, SitTargetOrientZ) + SELECT CONVERT(varchar(36), UUID), CONVERT(varchar(36), RegionUUID), ParentID, CreationDate, Name, CONVERT(varchar(36), SceneGroupID), Text, Description, SitName, TouchName, ObjectFlags, CONVERT(varchar(36), CreatorID), CONVERT(varchar(36), OwnerID), CONVERT(varchar(36), GroupID), CONVERT(varchar(36), LastOwnerID), OwnerMask, NextOwnerMask, GroupMask, EveryoneMask, BaseMask, PositionX, PositionY, PositionZ, GroupPositionX, GroupPositionY, GroupPositionZ, VelocityX, VelocityY, VelocityZ, AngularVelocityX, AngularVelocityY, AngularVelocityZ, AccelerationX, AccelerationY, AccelerationZ, RotationX, RotationY, RotationZ, RotationW, SitTargetOffsetX, SitTargetOffsetY, SitTargetOffsetZ, SitTargetOrientW, SitTargetOrientX, SitTargetOrientY, SitTargetOrientZ FROM dbo.prims WITH (HOLDLOCK TABLOCKX)') + +DROP TABLE dbo.prims + +EXECUTE sp_rename N'dbo.Tmp_prims', N'prims', 'OBJECT' + +ALTER TABLE dbo.prims ADD CONSTRAINT + PK__prims__10566F31 PRIMARY KEY CLUSTERED + ( + UUID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +COMMIT + +:VERSION 4 + +BEGIN TRANSACTION + +CREATE TABLE Tmp_primitems + ( + itemID varchar(36) NOT NULL, + primID varchar(36) NULL, + assetID varchar(36) NULL, + parentFolderID varchar(36) NULL, + invType int NULL, + assetType int NULL, + name varchar(255) NULL, + description varchar(255) NULL, + creationDate varchar(255) NULL, + creatorID varchar(36) NULL, + ownerID varchar(36) NULL, + lastOwnerID varchar(36) NULL, + groupID varchar(36) NULL, + nextPermissions int NULL, + currentPermissions int NULL, + basePermissions int NULL, + everyonePermissions int NULL, + groupPermissions int NULL + ) ON [PRIMARY] + +IF EXISTS(SELECT * FROM primitems) + EXEC('INSERT INTO Tmp_primitems (itemID, primID, assetID, parentFolderID, invType, assetType, name, description, creationDate, creatorID, ownerID, lastOwnerID, groupID, nextPermissions, currentPermissions, basePermissions, everyonePermissions, groupPermissions) + SELECT CONVERT(varchar(36), itemID), CONVERT(varchar(36), primID), CONVERT(varchar(36), assetID), CONVERT(varchar(36), parentFolderID), invType, assetType, name, description, creationDate, CONVERT(varchar(36), creatorID), CONVERT(varchar(36), ownerID), CONVERT(varchar(36), lastOwnerID), CONVERT(varchar(36), groupID), nextPermissions, currentPermissions, basePermissions, everyonePermissions, groupPermissions') + +DROP TABLE primitems + +EXECUTE sp_rename N'Tmp_primitems', N'primitems', 'OBJECT' + +ALTER TABLE primitems ADD CONSTRAINT + PK__primitems__0A688BB1 PRIMARY KEY CLUSTERED + ( + itemID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + + +COMMIT + + +:VERSION 5 + +BEGIN TRANSACTION + +CREATE TABLE Tmp_primshapes + ( + UUID varchar(36) NOT NULL, + Shape int NULL, + ScaleX float(53) NULL, + ScaleY float(53) NULL, + ScaleZ float(53) NULL, + PCode int NULL, + PathBegin int NULL, + PathEnd int NULL, + PathScaleX int NULL, + PathScaleY int NULL, + PathShearX int NULL, + PathShearY int NULL, + PathSkew int NULL, + PathCurve int NULL, + PathRadiusOffset int NULL, + PathRevolutions int NULL, + PathTaperX int NULL, + PathTaperY int NULL, + PathTwist int NULL, + PathTwistBegin int NULL, + ProfileBegin int NULL, + ProfileEnd int NULL, + ProfileCurve int NULL, + ProfileHollow int NULL, + State int NULL, + Texture image NULL, + ExtraParams image NULL + ) ON [PRIMARY] + TEXTIMAGE_ON [PRIMARY] + +IF EXISTS(SELECT * FROM primshapes) + EXEC('INSERT INTO Tmp_primshapes (UUID, Shape, ScaleX, ScaleY, ScaleZ, PCode, PathBegin, PathEnd, PathScaleX, PathScaleY, PathShearX, PathShearY, PathSkew, PathCurve, PathRadiusOffset, PathRevolutions, PathTaperX, PathTaperY, PathTwist, PathTwistBegin, ProfileBegin, ProfileEnd, ProfileCurve, ProfileHollow, State, Texture, ExtraParams) + SELECT CONVERT(varchar(36), UUID), Shape, ScaleX, ScaleY, ScaleZ, PCode, PathBegin, PathEnd, PathScaleX, PathScaleY, PathShearX, PathShearY, PathSkew, PathCurve, PathRadiusOffset, PathRevolutions, PathTaperX, PathTaperY, PathTwist, PathTwistBegin, ProfileBegin, ProfileEnd, ProfileCurve, ProfileHollow, State, Texture, ExtraParams FROM primshapes WITH (HOLDLOCK TABLOCKX)') + +DROP TABLE primshapes + +EXECUTE sp_rename N'Tmp_primshapes', N'primshapes', 'OBJECT' + +ALTER TABLE primshapes ADD CONSTRAINT + PK__primshapes__0880433F PRIMARY KEY CLUSTERED + ( + UUID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +COMMIT + + +:VERSION 6 + +BEGIN TRANSACTION + +ALTER TABLE prims ADD PayPrice int not null default 0 +ALTER TABLE prims ADD PayButton1 int not null default 0 +ALTER TABLE prims ADD PayButton2 int not null default 0 +ALTER TABLE prims ADD PayButton3 int not null default 0 +ALTER TABLE prims ADD PayButton4 int not null default 0 +ALTER TABLE prims ADD LoopedSound varchar(36) not null default '00000000-0000-0000-0000-000000000000'; +ALTER TABLE prims ADD LoopedSoundGain float not null default 0.0; +ALTER TABLE prims ADD TextureAnimation image +ALTER TABLE prims ADD OmegaX float not null default 0.0 +ALTER TABLE prims ADD OmegaY float not null default 0.0 +ALTER TABLE prims ADD OmegaZ float not null default 0.0 +ALTER TABLE prims ADD CameraEyeOffsetX float not null default 0.0 +ALTER TABLE prims ADD CameraEyeOffsetY float not null default 0.0 +ALTER TABLE prims ADD CameraEyeOffsetZ float not null default 0.0 +ALTER TABLE prims ADD CameraAtOffsetX float not null default 0.0 +ALTER TABLE prims ADD CameraAtOffsetY float not null default 0.0 +ALTER TABLE prims ADD CameraAtOffsetZ float not null default 0.0 +ALTER TABLE prims ADD ForceMouselook tinyint not null default 0 +ALTER TABLE prims ADD ScriptAccessPin int not null default 0 +ALTER TABLE prims ADD AllowedDrop tinyint not null default 0 +ALTER TABLE prims ADD DieAtEdge tinyint not null default 0 +ALTER TABLE prims ADD SalePrice int not null default 10 +ALTER TABLE prims ADD SaleType tinyint not null default 0 + +ALTER TABLE primitems add flags integer not null default 0 + +ALTER TABLE land ADD AuthbuyerID varchar(36) NOT NULL default '00000000-0000-0000-0000-000000000000' + +CREATE index prims_regionuuid on prims(RegionUUID) +CREATE index prims_parentid on prims(ParentID) + +CREATE index primitems_primid on primitems(primID) + +COMMIT + + +:VERSION 7 + +BEGIN TRANSACTION + +ALTER TABLE prims ADD ColorR int not null default 0; +ALTER TABLE prims ADD ColorG int not null default 0; +ALTER TABLE prims ADD ColorB int not null default 0; +ALTER TABLE prims ADD ColorA int not null default 0; +ALTER TABLE prims ADD ParticleSystem IMAGE; +ALTER TABLE prims ADD ClickAction tinyint NOT NULL default 0; + +COMMIT + + +:VERSION 8 + +BEGIN TRANSACTION + +ALTER TABLE land ADD OtherCleanTime integer NOT NULL default 0; +ALTER TABLE land ADD Dwell integer NOT NULL default 0; + +COMMIT + +:VERSION 9 + +BEGIN TRANSACTION + +ALTER TABLE prims ADD Material tinyint NOT NULL default 3 + +COMMIT + + +:VERSION 10 + +BEGIN TRANSACTION + +ALTER TABLE regionsettings ADD sunvectorx float NOT NULL default 0; +ALTER TABLE regionsettings ADD sunvectory float NOT NULL default 0; +ALTER TABLE regionsettings ADD sunvectorz float NOT NULL default 0; + +COMMIT + + +:VERSION 11 + +BEGIN TRANSACTION + +ALTER TABLE prims ADD CollisionSound char(36) not null default '00000000-0000-0000-0000-000000000000' +ALTER TABLE prims ADD CollisionSoundVolume float not null default 0.0 + +COMMIT + + +:VERSION 12 + +BEGIN TRANSACTION + +ALTER TABLE prims ADD LinkNumber integer not null default 0 + +COMMIT + + +:VERSION 13 + +BEGIN TRANSACTION + +CREATE TABLE dbo.Tmp_prims + ( + UUID uniqueidentifier NOT NULL, + RegionUUID uniqueidentifier NULL, + ParentID int NULL, + CreationDate int NULL, + Name varchar(255) NULL, + SceneGroupID uniqueidentifier NULL, + Text varchar(255) NULL, + Description varchar(255) NULL, + SitName varchar(255) NULL, + TouchName varchar(255) NULL, + ObjectFlags int NULL, + CreatorID uniqueidentifier NULL, + OwnerID uniqueidentifier NULL, + GroupID uniqueidentifier NULL, + LastOwnerID uniqueidentifier NULL, + OwnerMask int NULL, + NextOwnerMask int NULL, + GroupMask int NULL, + EveryoneMask int NULL, + BaseMask int NULL, + PositionX float(53) NULL, + PositionY float(53) NULL, + PositionZ float(53) NULL, + GroupPositionX float(53) NULL, + GroupPositionY float(53) NULL, + GroupPositionZ float(53) NULL, + VelocityX float(53) NULL, + VelocityY float(53) NULL, + VelocityZ float(53) NULL, + AngularVelocityX float(53) NULL, + AngularVelocityY float(53) NULL, + AngularVelocityZ float(53) NULL, + AccelerationX float(53) NULL, + AccelerationY float(53) NULL, + AccelerationZ float(53) NULL, + RotationX float(53) NULL, + RotationY float(53) NULL, + RotationZ float(53) NULL, + RotationW float(53) NULL, + SitTargetOffsetX float(53) NULL, + SitTargetOffsetY float(53) NULL, + SitTargetOffsetZ float(53) NULL, + SitTargetOrientW float(53) NULL, + SitTargetOrientX float(53) NULL, + SitTargetOrientY float(53) NULL, + SitTargetOrientZ float(53) NULL, + PayPrice int NOT NULL DEFAULT ((0)), + PayButton1 int NOT NULL DEFAULT ((0)), + PayButton2 int NOT NULL DEFAULT ((0)), + PayButton3 int NOT NULL DEFAULT ((0)), + PayButton4 int NOT NULL DEFAULT ((0)), + LoopedSound uniqueidentifier NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000'), + LoopedSoundGain float(53) NOT NULL DEFAULT ((0.0)), + TextureAnimation image NULL, + OmegaX float(53) NOT NULL DEFAULT ((0.0)), + OmegaY float(53) NOT NULL DEFAULT ((0.0)), + OmegaZ float(53) NOT NULL DEFAULT ((0.0)), + CameraEyeOffsetX float(53) NOT NULL DEFAULT ((0.0)), + CameraEyeOffsetY float(53) NOT NULL DEFAULT ((0.0)), + CameraEyeOffsetZ float(53) NOT NULL DEFAULT ((0.0)), + CameraAtOffsetX float(53) NOT NULL DEFAULT ((0.0)), + CameraAtOffsetY float(53) NOT NULL DEFAULT ((0.0)), + CameraAtOffsetZ float(53) NOT NULL DEFAULT ((0.0)), + ForceMouselook tinyint NOT NULL DEFAULT ((0)), + ScriptAccessPin int NOT NULL DEFAULT ((0)), + AllowedDrop tinyint NOT NULL DEFAULT ((0)), + DieAtEdge tinyint NOT NULL DEFAULT ((0)), + SalePrice int NOT NULL DEFAULT ((10)), + SaleType tinyint NOT NULL DEFAULT ((0)), + ColorR int NOT NULL DEFAULT ((0)), + ColorG int NOT NULL DEFAULT ((0)), + ColorB int NOT NULL DEFAULT ((0)), + ColorA int NOT NULL DEFAULT ((0)), + ParticleSystem image NULL, + ClickAction tinyint NOT NULL DEFAULT ((0)), + Material tinyint NOT NULL DEFAULT ((3)), + CollisionSound uniqueidentifier NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000'), + CollisionSoundVolume float(53) NOT NULL DEFAULT ((0.0)), + LinkNumber int NOT NULL DEFAULT ((0)) + ) ON [PRIMARY] + TEXTIMAGE_ON [PRIMARY] + +IF EXISTS(SELECT * FROM dbo.prims) + EXEC('INSERT INTO dbo.Tmp_prims (UUID, RegionUUID, ParentID, CreationDate, Name, SceneGroupID, Text, Description, SitName, TouchName, ObjectFlags, CreatorID, OwnerID, GroupID, LastOwnerID, OwnerMask, NextOwnerMask, GroupMask, EveryoneMask, BaseMask, PositionX, PositionY, PositionZ, GroupPositionX, GroupPositionY, GroupPositionZ, VelocityX, VelocityY, VelocityZ, AngularVelocityX, AngularVelocityY, AngularVelocityZ, AccelerationX, AccelerationY, AccelerationZ, RotationX, RotationY, RotationZ, RotationW, SitTargetOffsetX, SitTargetOffsetY, SitTargetOffsetZ, SitTargetOrientW, SitTargetOrientX, SitTargetOrientY, SitTargetOrientZ, PayPrice, PayButton1, PayButton2, PayButton3, PayButton4, LoopedSound, LoopedSoundGain, TextureAnimation, OmegaX, OmegaY, OmegaZ, CameraEyeOffsetX, CameraEyeOffsetY, CameraEyeOffsetZ, CameraAtOffsetX, CameraAtOffsetY, CameraAtOffsetZ, ForceMouselook, ScriptAccessPin, AllowedDrop, DieAtEdge, SalePrice, SaleType, ColorR, ColorG, ColorB, ColorA, ParticleSystem, ClickAction, Material, CollisionSound, CollisionSoundVolume, LinkNumber) + SELECT CONVERT(uniqueidentifier, UUID), CONVERT(uniqueidentifier, RegionUUID), ParentID, CreationDate, Name, CONVERT(uniqueidentifier, SceneGroupID), Text, Description, SitName, TouchName, ObjectFlags, CONVERT(uniqueidentifier, CreatorID), CONVERT(uniqueidentifier, OwnerID), CONVERT(uniqueidentifier, GroupID), CONVERT(uniqueidentifier, LastOwnerID), OwnerMask, NextOwnerMask, GroupMask, EveryoneMask, BaseMask, PositionX, PositionY, PositionZ, GroupPositionX, GroupPositionY, GroupPositionZ, VelocityX, VelocityY, VelocityZ, AngularVelocityX, AngularVelocityY, AngularVelocityZ, AccelerationX, AccelerationY, AccelerationZ, RotationX, RotationY, RotationZ, RotationW, SitTargetOffsetX, SitTargetOffsetY, SitTargetOffsetZ, SitTargetOrientW, SitTargetOrientX, SitTargetOrientY, SitTargetOrientZ, PayPrice, PayButton1, PayButton2, PayButton3, PayButton4, CONVERT(uniqueidentifier, LoopedSound), LoopedSoundGain, TextureAnimation, OmegaX, OmegaY, OmegaZ, CameraEyeOffsetX, CameraEyeOffsetY, CameraEyeOffsetZ, CameraAtOffsetX, CameraAtOffsetY, CameraAtOffsetZ, ForceMouselook, ScriptAccessPin, AllowedDrop, DieAtEdge, SalePrice, SaleType, ColorR, ColorG, ColorB, ColorA, ParticleSystem, ClickAction, Material, CONVERT(uniqueidentifier, CollisionSound), CollisionSoundVolume, LinkNumber FROM dbo.prims WITH (HOLDLOCK TABLOCKX)') + +DROP TABLE dbo.prims + +EXECUTE sp_rename N'dbo.Tmp_prims', N'prims', 'OBJECT' + +ALTER TABLE dbo.prims ADD CONSTRAINT + PK__prims__10566F31 PRIMARY KEY CLUSTERED + ( + UUID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + + +CREATE NONCLUSTERED INDEX prims_regionuuid ON dbo.prims + ( + RegionUUID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +CREATE NONCLUSTERED INDEX prims_parentid ON dbo.prims + ( + ParentID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +COMMIT + + +:VERSION 14 + +BEGIN TRANSACTION + +CREATE TABLE dbo.Tmp_primshapes + ( + UUID uniqueidentifier NOT NULL, + Shape int NULL, + ScaleX float(53) NULL, + ScaleY float(53) NULL, + ScaleZ float(53) NULL, + PCode int NULL, + PathBegin int NULL, + PathEnd int NULL, + PathScaleX int NULL, + PathScaleY int NULL, + PathShearX int NULL, + PathShearY int NULL, + PathSkew int NULL, + PathCurve int NULL, + PathRadiusOffset int NULL, + PathRevolutions int NULL, + PathTaperX int NULL, + PathTaperY int NULL, + PathTwist int NULL, + PathTwistBegin int NULL, + ProfileBegin int NULL, + ProfileEnd int NULL, + ProfileCurve int NULL, + ProfileHollow int NULL, + State int NULL, + Texture image NULL, + ExtraParams image NULL + ) ON [PRIMARY] + TEXTIMAGE_ON [PRIMARY] + +IF EXISTS(SELECT * FROM dbo.primshapes) + EXEC('INSERT INTO dbo.Tmp_primshapes (UUID, Shape, ScaleX, ScaleY, ScaleZ, PCode, PathBegin, PathEnd, PathScaleX, PathScaleY, PathShearX, PathShearY, PathSkew, PathCurve, PathRadiusOffset, PathRevolutions, PathTaperX, PathTaperY, PathTwist, PathTwistBegin, ProfileBegin, ProfileEnd, ProfileCurve, ProfileHollow, State, Texture, ExtraParams) + SELECT CONVERT(uniqueidentifier, UUID), Shape, ScaleX, ScaleY, ScaleZ, PCode, PathBegin, PathEnd, PathScaleX, PathScaleY, PathShearX, PathShearY, PathSkew, PathCurve, PathRadiusOffset, PathRevolutions, PathTaperX, PathTaperY, PathTwist, PathTwistBegin, ProfileBegin, ProfileEnd, ProfileCurve, ProfileHollow, State, Texture, ExtraParams FROM dbo.primshapes WITH (HOLDLOCK TABLOCKX)') + +DROP TABLE dbo.primshapes + +EXECUTE sp_rename N'dbo.Tmp_primshapes', N'primshapes', 'OBJECT' + +ALTER TABLE dbo.primshapes ADD CONSTRAINT + PK__primshapes__0880433F PRIMARY KEY CLUSTERED + ( + UUID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +COMMIT + + +:VERSION 15 + +BEGIN TRANSACTION + +CREATE TABLE dbo.Tmp_primitems + ( + itemID uniqueidentifier NOT NULL, + primID uniqueidentifier NULL, + assetID uniqueidentifier NULL, + parentFolderID uniqueidentifier NULL, + invType int NULL, + assetType int NULL, + name varchar(255) NULL, + description varchar(255) NULL, + creationDate varchar(255) NULL, + creatorID uniqueidentifier NULL, + ownerID uniqueidentifier NULL, + lastOwnerID uniqueidentifier NULL, + groupID uniqueidentifier NULL, + nextPermissions int NULL, + currentPermissions int NULL, + basePermissions int NULL, + everyonePermissions int NULL, + groupPermissions int NULL, + flags int NOT NULL DEFAULT ((0)) + ) ON [PRIMARY] + +IF EXISTS(SELECT * FROM dbo.primitems) + EXEC('INSERT INTO dbo.Tmp_primitems (itemID, primID, assetID, parentFolderID, invType, assetType, name, description, creationDate, creatorID, ownerID, lastOwnerID, groupID, nextPermissions, currentPermissions, basePermissions, everyonePermissions, groupPermissions, flags) + SELECT CONVERT(uniqueidentifier, itemID), CONVERT(uniqueidentifier, primID), CONVERT(uniqueidentifier, assetID), CONVERT(uniqueidentifier, parentFolderID), invType, assetType, name, description, creationDate, CONVERT(uniqueidentifier, creatorID), CONVERT(uniqueidentifier, ownerID), CONVERT(uniqueidentifier, lastOwnerID), CONVERT(uniqueidentifier, groupID), nextPermissions, currentPermissions, basePermissions, everyonePermissions, groupPermissions, flags FROM dbo.primitems WITH (HOLDLOCK TABLOCKX)') + +DROP TABLE dbo.primitems + +EXECUTE sp_rename N'dbo.Tmp_primitems', N'primitems', 'OBJECT' + +ALTER TABLE dbo.primitems ADD CONSTRAINT + PK__primitems__0A688BB1 PRIMARY KEY CLUSTERED + ( + itemID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +CREATE NONCLUSTERED INDEX primitems_primid ON dbo.primitems + ( + primID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +COMMIT + + +:VERSION 16 + + +BEGIN TRANSACTION + +CREATE TABLE dbo.Tmp_terrain + ( + RegionUUID uniqueidentifier NULL, + Revision int NULL, + Heightfield image NULL + ) ON [PRIMARY] + TEXTIMAGE_ON [PRIMARY] + +IF EXISTS(SELECT * FROM dbo.terrain) + EXEC('INSERT INTO dbo.Tmp_terrain (RegionUUID, Revision, Heightfield) + SELECT CONVERT(uniqueidentifier, RegionUUID), Revision, Heightfield FROM dbo.terrain WITH (HOLDLOCK TABLOCKX)') + +DROP TABLE dbo.terrain + +EXECUTE sp_rename N'dbo.Tmp_terrain', N'terrain', 'OBJECT' + +COMMIT + + +:VERSION 17 + +BEGIN TRANSACTION + +CREATE TABLE dbo.Tmp_land + ( + UUID uniqueidentifier NOT NULL, + RegionUUID uniqueidentifier NULL, + LocalLandID int NULL, + Bitmap image NULL, + Name varchar(255) NULL, + Description varchar(255) NULL, + OwnerUUID uniqueidentifier NULL, + IsGroupOwned int NULL, + Area int NULL, + AuctionID int NULL, + Category int NULL, + ClaimDate int NULL, + ClaimPrice int NULL, + GroupUUID uniqueidentifier NULL, + SalePrice int NULL, + LandStatus int NULL, + LandFlags int NULL, + LandingType int NULL, + MediaAutoScale int NULL, + MediaTextureUUID uniqueidentifier NULL, + MediaURL varchar(255) NULL, + MusicURL varchar(255) NULL, + PassHours float(53) NULL, + PassPrice int NULL, + SnapshotUUID uniqueidentifier NULL, + UserLocationX float(53) NULL, + UserLocationY float(53) NULL, + UserLocationZ float(53) NULL, + UserLookAtX float(53) NULL, + UserLookAtY float(53) NULL, + UserLookAtZ float(53) NULL, + AuthbuyerID uniqueidentifier NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000'), + OtherCleanTime int NOT NULL DEFAULT ((0)), + Dwell int NOT NULL DEFAULT ((0)) + ) ON [PRIMARY] + TEXTIMAGE_ON [PRIMARY] + +IF EXISTS(SELECT * FROM dbo.land) + EXEC('INSERT INTO dbo.Tmp_land (UUID, RegionUUID, LocalLandID, Bitmap, Name, Description, OwnerUUID, IsGroupOwned, Area, AuctionID, Category, ClaimDate, ClaimPrice, GroupUUID, SalePrice, LandStatus, LandFlags, LandingType, MediaAutoScale, MediaTextureUUID, MediaURL, MusicURL, PassHours, PassPrice, SnapshotUUID, UserLocationX, UserLocationY, UserLocationZ, UserLookAtX, UserLookAtY, UserLookAtZ, AuthbuyerID, OtherCleanTime, Dwell) + SELECT CONVERT(uniqueidentifier, UUID), CONVERT(uniqueidentifier, RegionUUID), LocalLandID, Bitmap, Name, Description, CONVERT(uniqueidentifier, OwnerUUID), IsGroupOwned, Area, AuctionID, Category, ClaimDate, ClaimPrice, CONVERT(uniqueidentifier, GroupUUID), SalePrice, LandStatus, LandFlags, LandingType, MediaAutoScale, CONVERT(uniqueidentifier, MediaTextureUUID), MediaURL, MusicURL, PassHours, PassPrice, CONVERT(uniqueidentifier, SnapshotUUID), UserLocationX, UserLocationY, UserLocationZ, UserLookAtX, UserLookAtY, UserLookAtZ, CONVERT(uniqueidentifier, AuthbuyerID), OtherCleanTime, Dwell FROM dbo.land WITH (HOLDLOCK TABLOCKX)') + +DROP TABLE dbo.land + +EXECUTE sp_rename N'dbo.Tmp_land', N'land', 'OBJECT' + +ALTER TABLE dbo.land ADD CONSTRAINT + PK__land__65A475E71BFD2C07 PRIMARY KEY CLUSTERED + ( + UUID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +COMMIT + + + +:VERSION 18 + +BEGIN TRANSACTION + +CREATE TABLE dbo.Tmp_landaccesslist + ( + LandUUID uniqueidentifier NULL, + AccessUUID uniqueidentifier NULL, + Flags int NULL + ) ON [PRIMARY] + +IF EXISTS(SELECT * FROM dbo.landaccesslist) + EXEC('INSERT INTO dbo.Tmp_landaccesslist (LandUUID, AccessUUID, Flags) + SELECT CONVERT(uniqueidentifier, LandUUID), CONVERT(uniqueidentifier, AccessUUID), Flags FROM dbo.landaccesslist WITH (HOLDLOCK TABLOCKX)') + +DROP TABLE dbo.landaccesslist + +EXECUTE sp_rename N'dbo.Tmp_landaccesslist', N'landaccesslist', 'OBJECT' + +COMMIT + + + +:VERSION 19 + +BEGIN TRANSACTION + +CREATE TABLE dbo.Tmp_regionban + ( + regionUUID uniqueidentifier NOT NULL, + bannedUUID uniqueidentifier NOT NULL, + bannedIp varchar(16) NOT NULL, + bannedIpHostMask varchar(16) NOT NULL + ) ON [PRIMARY] + +IF EXISTS(SELECT * FROM dbo.regionban) + EXEC('INSERT INTO dbo.Tmp_regionban (regionUUID, bannedUUID, bannedIp, bannedIpHostMask) + SELECT CONVERT(uniqueidentifier, regionUUID), CONVERT(uniqueidentifier, bannedUUID), bannedIp, bannedIpHostMask FROM dbo.regionban WITH (HOLDLOCK TABLOCKX)') + +DROP TABLE dbo.regionban + +EXECUTE sp_rename N'dbo.Tmp_regionban', N'regionban', 'OBJECT' + +COMMIT + + +:VERSION 20 + +BEGIN TRANSACTION + +CREATE TABLE dbo.Tmp_regionsettings + ( + regionUUID uniqueidentifier NOT NULL, + block_terraform bit NOT NULL, + block_fly bit NOT NULL, + allow_damage bit NOT NULL, + restrict_pushing bit NOT NULL, + allow_land_resell bit NOT NULL, + allow_land_join_divide bit NOT NULL, + block_show_in_search bit NOT NULL, + agent_limit int NOT NULL, + object_bonus float(53) NOT NULL, + maturity int NOT NULL, + disable_scripts bit NOT NULL, + disable_collisions bit NOT NULL, + disable_physics bit NOT NULL, + terrain_texture_1 uniqueidentifier NOT NULL, + terrain_texture_2 uniqueidentifier NOT NULL, + terrain_texture_3 uniqueidentifier NOT NULL, + terrain_texture_4 uniqueidentifier NOT NULL, + elevation_1_nw float(53) NOT NULL, + elevation_2_nw float(53) NOT NULL, + elevation_1_ne float(53) NOT NULL, + elevation_2_ne float(53) NOT NULL, + elevation_1_se float(53) NOT NULL, + elevation_2_se float(53) NOT NULL, + elevation_1_sw float(53) NOT NULL, + elevation_2_sw float(53) NOT NULL, + water_height float(53) NOT NULL, + terrain_raise_limit float(53) NOT NULL, + terrain_lower_limit float(53) NOT NULL, + use_estate_sun bit NOT NULL, + fixed_sun bit NOT NULL, + sun_position float(53) NOT NULL, + covenant uniqueidentifier NULL DEFAULT (NULL), + Sandbox bit NOT NULL, + sunvectorx float(53) NOT NULL DEFAULT ((0)), + sunvectory float(53) NOT NULL DEFAULT ((0)), + sunvectorz float(53) NOT NULL DEFAULT ((0)) + ) ON [PRIMARY] + +IF EXISTS(SELECT * FROM dbo.regionsettings) + EXEC('INSERT INTO dbo.Tmp_regionsettings (regionUUID, block_terraform, block_fly, allow_damage, restrict_pushing, allow_land_resell, allow_land_join_divide, block_show_in_search, agent_limit, object_bonus, maturity, disable_scripts, disable_collisions, disable_physics, terrain_texture_1, terrain_texture_2, terrain_texture_3, terrain_texture_4, elevation_1_nw, elevation_2_nw, elevation_1_ne, elevation_2_ne, elevation_1_se, elevation_2_se, elevation_1_sw, elevation_2_sw, water_height, terrain_raise_limit, terrain_lower_limit, use_estate_sun, fixed_sun, sun_position, covenant, Sandbox, sunvectorx, sunvectory, sunvectorz) + SELECT CONVERT(uniqueidentifier, regionUUID), block_terraform, block_fly, allow_damage, restrict_pushing, allow_land_resell, allow_land_join_divide, block_show_in_search, agent_limit, object_bonus, maturity, disable_scripts, disable_collisions, disable_physics, CONVERT(uniqueidentifier, terrain_texture_1), CONVERT(uniqueidentifier, terrain_texture_2), CONVERT(uniqueidentifier, terrain_texture_3), CONVERT(uniqueidentifier, terrain_texture_4), elevation_1_nw, elevation_2_nw, elevation_1_ne, elevation_2_ne, elevation_1_se, elevation_2_se, elevation_1_sw, elevation_2_sw, water_height, terrain_raise_limit, terrain_lower_limit, use_estate_sun, fixed_sun, sun_position, CONVERT(uniqueidentifier, covenant), Sandbox, sunvectorx, sunvectory, sunvectorz FROM dbo.regionsettings WITH (HOLDLOCK TABLOCKX)') + +DROP TABLE dbo.regionsettings + +EXECUTE sp_rename N'dbo.Tmp_regionsettings', N'regionsettings', 'OBJECT' + +ALTER TABLE dbo.regionsettings ADD CONSTRAINT + PK__regionse__5B35159D21B6055D PRIMARY KEY CLUSTERED + ( + regionUUID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +COMMIT + + +:VERSION 21 + +BEGIN TRANSACTION + +ALTER TABLE prims ADD PassTouches bit not null default 0 + +COMMIT + + +:VERSION 22 + +BEGIN TRANSACTION + +ALTER TABLE regionsettings ADD loaded_creation_date varchar(20) +ALTER TABLE regionsettings ADD loaded_creation_time varchar(20) +ALTER TABLE regionsettings ADD loaded_creation_id varchar(64) + +COMMIT + +:VERSION 23 + +BEGIN TRANSACTION + +ALTER TABLE regionsettings DROP COLUMN loaded_creation_date +ALTER TABLE regionsettings DROP COLUMN loaded_creation_time +ALTER TABLE regionsettings ADD loaded_creation_datetime int NOT NULL default 0 + +COMMIT + + + diff --git a/OpenSim/Data/MSSQL/Resources/UserAccount.migrations b/OpenSim/Data/MSSQL/Resources/UserAccount.migrations new file mode 100644 index 0000000000..8534e235c9 --- /dev/null +++ b/OpenSim/Data/MSSQL/Resources/UserAccount.migrations @@ -0,0 +1,55 @@ +:VERSION 1 + +CREATE TABLE [UserAccounts] ( + [PrincipalID] uniqueidentifier NOT NULL, + [ScopeID] uniqueidentifier NOT NULL, + [FirstName] [varchar](64) NOT NULL, + [LastName] [varchar](64) NOT NULL, + [Email] [varchar](64) NULL, + [ServiceURLs] [text] NULL, + [Created] [int] default NULL, + + PRIMARY KEY CLUSTERED +( + [PrincipalID] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] +) ON [PRIMARY] + + +:VERSION 2 + +BEGIN TRANSACTION + +INSERT INTO UserAccounts (PrincipalID, ScopeID, FirstName, LastName, Email, ServiceURLs, Created) SELECT [UUID] AS PrincipalID, '00000000-0000-0000-0000-000000000000' AS ScopeID, +username AS FirstName, +lastname AS LastName, +email as Email, ( +'AssetServerURI=' + +userAssetURI + ' InventoryServerURI=' + userInventoryURI + ' GatewayURI= HomeURI=') AS ServiceURLs, +created as Created FROM users; + + +COMMIT + +:VERSION 3 + +BEGIN TRANSACTION + +CREATE UNIQUE INDEX PrincipalID ON UserAccounts(PrincipalID); +CREATE INDEX Email ON UserAccounts(Email); +CREATE INDEX FirstName ON UserAccounts(FirstName); +CREATE INDEX LastName ON UserAccounts(LastName); +CREATE INDEX Name ON UserAccounts(FirstName,LastName); + +COMMIT + +:VERSION 4 + +BEGIN TRANSACTION + +ALTER TABLE UserAccounts ADD UserLevel integer NOT NULL DEFAULT 0; +ALTER TABLE UserAccounts ADD UserFlags integer NOT NULL DEFAULT 0; +ALTER TABLE UserAccounts ADD UserTitle varchar(64) NOT NULL DEFAULT ''; + +COMMIT + diff --git a/OpenSim/Data/MSSQL/Resources/UserStore.migrations b/OpenSim/Data/MSSQL/Resources/UserStore.migrations new file mode 100644 index 0000000000..050c544f64 --- /dev/null +++ b/OpenSim/Data/MSSQL/Resources/UserStore.migrations @@ -0,0 +1,421 @@ +:VERSION 1 + +CREATE TABLE [users] ( + [UUID] [varchar](36) NOT NULL default '', + [username] [varchar](32) NOT NULL, + [lastname] [varchar](32) NOT NULL, + [passwordHash] [varchar](32) NOT NULL, + [passwordSalt] [varchar](32) NOT NULL, + [homeRegion] [bigint] default NULL, + [homeLocationX] [float] default NULL, + [homeLocationY] [float] default NULL, + [homeLocationZ] [float] default NULL, + [homeLookAtX] [float] default NULL, + [homeLookAtY] [float] default NULL, + [homeLookAtZ] [float] default NULL, + [created] [int] NOT NULL, + [lastLogin] [int] NOT NULL, + [userInventoryURI] [varchar](255) default NULL, + [userAssetURI] [varchar](255) default NULL, + [profileCanDoMask] [int] default NULL, + [profileWantDoMask] [int] default NULL, + [profileAboutText] [ntext], + [profileFirstText] [ntext], + [profileImage] [varchar](36) default NULL, + [profileFirstImage] [varchar](36) default NULL, + [webLoginKey] [varchar](36) default NULL, + PRIMARY KEY CLUSTERED +( + [UUID] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] +) ON [PRIMARY] + + +CREATE NONCLUSTERED INDEX [usernames] ON [users] +( + [username] ASC, + [lastname] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + + +CREATE TABLE [agents] ( + [UUID] [varchar](36) NOT NULL, + [sessionID] [varchar](36) NOT NULL, + [secureSessionID] [varchar](36) NOT NULL, + [agentIP] [varchar](16) NOT NULL, + [agentPort] [int] NOT NULL, + [agentOnline] [tinyint] NOT NULL, + [loginTime] [int] NOT NULL, + [logoutTime] [int] NOT NULL, + [currentRegion] [varchar](36) NOT NULL, + [currentHandle] [bigint] NOT NULL, + [currentPos] [varchar](64) NOT NULL, + PRIMARY KEY CLUSTERED +( + [UUID] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] +) ON [PRIMARY] + + +CREATE NONCLUSTERED INDEX [session] ON [agents] +( + [sessionID] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +CREATE NONCLUSTERED INDEX [ssession] ON [agents] +( + [secureSessionID] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + + +CREATE TABLE [dbo].[userfriends]( + [ownerID] [varchar](50) COLLATE Latin1_General_CI_AS NOT NULL, + [friendID] [varchar](50) COLLATE Latin1_General_CI_AS NOT NULL, + [friendPerms] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, + [datetimestamp] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL +) ON [PRIMARY] + +CREATE TABLE [avatarappearance] ( + [Owner] [varchar](36) NOT NULL, + [Serial] int NOT NULL, + [Visual_Params] [image] NOT NULL, + [Texture] [image] NOT NULL, + [Avatar_Height] float NOT NULL, + [Body_Item] [varchar](36) NOT NULL, + [Body_Asset] [varchar](36) NOT NULL, + [Skin_Item] [varchar](36) NOT NULL, + [Skin_Asset] [varchar](36) NOT NULL, + [Hair_Item] [varchar](36) NOT NULL, + [Hair_Asset] [varchar](36) NOT NULL, + [Eyes_Item] [varchar](36) NOT NULL, + [Eyes_Asset] [varchar](36) NOT NULL, + [Shirt_Item] [varchar](36) NOT NULL, + [Shirt_Asset] [varchar](36) NOT NULL, + [Pants_Item] [varchar](36) NOT NULL, + [Pants_Asset] [varchar](36) NOT NULL, + [Shoes_Item] [varchar](36) NOT NULL, + [Shoes_Asset] [varchar](36) NOT NULL, + [Socks_Item] [varchar](36) NOT NULL, + [Socks_Asset] [varchar](36) NOT NULL, + [Jacket_Item] [varchar](36) NOT NULL, + [Jacket_Asset] [varchar](36) NOT NULL, + [Gloves_Item] [varchar](36) NOT NULL, + [Gloves_Asset] [varchar](36) NOT NULL, + [Undershirt_Item] [varchar](36) NOT NULL, + [Undershirt_Asset] [varchar](36) NOT NULL, + [Underpants_Item] [varchar](36) NOT NULL, + [Underpants_Asset] [varchar](36) NOT NULL, + [Skirt_Item] [varchar](36) NOT NULL, + [Skirt_Asset] [varchar](36) NOT NULL, + + PRIMARY KEY CLUSTERED ( + [Owner] + ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] +) ON [PRIMARY] + +:VERSION 2 + +BEGIN TRANSACTION + +ALTER TABLE users ADD homeRegionID varchar(36) NOT NULL default '00000000-0000-0000-0000-000000000000'; +ALTER TABLE users ADD userFlags int NOT NULL default 0; +ALTER TABLE users ADD godLevel int NOT NULL default 0; +ALTER TABLE users ADD customType varchar(32) not null default ''; +ALTER TABLE users ADD partner varchar(36) not null default '00000000-0000-0000-0000-000000000000'; + +COMMIT + + +:VERSION 3 + +BEGIN TRANSACTION + +CREATE TABLE [avatarattachments] ( + [UUID] varchar(36) NOT NULL + , [attachpoint] int NOT NULL + , [item] varchar(36) NOT NULL + , [asset] varchar(36) NOT NULL) + +CREATE NONCLUSTERED INDEX IX_avatarattachments ON dbo.avatarattachments + ( + UUID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + + +COMMIT + + +:VERSION 4 + +BEGIN TRANSACTION + +CREATE TABLE Tmp_userfriends + ( + ownerID varchar(36) NOT NULL, + friendID varchar(36) NOT NULL, + friendPerms int NOT NULL, + datetimestamp int NOT NULL + ) ON [PRIMARY] + +IF EXISTS(SELECT * FROM userfriends) + EXEC('INSERT INTO dbo.Tmp_userfriends (ownerID, friendID, friendPerms, datetimestamp) + SELECT CONVERT(varchar(36), ownerID), CONVERT(varchar(36), friendID), CONVERT(int, friendPerms), CONVERT(int, datetimestamp) FROM dbo.userfriends WITH (HOLDLOCK TABLOCKX)') + +DROP TABLE dbo.userfriends + +EXECUTE sp_rename N'Tmp_userfriends', N'userfriends', 'OBJECT' + +CREATE NONCLUSTERED INDEX IX_userfriends_ownerID ON userfriends + ( + ownerID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +CREATE NONCLUSTERED INDEX IX_userfriends_friendID ON userfriends + ( + friendID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +COMMIT + + +:VERSION 5 + +BEGIN TRANSACTION + + ALTER TABLE users add email varchar(250); + +COMMIT + + +:VERSION 6 + +BEGIN TRANSACTION + +CREATE TABLE dbo.Tmp_users + ( + UUID uniqueidentifier NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000'), + username varchar(32) NOT NULL, + lastname varchar(32) NOT NULL, + passwordHash varchar(32) NOT NULL, + passwordSalt varchar(32) NOT NULL, + homeRegion bigint NULL DEFAULT (NULL), + homeLocationX float(53) NULL DEFAULT (NULL), + homeLocationY float(53) NULL DEFAULT (NULL), + homeLocationZ float(53) NULL DEFAULT (NULL), + homeLookAtX float(53) NULL DEFAULT (NULL), + homeLookAtY float(53) NULL DEFAULT (NULL), + homeLookAtZ float(53) NULL DEFAULT (NULL), + created int NOT NULL, + lastLogin int NOT NULL, + userInventoryURI varchar(255) NULL DEFAULT (NULL), + userAssetURI varchar(255) NULL DEFAULT (NULL), + profileCanDoMask int NULL DEFAULT (NULL), + profileWantDoMask int NULL DEFAULT (NULL), + profileAboutText ntext NULL, + profileFirstText ntext NULL, + profileImage uniqueidentifier NULL DEFAULT (NULL), + profileFirstImage uniqueidentifier NULL DEFAULT (NULL), + webLoginKey uniqueidentifier NULL DEFAULT (NULL), + homeRegionID uniqueidentifier NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000'), + userFlags int NOT NULL DEFAULT ((0)), + godLevel int NOT NULL DEFAULT ((0)), + customType varchar(32) NOT NULL DEFAULT (''), + partner uniqueidentifier NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000'), + email varchar(250) NULL + ) ON [PRIMARY] + TEXTIMAGE_ON [PRIMARY] + +IF EXISTS(SELECT * FROM dbo.users) + EXEC('INSERT INTO dbo.Tmp_users (UUID, username, lastname, passwordHash, passwordSalt, homeRegion, homeLocationX, homeLocationY, homeLocationZ, homeLookAtX, homeLookAtY, homeLookAtZ, created, lastLogin, userInventoryURI, userAssetURI, profileCanDoMask, profileWantDoMask, profileAboutText, profileFirstText, profileImage, profileFirstImage, webLoginKey, homeRegionID, userFlags, godLevel, customType, partner, email) + SELECT CONVERT(uniqueidentifier, UUID), username, lastname, passwordHash, passwordSalt, homeRegion, homeLocationX, homeLocationY, homeLocationZ, homeLookAtX, homeLookAtY, homeLookAtZ, created, lastLogin, userInventoryURI, userAssetURI, profileCanDoMask, profileWantDoMask, profileAboutText, profileFirstText, CONVERT(uniqueidentifier, profileImage), CONVERT(uniqueidentifier, profileFirstImage), CONVERT(uniqueidentifier, webLoginKey), CONVERT(uniqueidentifier, homeRegionID), userFlags, godLevel, customType, CONVERT(uniqueidentifier, partner), email FROM dbo.users WITH (HOLDLOCK TABLOCKX)') + +DROP TABLE dbo.users + +EXECUTE sp_rename N'dbo.Tmp_users', N'users', 'OBJECT' + +ALTER TABLE dbo.users ADD CONSTRAINT + PK__users__65A475E737A5467C PRIMARY KEY CLUSTERED + ( + UUID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +CREATE NONCLUSTERED INDEX usernames ON dbo.users + ( + username, + lastname + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +COMMIT + + +:VERSION 7 + +BEGIN TRANSACTION + +CREATE TABLE dbo.Tmp_agents + ( + UUID uniqueidentifier NOT NULL, + sessionID uniqueidentifier NOT NULL, + secureSessionID uniqueidentifier NOT NULL, + agentIP varchar(16) NOT NULL, + agentPort int NOT NULL, + agentOnline tinyint NOT NULL, + loginTime int NOT NULL, + logoutTime int NOT NULL, + currentRegion uniqueidentifier NOT NULL, + currentHandle bigint NOT NULL, + currentPos varchar(64) NOT NULL + ) ON [PRIMARY] + +IF EXISTS(SELECT * FROM dbo.agents) + EXEC('INSERT INTO dbo.Tmp_agents (UUID, sessionID, secureSessionID, agentIP, agentPort, agentOnline, loginTime, logoutTime, currentRegion, currentHandle, currentPos) + SELECT CONVERT(uniqueidentifier, UUID), CONVERT(uniqueidentifier, sessionID), CONVERT(uniqueidentifier, secureSessionID), agentIP, agentPort, agentOnline, loginTime, logoutTime, CONVERT(uniqueidentifier, currentRegion), currentHandle, currentPos FROM dbo.agents WITH (HOLDLOCK TABLOCKX)') + +DROP TABLE dbo.agents + +EXECUTE sp_rename N'dbo.Tmp_agents', N'agents', 'OBJECT' + +ALTER TABLE dbo.agents ADD CONSTRAINT + PK__agents__65A475E749C3F6B7 PRIMARY KEY CLUSTERED + ( + UUID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +CREATE NONCLUSTERED INDEX session ON dbo.agents + ( + sessionID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +CREATE NONCLUSTERED INDEX ssession ON dbo.agents + ( + secureSessionID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +COMMIT + + +:VERSION 8 + +BEGIN TRANSACTION + +CREATE TABLE dbo.Tmp_userfriends + ( + ownerID uniqueidentifier NOT NULL, + friendID uniqueidentifier NOT NULL, + friendPerms int NOT NULL, + datetimestamp int NOT NULL + ) ON [PRIMARY] + +IF EXISTS(SELECT * FROM dbo.userfriends) + EXEC('INSERT INTO dbo.Tmp_userfriends (ownerID, friendID, friendPerms, datetimestamp) + SELECT CONVERT(uniqueidentifier, ownerID), CONVERT(uniqueidentifier, friendID), friendPerms, datetimestamp FROM dbo.userfriends WITH (HOLDLOCK TABLOCKX)') + +DROP TABLE dbo.userfriends + +EXECUTE sp_rename N'dbo.Tmp_userfriends', N'userfriends', 'OBJECT' + +CREATE NONCLUSTERED INDEX IX_userfriends_ownerID ON dbo.userfriends + ( + ownerID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +CREATE NONCLUSTERED INDEX IX_userfriends_friendID ON dbo.userfriends + ( + friendID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +COMMIT + + +:VERSION 9 + +BEGIN TRANSACTION + +CREATE TABLE dbo.Tmp_avatarappearance + ( + Owner uniqueidentifier NOT NULL, + Serial int NOT NULL, + Visual_Params image NOT NULL, + Texture image NOT NULL, + Avatar_Height float(53) NOT NULL, + Body_Item uniqueidentifier NOT NULL, + Body_Asset uniqueidentifier NOT NULL, + Skin_Item uniqueidentifier NOT NULL, + Skin_Asset uniqueidentifier NOT NULL, + Hair_Item uniqueidentifier NOT NULL, + Hair_Asset uniqueidentifier NOT NULL, + Eyes_Item uniqueidentifier NOT NULL, + Eyes_Asset uniqueidentifier NOT NULL, + Shirt_Item uniqueidentifier NOT NULL, + Shirt_Asset uniqueidentifier NOT NULL, + Pants_Item uniqueidentifier NOT NULL, + Pants_Asset uniqueidentifier NOT NULL, + Shoes_Item uniqueidentifier NOT NULL, + Shoes_Asset uniqueidentifier NOT NULL, + Socks_Item uniqueidentifier NOT NULL, + Socks_Asset uniqueidentifier NOT NULL, + Jacket_Item uniqueidentifier NOT NULL, + Jacket_Asset uniqueidentifier NOT NULL, + Gloves_Item uniqueidentifier NOT NULL, + Gloves_Asset uniqueidentifier NOT NULL, + Undershirt_Item uniqueidentifier NOT NULL, + Undershirt_Asset uniqueidentifier NOT NULL, + Underpants_Item uniqueidentifier NOT NULL, + Underpants_Asset uniqueidentifier NOT NULL, + Skirt_Item uniqueidentifier NOT NULL, + Skirt_Asset uniqueidentifier NOT NULL + ) ON [PRIMARY] + TEXTIMAGE_ON [PRIMARY] + +IF EXISTS(SELECT * FROM dbo.avatarappearance) + EXEC('INSERT INTO dbo.Tmp_avatarappearance (Owner, Serial, Visual_Params, Texture, Avatar_Height, Body_Item, Body_Asset, Skin_Item, Skin_Asset, Hair_Item, Hair_Asset, Eyes_Item, Eyes_Asset, Shirt_Item, Shirt_Asset, Pants_Item, Pants_Asset, Shoes_Item, Shoes_Asset, Socks_Item, Socks_Asset, Jacket_Item, Jacket_Asset, Gloves_Item, Gloves_Asset, Undershirt_Item, Undershirt_Asset, Underpants_Item, Underpants_Asset, Skirt_Item, Skirt_Asset) + SELECT CONVERT(uniqueidentifier, Owner), Serial, Visual_Params, Texture, Avatar_Height, CONVERT(uniqueidentifier, Body_Item), CONVERT(uniqueidentifier, Body_Asset), CONVERT(uniqueidentifier, Skin_Item), CONVERT(uniqueidentifier, Skin_Asset), CONVERT(uniqueidentifier, Hair_Item), CONVERT(uniqueidentifier, Hair_Asset), CONVERT(uniqueidentifier, Eyes_Item), CONVERT(uniqueidentifier, Eyes_Asset), CONVERT(uniqueidentifier, Shirt_Item), CONVERT(uniqueidentifier, Shirt_Asset), CONVERT(uniqueidentifier, Pants_Item), CONVERT(uniqueidentifier, Pants_Asset), CONVERT(uniqueidentifier, Shoes_Item), CONVERT(uniqueidentifier, Shoes_Asset), CONVERT(uniqueidentifier, Socks_Item), CONVERT(uniqueidentifier, Socks_Asset), CONVERT(uniqueidentifier, Jacket_Item), CONVERT(uniqueidentifier, Jacket_Asset), CONVERT(uniqueidentifier, Gloves_Item), CONVERT(uniqueidentifier, Gloves_Asset), CONVERT(uniqueidentifier, Undershirt_Item), CONVERT(uniqueidentifier, Undershirt_Asset), CONVERT(uniqueidentifier, Underpants_Item), CONVERT(uniqueidentifier, Underpants_Asset), CONVERT(uniqueidentifier, Skirt_Item), CONVERT(uniqueidentifier, Skirt_Asset) FROM dbo.avatarappearance WITH (HOLDLOCK TABLOCKX)') + +DROP TABLE dbo.avatarappearance + +EXECUTE sp_rename N'dbo.Tmp_avatarappearance', N'avatarappearance', 'OBJECT' + +ALTER TABLE dbo.avatarappearance ADD CONSTRAINT + PK__avatarap__7DD115CC4E88ABD4 PRIMARY KEY CLUSTERED + ( + Owner + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +COMMIT + + +:VERSION 10 + +BEGIN TRANSACTION + +CREATE TABLE dbo.Tmp_avatarattachments + ( + UUID uniqueidentifier NOT NULL, + attachpoint int NOT NULL, + item uniqueidentifier NOT NULL, + asset uniqueidentifier NOT NULL + ) ON [PRIMARY] + +IF EXISTS(SELECT * FROM dbo.avatarattachments) + EXEC('INSERT INTO dbo.Tmp_avatarattachments (UUID, attachpoint, item, asset) + SELECT CONVERT(uniqueidentifier, UUID), attachpoint, CONVERT(uniqueidentifier, item), CONVERT(uniqueidentifier, asset) FROM dbo.avatarattachments WITH (HOLDLOCK TABLOCKX)') + +DROP TABLE dbo.avatarattachments + +EXECUTE sp_rename N'dbo.Tmp_avatarattachments', N'avatarattachments', 'OBJECT' + +CREATE NONCLUSTERED INDEX IX_avatarattachments ON dbo.avatarattachments + ( + UUID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + +COMMIT + + +:VERSION 11 + +BEGIN TRANSACTION + +ALTER TABLE users ADD scopeID uniqueidentifier not null default '00000000-0000-0000-0000-000000000000' + +COMMIT diff --git a/OpenSim/Data/Migration.cs b/OpenSim/Data/Migration.cs index 4622e23ded..4f113a2f49 100644 --- a/OpenSim/Data/Migration.cs +++ b/OpenSim/Data/Migration.cs @@ -53,8 +53,8 @@ namespace OpenSim.Data /// When a database driver starts up, it specifies a resource that /// needs to be brought up to the current revision. For instance: /// - /// Migration um = new Migration(Assembly, DbConnection, "Users"); - /// um.Upgrade(); + /// Migration um = new Migration(DbConnection, Assembly, "Users"); + /// um.Update(); /// /// This works out which version Users is at, and applies all the /// revisions past it to it. If there is no users table, all @@ -72,58 +72,116 @@ namespace OpenSim.Data { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - private string _type; - private DbConnection _conn; - // private string _subtype; - private Assembly _assem; - private Regex _match; + protected string _type; + protected DbConnection _conn; + protected Assembly _assem; - private static readonly string _migrations_create = "create table migrations(name varchar(100), version int)"; - // private static readonly string _migrations_init = "insert into migrations values('migrations', 1)"; - // private static readonly string _migrations_find = "select version from migrations where name='migrations'"; + private Regex _match_old; + private Regex _match_new; - - public Migration(DbConnection conn, Assembly assem, string type) - { - _type = type; - _conn = conn; - _assem = assem; - _match = new Regex(@"\.(\d\d\d)_" + _type + @"\.sql"); - Initialize(); + /// Have the parameterless constructor just so we can specify it as a generic parameter with the new() constraint. + /// Currently this is only used in the tests. A Migration instance created this way must be then + /// initialized with Initialize(). Regular creation should be through the parameterized constructors. + /// + public Migration() + { } public Migration(DbConnection conn, Assembly assem, string subtype, string type) + { + Initialize(conn, assem, type, subtype); + } + + public Migration(DbConnection conn, Assembly assem, string type) + { + Initialize(conn, assem, type, ""); + } + + /// Must be called after creating with the parameterless constructor. + /// NOTE that the Migration class now doesn't access database in any way during initialization. + /// Specifically, it won't check if the [migrations] table exists. Such checks are done later: + /// automatically on Update(), or you can explicitly call InitMigrationsTable(). + /// + /// + /// + /// + /// + public void Initialize (DbConnection conn, Assembly assem, string type, string subtype) { _type = type; _conn = conn; _assem = assem; - _match = new Regex(subtype + @"\.(\d\d\d)_" + _type + @"\.sql"); - Initialize(); + _match_old = new Regex(subtype + @"\.(\d\d\d)_" + _type + @"\.sql"); + string s = String.IsNullOrEmpty(subtype) ? _type : _type + @"\." + subtype; + _match_new = new Regex(@"\." + s + @"\.migrations(?:\.(?\d+)$|.*)"); } - private void Initialize() + public void InitMigrationsTable() { - // clever, eh, we figure out which migrations version we are - int migration_version = FindVersion(_conn, "migrations"); - - if (migration_version > 0) - return; - - // If not, create the migration tables - DbCommand cmd = _conn.CreateCommand(); - cmd.CommandText = _migrations_create; - cmd.ExecuteNonQuery(); - cmd.Dispose(); - - InsertVersion("migrations", 1); + // NOTE: normally when the [migrations] table is created, the version record for 'migrations' is + // added immediately. However, if for some reason the table is there but empty, we want to handle that as well. + int ver = FindVersion(_conn, "migrations"); + if (ver <= 0) // -1 = no table, 0 = no version record + { + if( ver < 0 ) + ExecuteScript("create table migrations(name varchar(100), version int)"); + InsertVersion("migrations", 1); + } } + /// Executes a script, possibly in a database-specific way. + /// It can be redefined for a specific DBMS, if necessary. Specifically, + /// to avoid problems with proc definitions in MySQL, we must use + /// MySqlScript class instead of just DbCommand. We don't want to bring + /// MySQL references here, so instead define a MySQLMigration class + /// in OpenSim.Data.MySQL + /// + /// + /// Array of strings, one-per-batch (often just one) + protected virtual void ExecuteScript(DbConnection conn, string[] script) + { + using (DbCommand cmd = conn.CreateCommand()) + { + cmd.CommandTimeout = 0; + foreach (string sql in script) + { + cmd.CommandText = sql; + try + { + cmd.ExecuteNonQuery(); + } + catch(Exception e) + { + throw new Exception(e.Message + " in SQL: " + sql); + } + } + } + } + + protected void ExecuteScript(DbConnection conn, string sql) + { + ExecuteScript(conn, new string[]{sql}); + } + + protected void ExecuteScript(string sql) + { + ExecuteScript(_conn, sql); + } + + protected void ExecuteScript(string[] script) + { + ExecuteScript(_conn, script); + } + + + public void Update() { - int version = 0; - version = FindVersion(_conn, _type); + InitMigrationsTable(); - SortedList migrations = GetMigrationsAfter(version); + int version = FindVersion(_conn, _type); + + SortedList migrations = GetMigrationsAfter(version); if (migrations.Count < 1) return; @@ -131,21 +189,26 @@ namespace OpenSim.Data m_log.InfoFormat("[MIGRATIONS] Upgrading {0} to latest revision {1}.", _type, migrations.Keys[migrations.Count - 1]); m_log.Info("[MIGRATIONS] NOTE: this may take a while, don't interupt this process!"); - DbCommand cmd = _conn.CreateCommand(); - foreach (KeyValuePair kvp in migrations) + foreach (KeyValuePair kvp in migrations) { int newversion = kvp.Key; - cmd.CommandText = kvp.Value; // we need to up the command timeout to infinite as we might be doing long migrations. - cmd.CommandTimeout = 0; + + /* [AlexRa 01-May-10]: We can't always just run any SQL in a single batch (= ExecuteNonQuery()). Things like + * stored proc definitions might have to be sent to the server each in a separate batch. + * This is certainly so for MS SQL; not sure how the MySQL connector sorts out the mess + * with 'delimiter @@'/'delimiter ;' around procs. So each "script" this code executes now is not + * a single string, but an array of strings, executed separately. + */ try { - cmd.ExecuteNonQuery(); + ExecuteScript(kvp.Value); } catch (Exception e) { - m_log.DebugFormat("[MIGRATIONS] Cmd was {0}", cmd.CommandText); - m_log.DebugFormat("[MIGRATIONS]: An error has occurred in the migration {0}.\n This may mean you could see errors trying to run OpenSim. If you see database related errors, you will need to fix the issue manually. Continuing.", e.Message); + m_log.DebugFormat("[MIGRATIONS] Cmd was {0}", e.Message.Replace("\n", " ")); + m_log.Debug("[MIGRATIONS]: An error has occurred in the migration. This may mean you could see errors trying to run OpenSim. If you see database related errors, you will need to fix the issue manually. Continuing."); + ExecuteScript("ROLLBACK;"); } if (version == 0) @@ -157,28 +220,9 @@ namespace OpenSim.Data UpdateVersion(_type, newversion); } version = newversion; - cmd.Dispose(); } } - // private int MaxVersion() - // { - // int max = 0; - // string[] names = _assem.GetManifestResourceNames(); - - // foreach (string s in names) - // { - // Match m = _match.Match(s); - // if (m.Success) - // { - // int MigrationVersion = int.Parse(m.Groups[1].ToString()); - // if (MigrationVersion > max) - // max = MigrationVersion; - // } - // } - // return max; - // } - public int Version { get { return FindVersion(_conn, _type); } @@ -197,78 +241,176 @@ namespace OpenSim.Data protected virtual int FindVersion(DbConnection conn, string type) { int version = 0; - DbCommand cmd = conn.CreateCommand(); - try + using (DbCommand cmd = conn.CreateCommand()) { - cmd.CommandText = "select version from migrations where name='" + type +"' order by version desc"; - using (IDataReader reader = cmd.ExecuteReader()) + try { - if (reader.Read()) + cmd.CommandText = "select version from migrations where name='" + type + "' order by version desc"; + using (DbDataReader reader = cmd.ExecuteReader()) { - version = Convert.ToInt32(reader["version"]); + if (reader.Read()) + { + version = Convert.ToInt32(reader["version"]); + } + reader.Close(); } - reader.Close(); + } + catch + { + // Something went wrong (probably no table), so we're at version -1 + version = -1; } } - catch - { - // Something went wrong, so we're version 0 - } - cmd.Dispose(); return version; } private void InsertVersion(string type, int version) { - DbCommand cmd = _conn.CreateCommand(); - cmd.CommandText = "insert into migrations(name, version) values('" + type + "', " + version + ")"; m_log.InfoFormat("[MIGRATIONS]: Creating {0} at version {1}", type, version); - cmd.ExecuteNonQuery(); - cmd.Dispose(); + ExecuteScript("insert into migrations(name, version) values('" + type + "', " + version + ")"); } private void UpdateVersion(string type, int version) { - DbCommand cmd = _conn.CreateCommand(); - cmd.CommandText = "update migrations set version=" + version + " where name='" + type + "'"; m_log.InfoFormat("[MIGRATIONS]: Updating {0} to version {1}", type, version); - cmd.ExecuteNonQuery(); - cmd.Dispose(); + ExecuteScript("update migrations set version=" + version + " where name='" + type + "'"); } - // private SortedList GetAllMigrations() - // { - // return GetMigrationsAfter(0); - // } + private delegate void FlushProc(); - private SortedList GetMigrationsAfter(int after) + /// Scans for migration resources in either old-style "scattered" (one file per version) + /// or new-style "integrated" format (single file with ":VERSION nnn" sections). + /// In the new-style migrations it also recognizes ':GO' separators for parts of the SQL script + /// that must be sent to the server separately. The old-style migrations are loaded each in one piece + /// and don't support the ':GO' feature. + /// + /// The version we are currently at. Scan for any higher versions + /// A list of string arrays, representing the scripts. + private SortedList GetMigrationsAfter(int after) { - string[] names = _assem.GetManifestResourceNames(); - SortedList migrations = new SortedList(); - // because life is funny if we don't - Array.Sort(names); + SortedList migrations = new SortedList(); + string[] names = _assem.GetManifestResourceNames(); + if( names.Length == 0 ) // should never happen + return migrations; + + Array.Sort(names); // we want all the migrations ordered + + int nLastVerFound = 0; + Match m = null; + string sFile = Array.FindLast(names, nm => { m = _match_new.Match(nm); return m.Success; }); // ; nm.StartsWith(sPrefix, StringComparison.InvariantCultureIgnoreCase + + if( (m != null) && !String.IsNullOrEmpty(sFile) ) + { + /* The filename should be '.migrations[.NNN]' where NNN + * is the last version number defined in the file. If the '.NNN' part is recognized, the code can skip + * the file without looking inside if we have a higher version already. Without the suffix we read + * the file anyway and use the version numbers inside. Any unrecognized suffix (such as '.sql') + * is valid but ignored. + * + * NOTE that we expect only one 'merged' migration file. If there are several, we take the last one. + * If you are numbering them, leave only the latest one in the project or at least make sure they numbered + * to come up in the correct order (e.g. 'SomeStore.migrations.001' rather than 'SomeStore.migrations.1') + */ + + if (m.Groups.Count > 1 && int.TryParse(m.Groups[1].Value, out nLastVerFound)) + { + if( nLastVerFound <= after ) + goto scan_old_style; + } + + System.Text.StringBuilder sb = new System.Text.StringBuilder(4096); + int nVersion = -1; + + List script = new List(); + + FlushProc flush = delegate() + { + if (sb.Length > 0) // last SQL stmt to script list + { + script.Add(sb.ToString()); + sb.Length = 0; + } + + if ( (nVersion > 0) && (nVersion > after) && (script.Count > 0) && !migrations.ContainsKey(nVersion)) // script to the versioned script list + { + migrations[nVersion] = script.ToArray(); + } + script.Clear(); + }; + + using (Stream resource = _assem.GetManifestResourceStream(sFile)) + using (StreamReader resourceReader = new StreamReader(resource)) + { + int nLineNo = 0; + while (!resourceReader.EndOfStream) + { + string sLine = resourceReader.ReadLine(); + nLineNo++; + + if( String.IsNullOrEmpty(sLine) || sLine.StartsWith("#") ) // ignore a comment or empty line + continue; + + if (sLine.Trim().Equals(":GO", StringComparison.InvariantCultureIgnoreCase)) + { + if (sb.Length == 0) continue; + if (nVersion > after) + script.Add(sb.ToString()); + sb.Length = 0; + continue; + } + + if (sLine.StartsWith(":VERSION ", StringComparison.InvariantCultureIgnoreCase)) // ":VERSION nnn" + { + flush(); + + int n = sLine.IndexOf('#'); // Comment is allowed in version sections, ignored + if (n >= 0) + sLine = sLine.Substring(0, n); + + if (!int.TryParse(sLine.Substring(9).Trim(), out nVersion)) + { + m_log.ErrorFormat("[MIGRATIONS]: invalid version marker at {0}: line {1}. Migration failed!", sFile, nLineNo); + break; + } + } + else + { + sb.AppendLine(sLine); + } + } + flush(); + + // If there are scattered migration files as well, only look for those with higher version numbers. + if (after < nVersion) + after = nVersion; + } + } + +scan_old_style: + // scan "old style" migration pieces anyway, ignore any versions already filled from the single file foreach (string s in names) { - Match m = _match.Match(s); + m = _match_old.Match(s); if (m.Success) { int version = int.Parse(m.Groups[1].ToString()); - if (version > after) + if ( (version > after) && !migrations.ContainsKey(version) ) { using (Stream resource = _assem.GetManifestResourceStream(s)) { using (StreamReader resourceReader = new StreamReader(resource)) { - string resourceString = resourceReader.ReadToEnd(); - migrations.Add(version, resourceString); + string sql = resourceReader.ReadToEnd(); + migrations.Add(version, new string[]{sql}); } } } } } - - if (migrations.Count < 1) { + + if (migrations.Count < 1) + { m_log.InfoFormat("[MIGRATIONS]: {0} up to date, no migrations to apply", _type); } return migrations; diff --git a/OpenSim/Data/MySQL/MySQLAssetData.cs b/OpenSim/Data/MySQL/MySQLAssetData.cs index d55369a946..fe5152ad85 100644 --- a/OpenSim/Data/MySQL/MySQLAssetData.cs +++ b/OpenSim/Data/MySQL/MySQLAssetData.cs @@ -33,6 +33,7 @@ using log4net; using MySql.Data.MySqlClient; using OpenMetaverse; using OpenSim.Framework; +using OpenSim.Data; namespace OpenSim.Data.MySQL { @@ -111,7 +112,7 @@ namespace OpenSim.Data.MySQL dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand( - "SELECT name, description, assetType, local, temporary, data FROM assets WHERE id=?id", + "SELECT name, description, assetType, local, temporary, asset_flags, CreatorID, data FROM assets WHERE id=?id", dbcon)) { cmd.Parameters.AddWithValue("?id", assetID.ToString()); @@ -122,7 +123,7 @@ namespace OpenSim.Data.MySQL { if (dbReader.Read()) { - asset = new AssetBase(assetID, (string)dbReader["name"], (sbyte)dbReader["assetType"], UUID.Zero.ToString()); + asset = new AssetBase(assetID, (string)dbReader["name"], (sbyte)dbReader["assetType"], dbReader["CreatorID"].ToString()); asset.Data = (byte[])dbReader["data"]; asset.Description = (string)dbReader["description"]; @@ -133,6 +134,7 @@ namespace OpenSim.Data.MySQL asset.Local = false; asset.Temporary = Convert.ToBoolean(dbReader["temporary"]); + asset.Flags = (AssetFlags)Convert.ToInt32(dbReader["asset_flags"]); } } } @@ -161,8 +163,8 @@ namespace OpenSim.Data.MySQL MySqlCommand cmd = new MySqlCommand( - "replace INTO assets(id, name, description, assetType, local, temporary, create_time, access_time, data)" + - "VALUES(?id, ?name, ?description, ?assetType, ?local, ?temporary, ?create_time, ?access_time, ?data)", + "replace INTO assets(id, name, description, assetType, local, temporary, create_time, access_time, asset_flags, CreatorID, data)" + + "VALUES(?id, ?name, ?description, ?assetType, ?local, ?temporary, ?create_time, ?access_time, ?asset_flags, ?CreatorID, ?data)", dbcon); string assetName = asset.Name; @@ -194,6 +196,8 @@ namespace OpenSim.Data.MySQL cmd.Parameters.AddWithValue("?temporary", asset.Temporary); cmd.Parameters.AddWithValue("?create_time", now); cmd.Parameters.AddWithValue("?access_time", now); + cmd.Parameters.AddWithValue("?CreatorID", asset.Metadata.CreatorID); + cmd.Parameters.AddWithValue("?asset_flags", (int)asset.Flags); cmd.Parameters.AddWithValue("?data", asset.Data); cmd.ExecuteNonQuery(); cmd.Dispose(); @@ -302,7 +306,7 @@ namespace OpenSim.Data.MySQL using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); - MySqlCommand cmd = new MySqlCommand("SELECT name,description,assetType,temporary,id FROM assets LIMIT ?start, ?count", dbcon); + MySqlCommand cmd = new MySqlCommand("SELECT name,description,assetType,temporary,id,asset_flags,CreatorID FROM assets LIMIT ?start, ?count", dbcon); cmd.Parameters.AddWithValue("?start", start); cmd.Parameters.AddWithValue("?count", count); @@ -317,7 +321,9 @@ namespace OpenSim.Data.MySQL metadata.Description = (string)dbReader["description"]; metadata.Type = (sbyte)dbReader["assetType"]; metadata.Temporary = Convert.ToBoolean(dbReader["temporary"]); // Not sure if this is correct. - metadata.FullID = new UUID((string)dbReader["id"]); + metadata.Flags = (AssetFlags)Convert.ToInt32(dbReader["asset_flags"]); + metadata.FullID = DBGuid.FromDB(dbReader["id"]); + metadata.CreatorID = dbReader["CreatorID"].ToString(); // Current SHA1s are not stored/computed. metadata.SHA1 = new byte[] { }; @@ -336,6 +342,24 @@ namespace OpenSim.Data.MySQL return retList; } + public override bool Delete(string id) + { + lock (m_dbLock) + { + using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) + { + dbcon.Open(); + MySqlCommand cmd = new MySqlCommand("delete from assets where id=?id", dbcon); + cmd.Parameters.AddWithValue("?id", id); + cmd.ExecuteNonQuery(); + + cmd.Dispose(); + } + } + + return true; + } + #endregion } } diff --git a/OpenSim/Data/MySQL/MySQLEstateData.cs b/OpenSim/Data/MySQL/MySQLEstateData.cs index d0c02f0647..9158f7a427 100644 --- a/OpenSim/Data/MySQL/MySQLEstateData.cs +++ b/OpenSim/Data/MySQL/MySQLEstateData.cs @@ -34,6 +34,7 @@ using MySql.Data.MySqlClient; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; +using OpenSim.Data; namespace OpenSim.Data.MySQL { @@ -156,20 +157,13 @@ namespace OpenSim.Data.MySQL foreach (string name in FieldList) { - if (m_FieldMap[name].GetValue(es) is bool) + if (m_FieldMap[name].FieldType == typeof(bool)) { - int v = Convert.ToInt32(r[name]); - if (v != 0) - m_FieldMap[name].SetValue(es, true); - else - m_FieldMap[name].SetValue(es, false); + m_FieldMap[name].SetValue(es, Convert.ToInt32(r[name]) != 0); } - else if (m_FieldMap[name].GetValue(es) is UUID) + else if (m_FieldMap[name].FieldType == typeof(UUID)) { - UUID uuid = UUID.Zero; - - UUID.TryParse(r[name].ToString(), out uuid); - m_FieldMap[name].SetValue(es, uuid); + m_FieldMap[name].SetValue(es, DBGuid.FromDB(r[name])); } else { @@ -385,11 +379,7 @@ namespace OpenSim.Data.MySQL while (r.Read()) { // EstateBan eb = new EstateBan(); - - UUID uuid = new UUID(); - UUID.TryParse(r["uuid"].ToString(), out uuid); - - uuids.Add(uuid); + uuids.Add(DBGuid.FromDB(r["uuid"])); } } } @@ -474,7 +464,36 @@ namespace OpenSim.Data.MySQL public List GetRegions(int estateID) { - return new List(); + List result = new List(); + + using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) + { + dbcon.Open(); + + try + { + using (MySqlCommand cmd = dbcon.CreateCommand()) + { + cmd.CommandText = "select RegionID from estate_map where EstateID = ?EstateID"; + cmd.Parameters.AddWithValue("?EstateID", estateID.ToString()); + + using (IDataReader reader = cmd.ExecuteReader()) + { + while(reader.Read()) + result.Add(DBGuid.FromDB(reader["RegionID"])); + reader.Close(); + } + } + } + catch (Exception e) + { + m_log.Error("[REGION DB]: Error reading estate map. " + e.ToString()); + return result; + } + dbcon.Close(); + } + + return result; } public bool DeleteEstate(int estateID) diff --git a/OpenSim/Data/MySQL/MySQLGenericTableHandler.cs b/OpenSim/Data/MySQL/MySQLGenericTableHandler.cs index 1253e0b455..6cbb2ee9a2 100644 --- a/OpenSim/Data/MySQL/MySQLGenericTableHandler.cs +++ b/OpenSim/Data/MySQL/MySQLGenericTableHandler.cs @@ -148,19 +148,16 @@ namespace OpenSim.Data.MySQL foreach (string name in m_Fields.Keys) { - if (m_Fields[name].GetValue(row) is bool) + if (m_Fields[name].FieldType == typeof(bool)) { int v = Convert.ToInt32(reader[name]); m_Fields[name].SetValue(row, v != 0 ? true : false); } - else if (m_Fields[name].GetValue(row) is UUID) + else if (m_Fields[name].FieldType == typeof(UUID)) { - UUID uuid = UUID.Zero; - - UUID.TryParse(reader[name].ToString(), out uuid); - m_Fields[name].SetValue(row, uuid); + m_Fields[name].SetValue(row, DBGuid.FromDB(reader[name])); } - else if (m_Fields[name].GetValue(row) is int) + else if (m_Fields[name].FieldType == typeof(int)) { int v = Convert.ToInt32(reader[name]); m_Fields[name].SetValue(row, v); diff --git a/OpenSim/Data/MySQL/MySQLGridUserData.cs b/OpenSim/Data/MySQL/MySQLGridUserData.cs index df29ecdc2d..a9ce94d33c 100644 --- a/OpenSim/Data/MySQL/MySQLGridUserData.cs +++ b/OpenSim/Data/MySQL/MySQLGridUserData.cs @@ -44,9 +44,9 @@ namespace OpenSim.Data.MySQL { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - public MySQLGridUserData(string connectionString, string realm) : base(connectionString, realm, "UserGrid") {} + public MySQLGridUserData(string connectionString, string realm) : base(connectionString, realm, "GridUserStore") {} - public GridUserData GetGridUserData(string userID) + public GridUserData Get(string userID) { GridUserData[] ret = Get("UserID", userID); @@ -56,9 +56,6 @@ namespace OpenSim.Data.MySQL return ret[0]; } - public bool StoreGridUserData(GridUserData data) - { - return Store(data); - } + } } \ No newline at end of file diff --git a/OpenSim/Data/MySQL/MySQLInventoryData.cs b/OpenSim/Data/MySQL/MySQLInventoryData.cs index 192deb298a..0aea30ffb9 100644 --- a/OpenSim/Data/MySQL/MySQLInventoryData.cs +++ b/OpenSim/Data/MySQL/MySQLInventoryData.cs @@ -32,6 +32,7 @@ using log4net; using MySql.Data.MySqlClient; using OpenMetaverse; using OpenSim.Framework; +using OpenSim.Data; namespace OpenSim.Data.MySQL { @@ -145,7 +146,7 @@ namespace OpenSim.Data.MySQL /// /// Returns a list of the root folders within a users inventory /// - /// The user whos inventory is to be searched + /// The user whose inventory is to be searched /// A list of folder objects public List getUserRootFolders(UUID user) { @@ -284,32 +285,24 @@ namespace OpenSim.Data.MySQL { InventoryItemBase item = new InventoryItemBase(); - // TODO: this is to handle a case where NULLs creep in there, which we are not sure is indemic to the system, or legacy. It would be nice to live fix these. - if (reader["creatorID"] == null) - { - item.CreatorId = UUID.Zero.ToString(); - } - else - { - item.CreatorId = (string)reader["creatorID"]; - } + // TODO: this is to handle a case where NULLs creep in there, which we are not sure is endemic to the system, or legacy. It would be nice to live fix these. + // ( DBGuid.FromDB() reads db NULLs as well, returns UUID.Zero ) + item.CreatorId = reader["creatorID"].ToString(); // Be a bit safer in parsing these because the // database doesn't enforce them to be not null, and // the inventory still works if these are weird in the // db - UUID Owner = UUID.Zero; - UUID GroupID = UUID.Zero; - UUID.TryParse((string)reader["avatarID"], out Owner); - UUID.TryParse((string)reader["groupID"], out GroupID); - item.Owner = Owner; - item.GroupID = GroupID; + + // (Empty is Ok, but "weird" will throw!) + item.Owner = DBGuid.FromDB(reader["avatarID"]); + item.GroupID = DBGuid.FromDB(reader["groupID"]); // Rest of the parsing. If these UUID's fail, we're dead anyway - item.ID = new UUID((string) reader["inventoryID"]); - item.AssetID = new UUID((string) reader["assetID"]); + item.ID = DBGuid.FromDB(reader["inventoryID"]); + item.AssetID = DBGuid.FromDB(reader["assetID"]); item.AssetType = (int) reader["assetType"]; - item.Folder = new UUID((string) reader["parentFolderID"]); + item.Folder = DBGuid.FromDB(reader["parentFolderID"]); item.Name = (string)(reader["inventoryName"] ?? String.Empty); item.Description = (string)(reader["inventoryDescription"] ?? String.Empty); item.NextPermissions = (uint) reader["inventoryNextPermissions"]; @@ -382,9 +375,9 @@ namespace OpenSim.Data.MySQL try { InventoryFolderBase folder = new InventoryFolderBase(); - folder.Owner = new UUID((string) reader["agentID"]); - folder.ParentID = new UUID((string) reader["parentFolderID"]); - folder.ID = new UUID((string) reader["folderID"]); + folder.Owner = DBGuid.FromDB(reader["agentID"]); + folder.ParentID = DBGuid.FromDB(reader["parentFolderID"]); + folder.ID = DBGuid.FromDB(reader["folderID"]); folder.Name = (string) reader["folderName"]; folder.Type = (short) reader["type"]; folder.Version = (ushort) ((int) reader["version"]); diff --git a/OpenSim/Data/MySQL/MySQLLegacyRegionData.cs b/OpenSim/Data/MySQL/MySQLLegacyRegionData.cs index a395ddc3e7..bfeae12385 100644 --- a/OpenSim/Data/MySQL/MySQLLegacyRegionData.cs +++ b/OpenSim/Data/MySQL/MySQLLegacyRegionData.cs @@ -38,6 +38,7 @@ using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; +using OpenSim.Data; namespace OpenSim.Data.MySQL { @@ -269,7 +270,7 @@ namespace OpenSim.Data.MySQL using (IDataReader reader = ExecuteReader(cmd)) { while (reader.Read()) - uuids.Add(new UUID(reader["UUID"].ToString())); + uuids.Add(DBGuid.FromDB(reader["UUID"].ToString())); } // delete the main prims @@ -422,7 +423,7 @@ namespace OpenSim.Data.MySQL else prim.Shape = BuildShape(reader); - UUID parentID = new UUID(reader["SceneGroupID"].ToString()); + UUID parentID = DBGuid.FromDB(reader["SceneGroupID"].ToString()); if (parentID != prim.UUID) prim.ParentUUID = parentID; @@ -500,7 +501,7 @@ namespace OpenSim.Data.MySQL { if (!(itemReader["primID"] is DBNull)) { - UUID primID = new UUID(itemReader["primID"].ToString()); + UUID primID = DBGuid.FromDB(itemReader["primID"].ToString()); if (prims.ContainsKey(primID)) primsWithInventory.Add(prims[primID]); } @@ -738,7 +739,7 @@ namespace OpenSim.Data.MySQL } else { - UUID.TryParse(result["region_id"].ToString(), out nWP.regionID); + nWP.regionID = DBGuid.FromDB(result["region_id"]); nWP.waterColor.X = Convert.ToSingle(result["water_color_r"]); nWP.waterColor.Y = Convert.ToSingle(result["water_color_g"]); nWP.waterColor.Z = Convert.ToSingle(result["water_color_b"]); @@ -975,7 +976,7 @@ namespace OpenSim.Data.MySQL "use_estate_sun, fixed_sun, sun_position, " + "covenant, Sandbox, sunvectorx, sunvectory, " + "sunvectorz, loaded_creation_datetime, " + - "loaded_creation_id) values (?RegionUUID, ?BlockTerraform, " + + "loaded_creation_id, map_tile_ID) values (?RegionUUID, ?BlockTerraform, " + "?BlockFly, ?AllowDamage, ?RestrictPushing, " + "?AllowLandResell, ?AllowLandJoinDivide, " + "?BlockShowInSearch, ?AgentLimit, ?ObjectBonus, " + @@ -989,7 +990,8 @@ namespace OpenSim.Data.MySQL "?TerrainLowerLimit, ?UseEstateSun, ?FixedSun, " + "?SunPosition, ?Covenant, ?Sandbox, " + "?SunVectorX, ?SunVectorY, ?SunVectorZ, " + - "?LoadedCreationDateTime, ?LoadedCreationID)"; + "?LoadedCreationDateTime, ?LoadedCreationID, " + + "?TerrainImageID)"; FillRegionSettingsCommand(cmd, rs); @@ -1054,7 +1056,14 @@ namespace OpenSim.Data.MySQL private SceneObjectPart BuildPrim(IDataReader row) { SceneObjectPart prim = new SceneObjectPart(); - prim.UUID = new UUID((string)row["UUID"]); + + // depending on the MySQL connector version, CHAR(36) may be already converted to Guid! + prim.UUID = DBGuid.FromDB(row["UUID"]); + prim.CreatorID = DBGuid.FromDB(row["CreatorID"]); + prim.OwnerID = DBGuid.FromDB(row["OwnerID"]); + prim.GroupID = DBGuid.FromDB(row["GroupID"]); + prim.LastOwnerID = DBGuid.FromDB(row["LastOwnerID"]); + // explicit conversion of integers is required, which sort // of sucks. No idea if there is a shortcut here or not. prim.CreationDate = (int)row["CreationDate"]; @@ -1073,15 +1082,12 @@ namespace OpenSim.Data.MySQL prim.TouchName = (string)row["TouchName"]; // Permissions prim.ObjectFlags = (uint)(int)row["ObjectFlags"]; - prim.CreatorID = new UUID((string)row["CreatorID"]); - prim.OwnerID = new UUID((string)row["OwnerID"]); - prim.GroupID = new UUID((string)row["GroupID"]); - prim.LastOwnerID = new UUID((string)row["LastOwnerID"]); prim.OwnerMask = (uint)(int)row["OwnerMask"]; prim.NextOwnerMask = (uint)(int)row["NextOwnerMask"]; prim.GroupMask = (uint)(int)row["GroupMask"]; prim.EveryoneMask = (uint)(int)row["EveryoneMask"]; prim.BaseMask = (uint)(int)row["BaseMask"]; + // Vectors prim.OffsetPosition = new Vector3( (float)(double)row["PositionX"], @@ -1133,7 +1139,7 @@ namespace OpenSim.Data.MySQL prim.PayPrice[3] = (int)row["PayButton3"]; prim.PayPrice[4] = (int)row["PayButton4"]; - prim.Sound = new UUID(row["LoopedSound"].ToString()); + prim.Sound = DBGuid.FromDB(row["LoopedSound"].ToString()); prim.SoundGain = (float)(double)row["LoopedSoundGain"]; prim.SoundFlags = 1; // If it's persisted at all, it's looped @@ -1160,16 +1166,10 @@ namespace OpenSim.Data.MySQL (float)(double)row["CameraAtOffsetZ"] )); - if ((sbyte)row["ForceMouselook"] != 0) - prim.SetForceMouselook(true); - + prim.SetForceMouselook((sbyte)row["ForceMouselook"] != 0); prim.ScriptAccessPin = (int)row["ScriptAccessPin"]; - - if ((sbyte)row["AllowedDrop"] != 0) - prim.AllowedDrop = true; - - if ((sbyte)row["DieAtEdge"] != 0) - prim.DIE_AT_EDGE = true; + prim.AllowedDrop = ((sbyte)row["AllowedDrop"] != 0); + prim.DIE_AT_EDGE = ((sbyte)row["DieAtEdge"] != 0); prim.SalePrice = (int)row["SalePrice"]; prim.ObjectSaleType = unchecked((byte)(sbyte)row["SaleType"]); @@ -1179,11 +1179,10 @@ namespace OpenSim.Data.MySQL if (!(row["ClickAction"] is DBNull)) prim.ClickAction = unchecked((byte)(sbyte)row["ClickAction"]); - prim.CollisionSound = new UUID(row["CollisionSound"].ToString()); + prim.CollisionSound = DBGuid.FromDB(row["CollisionSound"]); prim.CollisionSoundVolume = (float)(double)row["CollisionSoundVolume"]; - if ((sbyte)row["PassTouches"] != 0) - prim.PassTouches = true; + prim.PassTouches = ((sbyte)row["PassTouches"] != 0); prim.LinkNum = (int)row["LinkNumber"]; return prim; @@ -1199,10 +1198,10 @@ namespace OpenSim.Data.MySQL { TaskInventoryItem taskItem = new TaskInventoryItem(); - taskItem.ItemID = new UUID((String)row["itemID"]); - taskItem.ParentPartID = new UUID((String)row["primID"]); - taskItem.AssetID = new UUID((String)row["assetID"]); - taskItem.ParentID = new UUID((String)row["parentFolderID"]); + taskItem.ItemID = DBGuid.FromDB(row["itemID"]); + taskItem.ParentPartID = DBGuid.FromDB(row["primID"]); + taskItem.AssetID = DBGuid.FromDB(row["assetID"]); + taskItem.ParentID = DBGuid.FromDB(row["parentFolderID"]); taskItem.InvType = Convert.ToInt32(row["invType"]); taskItem.Type = Convert.ToInt32(row["assetType"]); @@ -1210,10 +1209,10 @@ namespace OpenSim.Data.MySQL taskItem.Name = (String)row["name"]; taskItem.Description = (String)row["description"]; taskItem.CreationDate = Convert.ToUInt32(row["creationDate"]); - taskItem.CreatorID = new UUID((String)row["creatorID"]); - taskItem.OwnerID = new UUID((String)row["ownerID"]); - taskItem.LastOwnerID = new UUID((String)row["lastOwnerID"]); - taskItem.GroupID = new UUID((String)row["groupID"]); + taskItem.CreatorID = DBGuid.FromDB(row["creatorID"]); + taskItem.OwnerID = DBGuid.FromDB(row["ownerID"]); + taskItem.LastOwnerID = DBGuid.FromDB(row["lastOwnerID"]); + taskItem.GroupID = DBGuid.FromDB(row["groupID"]); taskItem.NextPermissions = Convert.ToUInt32(row["nextPermissions"]); taskItem.CurrentPermissions = Convert.ToUInt32(row["currentPermissions"]); @@ -1229,7 +1228,7 @@ namespace OpenSim.Data.MySQL { RegionSettings newSettings = new RegionSettings(); - newSettings.RegionUUID = new UUID((string) row["regionUUID"]); + newSettings.RegionUUID = DBGuid.FromDB(row["regionUUID"]); newSettings.BlockTerraform = Convert.ToBoolean(row["block_terraform"]); newSettings.AllowDamage = Convert.ToBoolean(row["allow_damage"]); newSettings.BlockFly = Convert.ToBoolean(row["block_fly"]); @@ -1243,10 +1242,10 @@ namespace OpenSim.Data.MySQL newSettings.DisableScripts = Convert.ToBoolean(row["disable_scripts"]); newSettings.DisableCollisions = Convert.ToBoolean(row["disable_collisions"]); newSettings.DisablePhysics = Convert.ToBoolean(row["disable_physics"]); - newSettings.TerrainTexture1 = new UUID((String) row["terrain_texture_1"]); - newSettings.TerrainTexture2 = new UUID((String) row["terrain_texture_2"]); - newSettings.TerrainTexture3 = new UUID((String) row["terrain_texture_3"]); - newSettings.TerrainTexture4 = new UUID((String) row["terrain_texture_4"]); + newSettings.TerrainTexture1 = DBGuid.FromDB(row["terrain_texture_1"]); + newSettings.TerrainTexture2 = DBGuid.FromDB(row["terrain_texture_2"]); + newSettings.TerrainTexture3 = DBGuid.FromDB(row["terrain_texture_3"]); + newSettings.TerrainTexture4 = DBGuid.FromDB(row["terrain_texture_4"]); newSettings.Elevation1NW = Convert.ToDouble(row["elevation_1_nw"]); newSettings.Elevation2NW = Convert.ToDouble(row["elevation_2_nw"]); newSettings.Elevation1NE = Convert.ToDouble(row["elevation_1_ne"]); @@ -1267,7 +1266,7 @@ namespace OpenSim.Data.MySQL ); newSettings.FixedSun = Convert.ToBoolean(row["fixed_sun"]); newSettings.SunPosition = Convert.ToDouble(row["sun_position"]); - newSettings.Covenant = new UUID((String) row["covenant"]); + newSettings.Covenant = DBGuid.FromDB(row["covenant"]); newSettings.LoadedCreationDateTime = Convert.ToInt32(row["loaded_creation_datetime"]); @@ -1276,6 +1275,8 @@ namespace OpenSim.Data.MySQL else newSettings.LoadedCreationID = (String) row["loaded_creation_id"]; + newSettings.TerrainImageID = DBGuid.FromDB(row["map_tile_ID"]); + return newSettings; } @@ -1288,7 +1289,7 @@ namespace OpenSim.Data.MySQL { LandData newData = new LandData(); - newData.GlobalID = new UUID((String) row["UUID"]); + newData.GlobalID = DBGuid.FromDB(row["UUID"]); newData.LocalID = Convert.ToInt32(row["LocalLandID"]); // Bitmap is a byte[512] @@ -1296,7 +1297,7 @@ namespace OpenSim.Data.MySQL newData.Name = (String) row["Name"]; newData.Description = (String) row["Description"]; - newData.OwnerID = new UUID((String)row["OwnerUUID"]); + newData.OwnerID = DBGuid.FromDB(row["OwnerUUID"]); newData.IsGroupOwned = Convert.ToBoolean(row["IsGroupOwned"]); newData.Area = Convert.ToInt32(row["Area"]); newData.AuctionID = Convert.ToUInt32(row["AuctionID"]); //Unimplemented @@ -1304,14 +1305,14 @@ namespace OpenSim.Data.MySQL //Enum libsecondlife.Parcel.ParcelCategory newData.ClaimDate = Convert.ToInt32(row["ClaimDate"]); newData.ClaimPrice = Convert.ToInt32(row["ClaimPrice"]); - newData.GroupID = new UUID((String) row["GroupUUID"]); + newData.GroupID = DBGuid.FromDB(row["GroupUUID"]); newData.SalePrice = Convert.ToInt32(row["SalePrice"]); newData.Status = (ParcelStatus) Convert.ToInt32(row["LandStatus"]); //Enum. libsecondlife.Parcel.ParcelStatus newData.Flags = Convert.ToUInt32(row["LandFlags"]); newData.LandingType = Convert.ToByte(row["LandingType"]); newData.MediaAutoScale = Convert.ToByte(row["MediaAutoScale"]); - newData.MediaID = new UUID((String) row["MediaTextureUUID"]); + newData.MediaID = DBGuid.FromDB(row["MediaTextureUUID"]); newData.MediaURL = (String) row["MediaURL"]; newData.MusicURL = (String) row["MusicURL"]; newData.PassHours = Convert.ToSingle(row["PassHours"]); @@ -1355,7 +1356,7 @@ namespace OpenSim.Data.MySQL private static ParcelManager.ParcelAccessEntry BuildLandAccessData(IDataReader row) { ParcelManager.ParcelAccessEntry entry = new ParcelManager.ParcelAccessEntry(); - entry.AgentID = new UUID((string) row["AccessUUID"]); + entry.AgentID = DBGuid.FromDB(row["AccessUUID"]); entry.Flags = (AccessList) Convert.ToInt32(row["Flags"]); entry.Time = new DateTime(); return entry; @@ -1596,6 +1597,7 @@ namespace OpenSim.Data.MySQL cmd.Parameters.AddWithValue("Covenant", settings.Covenant.ToString()); cmd.Parameters.AddWithValue("LoadedCreationDateTime", settings.LoadedCreationDateTime); cmd.Parameters.AddWithValue("LoadedCreationID", settings.LoadedCreationID); + cmd.Parameters.AddWithValue("TerrainImageID", settings.TerrainImageID); } diff --git a/OpenSim/Data/MySQL/MySQLMigrations.cs b/OpenSim/Data/MySQL/MySQLMigrations.cs new file mode 100644 index 0000000000..81a0e837ea --- /dev/null +++ b/OpenSim/Data/MySQL/MySQLMigrations.cs @@ -0,0 +1,83 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.IO; +using System.Reflection; +using System.Text.RegularExpressions; +using log4net; +using MySql.Data.MySqlClient; + +namespace OpenSim.Data.MySQL +{ + /// This is a MySQL-customized migration processor. The only difference is in how + /// it executes SQL scripts (using MySqlScript instead of MyCommand) + /// + /// + public class MySqlMigration : Migration + { + public MySqlMigration() + : base() + { + } + + public MySqlMigration(DbConnection conn, Assembly assem, string subtype, string type) : + base(conn, assem, subtype, type) + { + } + + public MySqlMigration(DbConnection conn, Assembly assem, string type) : + base(conn, assem, type) + { + } + + protected override void ExecuteScript(DbConnection conn, string[] script) + { + if (!(conn is MySqlConnection)) + { + base.ExecuteScript(conn, script); + return; + } + + MySqlScript scr = new MySqlScript((MySqlConnection)conn); + { + foreach (string sql in script) + { + scr.Query = sql; + scr.Error += delegate(object sender, MySqlScriptErrorEventArgs args) + { + throw new Exception(sql); + }; + scr.Execute(); + } + } + } + } +} diff --git a/OpenSim/Data/MySQL/MySQLPresenceData.cs b/OpenSim/Data/MySQL/MySQLPresenceData.cs index 143dbe38cb..71caa1aa2a 100644 --- a/OpenSim/Data/MySQL/MySQLPresenceData.cs +++ b/OpenSim/Data/MySQL/MySQLPresenceData.cs @@ -65,15 +65,14 @@ namespace OpenSim.Data.MySQL { MySqlCommand cmd = new MySqlCommand(); - cmd.CommandText = String.Format("update {0} set Online='false' where `RegionID`=?RegionID", m_Realm); + cmd.CommandText = String.Format("delete from {0} where `RegionID`=?RegionID", m_Realm); cmd.Parameters.AddWithValue("?RegionID", regionID.ToString()); ExecuteNonQuery(cmd); } - public bool ReportAgent(UUID sessionID, UUID regionID, string position, - string lookAt) + public bool ReportAgent(UUID sessionID, UUID regionID) { PresenceData[] pd = Get("SessionID", sessionID.ToString()); if (pd.Length == 0) @@ -81,12 +80,10 @@ namespace OpenSim.Data.MySQL MySqlCommand cmd = new MySqlCommand(); - cmd.CommandText = String.Format("update {0} set RegionID=?RegionID, Position=?Position, LookAt=?LookAt, Online='true' where `SessionID`=?SessionID", m_Realm); + cmd.CommandText = String.Format("update {0} set RegionID=?RegionID where `SessionID`=?SessionID", m_Realm); cmd.Parameters.AddWithValue("?SessionID", sessionID.ToString()); cmd.Parameters.AddWithValue("?RegionID", regionID.ToString()); - cmd.Parameters.AddWithValue("?Position", position.ToString()); - cmd.Parameters.AddWithValue("?LookAt", lookAt.ToString()); if (ExecuteNonQuery(cmd) == 0) return false; @@ -94,62 +91,5 @@ namespace OpenSim.Data.MySQL return true; } - public bool SetHomeLocation(string userID, UUID regionID, Vector3 position, Vector3 lookAt) - { - PresenceData[] pd = Get("UserID", userID); - if (pd.Length == 0) - return false; - - MySqlCommand cmd = new MySqlCommand(); - - cmd.CommandText = String.Format("update {0} set HomeRegionID=?HomeRegionID, HomePosition=?HomePosition, HomeLookAt=?HomeLookAt where UserID=?UserID", m_Realm); - - cmd.Parameters.AddWithValue("?UserID", userID); - cmd.Parameters.AddWithValue("?HomeRegionID", regionID.ToString()); - cmd.Parameters.AddWithValue("?HomePosition", position); - cmd.Parameters.AddWithValue("?HomeLookAt", lookAt); - - if (ExecuteNonQuery(cmd) == 0) - return false; - - return true; - } - - public void Prune(string userID) - { - MySqlCommand cmd = new MySqlCommand(); - - cmd.CommandText = String.Format("select * from {0} where UserID=?UserID", m_Realm); - - cmd.Parameters.AddWithValue("?UserID", userID); - - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - cmd.Connection = dbcon; - - using (IDataReader reader = cmd.ExecuteReader()) - { - List deleteSessions = new List(); - int online = 0; - - while (reader.Read()) - { - if (bool.Parse(reader["Online"].ToString())) - online++; - else - deleteSessions.Add(new UUID(reader["SessionID"].ToString())); - } - - // Leave one session behind so that we can pick up details such as home location - if (online == 0 && deleteSessions.Count > 0) - deleteSessions.RemoveAt(0); - - foreach (UUID s in deleteSessions) - Delete("SessionID", s.ToString()); - } - } - } } } diff --git a/OpenSim/Data/MySQL/MySQLRegionData.cs b/OpenSim/Data/MySQL/MySQLRegionData.cs index aa9a104d78..c7bddacd16 100644 --- a/OpenSim/Data/MySQL/MySQLRegionData.cs +++ b/OpenSim/Data/MySQL/MySQLRegionData.cs @@ -31,6 +31,7 @@ using System.Collections.Generic; using System.Data; using OpenMetaverse; using OpenSim.Framework; +using OpenSim.Data; using MySql.Data.MySqlClient; namespace OpenSim.Data.MySQL @@ -143,12 +144,9 @@ namespace OpenSim.Data.MySQL RegionData ret = new RegionData(); ret.Data = new Dictionary(); - UUID regionID; - UUID.TryParse(result["uuid"].ToString(), out regionID); - ret.RegionID = regionID; - UUID scope; - UUID.TryParse(result["ScopeID"].ToString(), out scope); - ret.ScopeID = scope; + ret.RegionID = DBGuid.FromDB(result["uuid"]); + ret.ScopeID = DBGuid.FromDB(result["ScopeID"]); + ret.RegionName = result["regionName"].ToString(); ret.posX = Convert.ToInt32(result["locX"]); ret.posY = Convert.ToInt32(result["locY"]); diff --git a/OpenSim/Data/MySQL/MySQLXInventoryData.cs b/OpenSim/Data/MySQL/MySQLXInventoryData.cs index 307a4c7cab..0fe801d696 100644 --- a/OpenSim/Data/MySQL/MySQLXInventoryData.cs +++ b/OpenSim/Data/MySQL/MySQLXInventoryData.cs @@ -160,5 +160,36 @@ namespace OpenSim.Data.MySQL } } } + + public override bool Store(XInventoryItem item) + { + if (!base.Store(item)) + return false; + + using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) + { + dbcon.Open(); + + using (MySqlCommand cmd = new MySqlCommand()) + { + cmd.Connection = dbcon; + + cmd.CommandText = String.Format("update inventoryfolders set version=version+1 where folderID = ?folderID"); + cmd.Parameters.AddWithValue("?folderID", item.parentFolderID.ToString()); + + try + { + cmd.ExecuteNonQuery(); + } + catch (Exception e) + { + return false; + } + cmd.Dispose(); + } + dbcon.Close(); + } + return true; + } } } diff --git a/OpenSim/Data/MySQL/Resources/001_AssetStore.sql b/OpenSim/Data/MySQL/Resources/001_AssetStore.sql deleted file mode 100644 index 6a9a127b8f..0000000000 --- a/OpenSim/Data/MySQL/Resources/001_AssetStore.sql +++ /dev/null @@ -1,15 +0,0 @@ -BEGIN; - -CREATE TABLE `assets` ( - `id` binary(16) NOT NULL, - `name` varchar(64) NOT NULL, - `description` varchar(64) NOT NULL, - `assetType` tinyint(4) NOT NULL, - `invType` tinyint(4) NOT NULL, - `local` tinyint(1) NOT NULL, - `temporary` tinyint(1) NOT NULL, - `data` longblob NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Rev. 1'; - -COMMIT; \ No newline at end of file diff --git a/OpenSim/Data/MySQL/Resources/001_Avatar.sql b/OpenSim/Data/MySQL/Resources/001_Avatar.sql deleted file mode 100644 index 27a307244b..0000000000 --- a/OpenSim/Data/MySQL/Resources/001_Avatar.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN; - -CREATE TABLE Avatars (PrincipalID CHAR(36) NOT NULL, Name VARCHAR(32) NOT NULL, Value VARCHAR(255) NOT NULL DEFAULT '', PRIMARY KEY(PrincipalID, Name), KEY(PrincipalID)); - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/001_Friends.sql b/OpenSim/Data/MySQL/Resources/001_Friends.sql deleted file mode 100644 index e158a2c802..0000000000 --- a/OpenSim/Data/MySQL/Resources/001_Friends.sql +++ /dev/null @@ -1,9 +0,0 @@ -BEGIN; - -CREATE TABLE `Friends` ( - `PrincipalID` CHAR(36) NOT NULL, - `FriendID` VARCHAR(255) NOT NULL, - `Flags` CHAR(16) NOT NULL DEFAULT '0' -) ENGINE=InnoDB; - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/001_FriendsStore.sql b/OpenSim/Data/MySQL/Resources/001_FriendsStore.sql deleted file mode 100644 index da2c59c6d0..0000000000 --- a/OpenSim/Data/MySQL/Resources/001_FriendsStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN; - -CREATE TABLE `Friends` (`PrincipalID` CHAR(36) NOT NULL, `Friend` VARCHAR(255) NOT NULL, `Flags` VARCHAR(16) NOT NULL DEFAULT 0, `Offered` VARCHAR(32) NOT NULL DEFAULT 0, PRIMARY KEY(`PrincipalID`, `Friend`), KEY(`PrincipalID`)); - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/001_InventoryStore.sql b/OpenSim/Data/MySQL/Resources/001_InventoryStore.sql deleted file mode 100644 index 40dc91cdc6..0000000000 --- a/OpenSim/Data/MySQL/Resources/001_InventoryStore.sql +++ /dev/null @@ -1,40 +0,0 @@ -BEGIN; - -CREATE TABLE `inventoryfolders` ( - `folderID` varchar(36) NOT NULL default '', - `agentID` varchar(36) default NULL, - `parentFolderID` varchar(36) default NULL, - `folderName` varchar(64) default NULL, - `type` smallint NOT NULL default 0, - `version` int NOT NULL default 0, - PRIMARY KEY (`folderID`), - KEY `owner` (`agentID`), - KEY `parent` (`parentFolderID`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - -CREATE TABLE `inventoryitems` ( - `inventoryID` varchar(36) NOT NULL default '', - `assetID` varchar(36) default NULL, - `assetType` int(11) default NULL, - `parentFolderID` varchar(36) default NULL, - `avatarID` varchar(36) default NULL, - `inventoryName` varchar(64) default NULL, - `inventoryDescription` varchar(128) default NULL, - `inventoryNextPermissions` int(10) unsigned default NULL, - `inventoryCurrentPermissions` int(10) unsigned default NULL, - `invType` int(11) default NULL, - `creatorID` varchar(36) default NULL, - `inventoryBasePermissions` int(10) unsigned NOT NULL default 0, - `inventoryEveryOnePermissions` int(10) unsigned NOT NULL default 0, - `salePrice` int(11) NOT NULL default 0, - `saleType` tinyint(4) NOT NULL default 0, - `creationDate` int(11) NOT NULL default 0, - `groupID` varchar(36) NOT NULL default '00000000-0000-0000-0000-000000000000', - `groupOwned` tinyint(4) NOT NULL default 0, - `flags` int(11) unsigned NOT NULL default 0, - PRIMARY KEY (`inventoryID`), - KEY `owner` (`avatarID`), - KEY `folder` (`parentFolderID`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - -COMMIT; \ No newline at end of file diff --git a/OpenSim/Data/MySQL/Resources/001_Presence.sql b/OpenSim/Data/MySQL/Resources/001_Presence.sql deleted file mode 100644 index b8abaf7dc7..0000000000 --- a/OpenSim/Data/MySQL/Resources/001_Presence.sql +++ /dev/null @@ -1,15 +0,0 @@ -BEGIN; - -CREATE TABLE `Presence` ( - `UserID` VARCHAR(255) NOT NULL, - `RegionID` CHAR(36) NOT NULL, - `SessionID` CHAR(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000', - `SecureSessionID` CHAR(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000', - `Online` CHAR(5) NOT NULL DEFAULT 'false', - `Login` CHAR(16) NOT NULL DEFAULT '0', - `Logout` CHAR(16) NOT NULL DEFAULT '0', - `Position` CHAR(64) NOT NULL DEFAULT '<0,0,0>', - `LookAt` CHAR(64) NOT NULL DEFAULT '<0,0,0>' -) ENGINE=InnoDB; - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/001_RegionStore.sql b/OpenSim/Data/MySQL/Resources/001_RegionStore.sql deleted file mode 100644 index 31164b35ed..0000000000 --- a/OpenSim/Data/MySQL/Resources/001_RegionStore.sql +++ /dev/null @@ -1,154 +0,0 @@ -BEGIN; - -CREATE TABLE `prims` ( - `UUID` varchar(255) NOT NULL, - `RegionUUID` varchar(255) default NULL, - `ParentID` int(11) default NULL, - `CreationDate` int(11) default NULL, - `Name` varchar(255) default NULL, - `SceneGroupID` varchar(255) default NULL, - `Text` varchar(255) default NULL, - `Description` varchar(255) default NULL, - `SitName` varchar(255) default NULL, - `TouchName` varchar(255) default NULL, - `ObjectFlags` int(11) default NULL, - `CreatorID` varchar(255) default NULL, - `OwnerID` varchar(255) default NULL, - `GroupID` varchar(255) default NULL, - `LastOwnerID` varchar(255) default NULL, - `OwnerMask` int(11) default NULL, - `NextOwnerMask` int(11) default NULL, - `GroupMask` int(11) default NULL, - `EveryoneMask` int(11) default NULL, - `BaseMask` int(11) default NULL, - `PositionX` float default NULL, - `PositionY` float default NULL, - `PositionZ` float default NULL, - `GroupPositionX` float default NULL, - `GroupPositionY` float default NULL, - `GroupPositionZ` float default NULL, - `VelocityX` float default NULL, - `VelocityY` float default NULL, - `VelocityZ` float default NULL, - `AngularVelocityX` float default NULL, - `AngularVelocityY` float default NULL, - `AngularVelocityZ` float default NULL, - `AccelerationX` float default NULL, - `AccelerationY` float default NULL, - `AccelerationZ` float default NULL, - `RotationX` float default NULL, - `RotationY` float default NULL, - `RotationZ` float default NULL, - `RotationW` float default NULL, - `SitTargetOffsetX` float default NULL, - `SitTargetOffsetY` float default NULL, - `SitTargetOffsetZ` float default NULL, - `SitTargetOrientW` float default NULL, - `SitTargetOrientX` float default NULL, - `SitTargetOrientY` float default NULL, - `SitTargetOrientZ` float default NULL, - PRIMARY KEY (`UUID`) -) ENGINE=MyISAM DEFAULT CHARSET=latin1; - -CREATE TABLE `primshapes` ( - `UUID` varchar(255) NOT NULL, - `Shape` int(11) default NULL, - `ScaleX` float default NULL, - `ScaleY` float default NULL, - `ScaleZ` float default NULL, - `PCode` int(11) default NULL, - `PathBegin` int(11) default NULL, - `PathEnd` int(11) default NULL, - `PathScaleX` int(11) default NULL, - `PathScaleY` int(11) default NULL, - `PathShearX` int(11) default NULL, - `PathShearY` int(11) default NULL, - `PathSkew` int(11) default NULL, - `PathCurve` int(11) default NULL, - `PathRadiusOffset` int(11) default NULL, - `PathRevolutions` int(11) default NULL, - `PathTaperX` int(11) default NULL, - `PathTaperY` int(11) default NULL, - `PathTwist` int(11) default NULL, - `PathTwistBegin` int(11) default NULL, - `ProfileBegin` int(11) default NULL, - `ProfileEnd` int(11) default NULL, - `ProfileCurve` int(11) default NULL, - `ProfileHollow` int(11) default NULL, - `State` int(11) default NULL, - `Texture` longblob, - `ExtraParams` longblob, - PRIMARY KEY (`UUID`) -) ENGINE=MyISAM DEFAULT CHARSET=latin1; - -CREATE TABLE `primitems` ( - `itemID` varchar(255) NOT NULL, - `primID` varchar(255) default NULL, - `assetID` varchar(255) default NULL, - `parentFolderID` varchar(255) default NULL, - `invType` int(11) default NULL, - `assetType` int(11) default NULL, - `name` varchar(255) default NULL, - `description` varchar(255) default NULL, - `creationDate` bigint(20) default NULL, - `creatorID` varchar(255) default NULL, - `ownerID` varchar(255) default NULL, - `lastOwnerID` varchar(255) default NULL, - `groupID` varchar(255) default NULL, - `nextPermissions` int(11) default NULL, - `currentPermissions` int(11) default NULL, - `basePermissions` int(11) default NULL, - `everyonePermissions` int(11) default NULL, - `groupPermissions` int(11) default NULL, - PRIMARY KEY (`itemID`) -) ENGINE=MyISAM DEFAULT CHARSET=latin1; - -CREATE TABLE `terrain` ( - `RegionUUID` varchar(255) default NULL, - `Revision` int(11) default NULL, - `Heightfield` longblob -) ENGINE=MyISAM DEFAULT CHARSET=latin1; - -CREATE TABLE `land` ( - `UUID` varchar(255) NOT NULL, - `RegionUUID` varchar(255) default NULL, - `LocalLandID` int(11) default NULL, - `Bitmap` longblob, - `Name` varchar(255) default NULL, - `Description` varchar(255) default NULL, - `OwnerUUID` varchar(255) default NULL, - `IsGroupOwned` int(11) default NULL, - `Area` int(11) default NULL, - `AuctionID` int(11) default NULL, - `Category` int(11) default NULL, - `ClaimDate` int(11) default NULL, - `ClaimPrice` int(11) default NULL, - `GroupUUID` varchar(255) default NULL, - `SalePrice` int(11) default NULL, - `LandStatus` int(11) default NULL, - `LandFlags` int(11) default NULL, - `LandingType` int(11) default NULL, - `MediaAutoScale` int(11) default NULL, - `MediaTextureUUID` varchar(255) default NULL, - `MediaURL` varchar(255) default NULL, - `MusicURL` varchar(255) default NULL, - `PassHours` float default NULL, - `PassPrice` int(11) default NULL, - `SnapshotUUID` varchar(255) default NULL, - `UserLocationX` float default NULL, - `UserLocationY` float default NULL, - `UserLocationZ` float default NULL, - `UserLookAtX` float default NULL, - `UserLookAtY` float default NULL, - `UserLookAtZ` float default NULL, - `AuthbuyerID` varchar(36) NOT NULL default '00000000-0000-0000-0000-000000000000', - PRIMARY KEY (`UUID`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - -CREATE TABLE `landaccesslist` ( - `LandUUID` varchar(255) default NULL, - `AccessUUID` varchar(255) default NULL, - `Flags` int(11) default NULL -) ENGINE=MyISAM DEFAULT CHARSET=latin1; - -COMMIT; \ No newline at end of file diff --git a/OpenSim/Data/MySQL/Resources/001_UserAccount.sql b/OpenSim/Data/MySQL/Resources/001_UserAccount.sql deleted file mode 100644 index 07da57118d..0000000000 --- a/OpenSim/Data/MySQL/Resources/001_UserAccount.sql +++ /dev/null @@ -1,13 +0,0 @@ -BEGIN; - -CREATE TABLE `UserAccounts` ( - `PrincipalID` CHAR(36) NOT NULL, - `ScopeID` CHAR(36) NOT NULL, - `FirstName` VARCHAR(64) NOT NULL, - `LastName` VARCHAR(64) NOT NULL, - `Email` VARCHAR(64), - `ServiceURLs` TEXT, - `Created` INT(11) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/002_AssetStore.sql b/OpenSim/Data/MySQL/Resources/002_AssetStore.sql deleted file mode 100644 index a7d7fca8c5..0000000000 --- a/OpenSim/Data/MySQL/Resources/002_AssetStore.sql +++ /dev/null @@ -1,9 +0,0 @@ -BEGIN; - -ALTER TABLE assets change id oldid binary(16); -ALTER TABLE assets add id varchar(36) not null default ''; -UPDATE assets set id = concat(substr(hex(oldid),1,8),"-",substr(hex(oldid),9,4),"-",substr(hex(oldid),13,4),"-",substr(hex(oldid),17,4),"-",substr(hex(oldid),21,12)); -ALTER TABLE assets drop oldid; -ALTER TABLE assets add constraint primary key(id); - -COMMIT; \ No newline at end of file diff --git a/OpenSim/Data/MySQL/Resources/002_AuthStore.sql b/OpenSim/Data/MySQL/Resources/002_AuthStore.sql deleted file mode 100644 index dc7dfe0115..0000000000 --- a/OpenSim/Data/MySQL/Resources/002_AuthStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN; - -INSERT INTO auth (UUID, passwordHash, passwordSalt, webLoginKey) SELECT `UUID` AS UUID, `passwordHash` AS passwordHash, `passwordSalt` AS passwordSalt, `webLoginKey` AS webLoginKey FROM users; - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/002_Friends.sql b/OpenSim/Data/MySQL/Resources/002_Friends.sql deleted file mode 100644 index 5ff64389f1..0000000000 --- a/OpenSim/Data/MySQL/Resources/002_Friends.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN; - -INSERT INTO Friends (PrincipalID, FriendID, Flags) SELECT ownerID, friendID, friendPerms FROM userfriends; - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/002_FriendsStore.sql b/OpenSim/Data/MySQL/Resources/002_FriendsStore.sql deleted file mode 100644 index a3638678c8..0000000000 --- a/OpenSim/Data/MySQL/Resources/002_FriendsStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN; - -INSERT INTO `Friends` SELECT `ownerID`, `friendID`, `friendPerms`, 0 FROM `userfriends`; - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/002_GridStore.sql b/OpenSim/Data/MySQL/Resources/002_GridStore.sql deleted file mode 100644 index 35b9be122e..0000000000 --- a/OpenSim/Data/MySQL/Resources/002_GridStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN; - -ALTER TABLE regions add column access integer unsigned default 1; - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/002_InventoryStore.sql b/OpenSim/Data/MySQL/Resources/002_InventoryStore.sql deleted file mode 100644 index c161a687e2..0000000000 --- a/OpenSim/Data/MySQL/Resources/002_InventoryStore.sql +++ /dev/null @@ -1,31 +0,0 @@ -BEGIN; - -ALTER TABLE inventoryfolders change folderID folderIDold varchar(36); -ALTER TABLE inventoryfolders change agentID agentIDold varchar(36); -ALTER TABLE inventoryfolders change parentFolderID parentFolderIDold varchar(36); -ALTER TABLE inventoryfolders add folderID char(36) not null default '00000000-0000-0000-0000-000000000000'; -ALTER TABLE inventoryfolders add agentID char(36) default NULL; -ALTER TABLE inventoryfolders add parentFolderID char(36) default NULL; -UPDATE inventoryfolders set folderID = folderIDold, agentID = agentIDold, parentFolderID = parentFolderIDold; -ALTER TABLE inventoryfolders drop folderIDold; -ALTER TABLE inventoryfolders drop agentIDold; -ALTER TABLE inventoryfolders drop parentFolderIDold; -ALTER TABLE inventoryfolders add constraint primary key(folderID); -ALTER TABLE inventoryfolders add index inventoryfolders_agentid(agentID); -ALTER TABLE inventoryfolders add index inventoryfolders_parentFolderid(parentFolderID); - -ALTER TABLE inventoryitems change inventoryID inventoryIDold varchar(36); -ALTER TABLE inventoryitems change avatarID avatarIDold varchar(36); -ALTER TABLE inventoryitems change parentFolderID parentFolderIDold varchar(36); -ALTER TABLE inventoryitems add inventoryID char(36) not null default '00000000-0000-0000-0000-000000000000'; -ALTER TABLE inventoryitems add avatarID char(36) default NULL; -ALTER TABLE inventoryitems add parentFolderID char(36) default NULL; -UPDATE inventoryitems set inventoryID = inventoryIDold, avatarID = avatarIDold, parentFolderID = parentFolderIDold; -ALTER TABLE inventoryitems drop inventoryIDold; -ALTER TABLE inventoryitems drop avatarIDold; -ALTER TABLE inventoryitems drop parentFolderIDold; -ALTER TABLE inventoryitems add constraint primary key(inventoryID); -ALTER TABLE inventoryitems add index inventoryitems_avatarid(avatarID); -ALTER TABLE inventoryitems add index inventoryitems_parentFolderid(parentFolderID); - -COMMIT; \ No newline at end of file diff --git a/OpenSim/Data/MySQL/Resources/002_Presence.sql b/OpenSim/Data/MySQL/Resources/002_Presence.sql deleted file mode 100644 index e65f105477..0000000000 --- a/OpenSim/Data/MySQL/Resources/002_Presence.sql +++ /dev/null @@ -1,7 +0,0 @@ -BEGIN; - -ALTER TABLE Presence ADD COLUMN `HomeRegionID` CHAR(36) NOT NULL; -ALTER TABLE Presence ADD COLUMN `HomePosition` CHAR(64) NOT NULL DEFAULT '<0,0,0>'; -ALTER TABLE Presence ADD COLUMN `HomeLookAt` CHAR(64) NOT NULL DEFAULT '<0,0,0>'; - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/002_RegionStore.sql b/OpenSim/Data/MySQL/Resources/002_RegionStore.sql deleted file mode 100644 index 45bf959d40..0000000000 --- a/OpenSim/Data/MySQL/Resources/002_RegionStore.sql +++ /dev/null @@ -1,6 +0,0 @@ -BEGIN; - -CREATE index prims_regionuuid on prims(RegionUUID); -CREATE index primitems_primid on primitems(primID); - -COMMIT; \ No newline at end of file diff --git a/OpenSim/Data/MySQL/Resources/002_UserAccount.sql b/OpenSim/Data/MySQL/Resources/002_UserAccount.sql deleted file mode 100644 index ad2ddda239..0000000000 --- a/OpenSim/Data/MySQL/Resources/002_UserAccount.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN; - -INSERT INTO UserAccounts (PrincipalID, ScopeID, FirstName, LastName, Email, ServiceURLs, Created) SELECT `UUID` AS PrincipalID, '00000000-0000-0000-0000-000000000000' AS ScopeID, username AS FirstName, lastname AS LastName, email as Email, CONCAT('AssetServerURI=', userAssetURI, ' InventoryServerURI=', userInventoryURI, ' GatewayURI= HomeURI=') AS ServiceURLs, created as Created FROM users; - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/002_UserStore.sql b/OpenSim/Data/MySQL/Resources/002_UserStore.sql deleted file mode 100644 index 393cea0f12..0000000000 --- a/OpenSim/Data/MySQL/Resources/002_UserStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN; - -ALTER TABLE users add homeRegionID char(36) NOT NULL default '00000000-0000-0000-0000-000000000000'; - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/003_AssetStore.sql b/OpenSim/Data/MySQL/Resources/003_AssetStore.sql deleted file mode 100644 index d489278f13..0000000000 --- a/OpenSim/Data/MySQL/Resources/003_AssetStore.sql +++ /dev/null @@ -1,9 +0,0 @@ -BEGIN; - -ALTER TABLE assets change id oldid varchar(36); -ALTER TABLE assets add id char(36) not null default '00000000-0000-0000-0000-000000000000'; -UPDATE assets set id = oldid; -ALTER TABLE assets drop oldid; -ALTER TABLE assets add constraint primary key(id); - -COMMIT; \ No newline at end of file diff --git a/OpenSim/Data/MySQL/Resources/003_AuthStore.sql b/OpenSim/Data/MySQL/Resources/003_AuthStore.sql deleted file mode 100644 index af9ffe6f1d..0000000000 --- a/OpenSim/Data/MySQL/Resources/003_AuthStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN; - -ALTER TABLE `auth` ADD COLUMN `accountType` VARCHAR(32) NOT NULL DEFAULT 'UserAccount'; - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/003_GridStore.sql b/OpenSim/Data/MySQL/Resources/003_GridStore.sql deleted file mode 100644 index bc3fe7df7a..0000000000 --- a/OpenSim/Data/MySQL/Resources/003_GridStore.sql +++ /dev/null @@ -1,7 +0,0 @@ -BEGIN; - -ALTER TABLE regions add column ScopeID char(36) not null default '00000000-0000-0000-0000-000000000000'; - -create index ScopeID on regions(ScopeID); - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/003_Presence.sql b/OpenSim/Data/MySQL/Resources/003_Presence.sql deleted file mode 100644 index 0efefa81bf..0000000000 --- a/OpenSim/Data/MySQL/Resources/003_Presence.sql +++ /dev/null @@ -1,6 +0,0 @@ -BEGIN; - -CREATE UNIQUE INDEX SessionID ON Presence(SessionID); -CREATE INDEX UserID ON Presence(UserID); - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/003_RegionStore.sql b/OpenSim/Data/MySQL/Resources/003_RegionStore.sql deleted file mode 100644 index cb0a6141cc..0000000000 --- a/OpenSim/Data/MySQL/Resources/003_RegionStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN; - - CREATE TABLE regionban (regionUUID VARCHAR(36) NOT NULL, bannedUUID VARCHAR(36) NOT NULL, bannedIp VARCHAR(16) NOT NULL, bannedIpHostMask VARCHAR(16) NOT NULL) ENGINE=INNODB DEFAULT CHARSET=utf8 COMMENT='Rev. 1'; - -COMMIT; \ No newline at end of file diff --git a/OpenSim/Data/MySQL/Resources/003_UserAccount.sql b/OpenSim/Data/MySQL/Resources/003_UserAccount.sql deleted file mode 100644 index e42d93b92c..0000000000 --- a/OpenSim/Data/MySQL/Resources/003_UserAccount.sql +++ /dev/null @@ -1,9 +0,0 @@ -BEGIN; - -CREATE UNIQUE INDEX PrincipalID ON UserAccounts(PrincipalID); -CREATE INDEX Email ON UserAccounts(Email); -CREATE INDEX FirstName ON UserAccounts(FirstName); -CREATE INDEX LastName ON UserAccounts(LastName); -CREATE INDEX Name ON UserAccounts(FirstName,LastName); - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/004_AssetStore.sql b/OpenSim/Data/MySQL/Resources/004_AssetStore.sql deleted file mode 100644 index ae1951df39..0000000000 --- a/OpenSim/Data/MySQL/Resources/004_AssetStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN; - -ALTER TABLE assets drop InvType; - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/004_GridStore.sql b/OpenSim/Data/MySQL/Resources/004_GridStore.sql deleted file mode 100644 index 2238a888ea..0000000000 --- a/OpenSim/Data/MySQL/Resources/004_GridStore.sql +++ /dev/null @@ -1,6 +0,0 @@ -BEGIN; - -ALTER TABLE regions add column sizeX integer not null default 0; -ALTER TABLE regions add column sizeY integer not null default 0; - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/004_InventoryStore.sql b/OpenSim/Data/MySQL/Resources/004_InventoryStore.sql deleted file mode 100644 index c45f773904..0000000000 --- a/OpenSim/Data/MySQL/Resources/004_InventoryStore.sql +++ /dev/null @@ -1,7 +0,0 @@ -BEGIN; - -update inventoryitems set creatorID = '00000000-0000-0000-0000-000000000000' where creatorID is NULL; -update inventoryitems set creatorID = '00000000-0000-0000-0000-000000000000' where creatorID = ''; -alter table inventoryitems modify column creatorID varchar(36) not NULL default '00000000-0000-0000-0000-000000000000'; - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/004_RegionStore.sql b/OpenSim/Data/MySQL/Resources/004_RegionStore.sql deleted file mode 100644 index 4db2f7587d..0000000000 --- a/OpenSim/Data/MySQL/Resources/004_RegionStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN; - -ALTER TABLE primitems add flags integer not null default 0; - -COMMIT; \ No newline at end of file diff --git a/OpenSim/Data/MySQL/Resources/004_UserAccount.sql b/OpenSim/Data/MySQL/Resources/004_UserAccount.sql deleted file mode 100644 index 8abcd53a16..0000000000 --- a/OpenSim/Data/MySQL/Resources/004_UserAccount.sql +++ /dev/null @@ -1,8 +0,0 @@ -BEGIN; - -ALTER TABLE UserAccounts ADD COLUMN UserLevel integer NOT NULL DEFAULT 0; -ALTER TABLE UserAccounts ADD COLUMN UserFlags integer NOT NULL DEFAULT 0; -ALTER TABLE UserAccounts ADD COLUMN UserTitle varchar(64) NOT NULL DEFAULT ''; - -COMMIT; - diff --git a/OpenSim/Data/MySQL/Resources/005_AssetStore.sql b/OpenSim/Data/MySQL/Resources/005_AssetStore.sql deleted file mode 100644 index bfeb6525af..0000000000 --- a/OpenSim/Data/MySQL/Resources/005_AssetStore.sql +++ /dev/null @@ -1,6 +0,0 @@ -BEGIN; - -ALTER TABLE assets add create_time integer default 0; -ALTER TABLE assets add access_time integer default 0; - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/005_GridStore.sql b/OpenSim/Data/MySQL/Resources/005_GridStore.sql deleted file mode 100644 index 835ba89369..0000000000 --- a/OpenSim/Data/MySQL/Resources/005_GridStore.sql +++ /dev/null @@ -1,6 +0,0 @@ -BEGIN; - -ALTER TABLE `regions` ADD COLUMN `flags` integer NOT NULL DEFAULT 0; -CREATE INDEX flags ON regions(flags); - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/005_RegionStore.sql b/OpenSim/Data/MySQL/Resources/005_RegionStore.sql deleted file mode 100644 index c4a9527403..0000000000 --- a/OpenSim/Data/MySQL/Resources/005_RegionStore.sql +++ /dev/null @@ -1,40 +0,0 @@ -BEGIN; - -create table regionsettings ( - regionUUID char(36) not null, - block_terraform integer not null, - block_fly integer not null, - allow_damage integer not null, - restrict_pushing integer not null, - allow_land_resell integer not null, - allow_land_join_divide integer not null, - block_show_in_search integer not null, - agent_limit integer not null, - object_bonus float not null, - maturity integer not null, - disable_scripts integer not null, - disable_collisions integer not null, - disable_physics integer not null, - terrain_texture_1 char(36) not null, - terrain_texture_2 char(36) not null, - terrain_texture_3 char(36) not null, - terrain_texture_4 char(36) not null, - elevation_1_nw float not null, - elevation_2_nw float not null, - elevation_1_ne float not null, - elevation_2_ne float not null, - elevation_1_se float not null, - elevation_2_se float not null, - elevation_1_sw float not null, - elevation_2_sw float not null, - water_height float not null, - terrain_raise_limit float not null, - terrain_lower_limit float not null, - use_estate_sun integer not null, - fixed_sun integer not null, - sun_position float not null, - covenant char(36), - primary key(regionUUID) -); - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/005_UserStore.sql b/OpenSim/Data/MySQL/Resources/005_UserStore.sql deleted file mode 100644 index 55896bc9a0..0000000000 --- a/OpenSim/Data/MySQL/Resources/005_UserStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN; - -CREATE TABLE `avatarattachments` (`UUID` char(36) NOT NULL, `attachpoint` int(11) NOT NULL, `item` char(36) NOT NULL, `asset` char(36) NOT NULL) ENGINE=InnoDB; - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/006_AssetStore.sql b/OpenSim/Data/MySQL/Resources/006_AssetStore.sql deleted file mode 100644 index 31043537a3..0000000000 --- a/OpenSim/Data/MySQL/Resources/006_AssetStore.sql +++ /dev/null @@ -1 +0,0 @@ -DELETE FROM assets WHERE id = 'dc4b9f0b-d008-45c6-96a4-01dd947ac621' diff --git a/OpenSim/Data/MySQL/Resources/006_GridStore.sql b/OpenSim/Data/MySQL/Resources/006_GridStore.sql deleted file mode 100644 index 91322d6431..0000000000 --- a/OpenSim/Data/MySQL/Resources/006_GridStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN; - -ALTER TABLE `regions` ADD COLUMN `last_seen` integer NOT NULL DEFAULT 0; - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/006_RegionStore.sql b/OpenSim/Data/MySQL/Resources/006_RegionStore.sql deleted file mode 100644 index c1ba5b808d..0000000000 --- a/OpenSim/Data/MySQL/Resources/006_RegionStore.sql +++ /dev/null @@ -1,12 +0,0 @@ -BEGIN; - -alter table landaccesslist ENGINE = InnoDB; -alter table migrations ENGINE = InnoDB; -alter table primitems ENGINE = InnoDB; -alter table prims ENGINE = InnoDB; -alter table primshapes ENGINE = InnoDB; -alter table regionsettings ENGINE = InnoDB; -alter table terrain ENGINE = InnoDB; - -COMMIT; - diff --git a/OpenSim/Data/MySQL/Resources/006_UserStore.sql b/OpenSim/Data/MySQL/Resources/006_UserStore.sql deleted file mode 100644 index 10b321e601..0000000000 --- a/OpenSim/Data/MySQL/Resources/006_UserStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN; - -ALTER TABLE agents add currentLookAt varchar(36) not null default ''; - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/007_GridStore.sql b/OpenSim/Data/MySQL/Resources/007_GridStore.sql deleted file mode 100644 index dbec58432e..0000000000 --- a/OpenSim/Data/MySQL/Resources/007_GridStore.sql +++ /dev/null @@ -1,7 +0,0 @@ -BEGIN; - -ALTER TABLE `regions` ADD COLUMN `PrincipalID` char(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000'; -ALTER TABLE `regions` ADD COLUMN `Token` varchar(255) NOT NULL; - -COMMIT; - diff --git a/OpenSim/Data/MySQL/Resources/007_RegionStore.sql b/OpenSim/Data/MySQL/Resources/007_RegionStore.sql deleted file mode 100644 index 404d248e6b..0000000000 --- a/OpenSim/Data/MySQL/Resources/007_RegionStore.sql +++ /dev/null @@ -1,25 +0,0 @@ -BEGIN; - -ALTER TABLE prims change UUID UUIDold varchar(255); -ALTER TABLE prims change RegionUUID RegionUUIDold varchar(255); -ALTER TABLE prims change CreatorID CreatorIDold varchar(255); -ALTER TABLE prims change OwnerID OwnerIDold varchar(255); -ALTER TABLE prims change GroupID GroupIDold varchar(255); -ALTER TABLE prims change LastOwnerID LastOwnerIDold varchar(255); -ALTER TABLE prims add UUID char(36); -ALTER TABLE prims add RegionUUID char(36); -ALTER TABLE prims add CreatorID char(36); -ALTER TABLE prims add OwnerID char(36); -ALTER TABLE prims add GroupID char(36); -ALTER TABLE prims add LastOwnerID char(36); -UPDATE prims set UUID = UUIDold, RegionUUID = RegionUUIDold, CreatorID = CreatorIDold, OwnerID = OwnerIDold, GroupID = GroupIDold, LastOwnerID = LastOwnerIDold; -ALTER TABLE prims drop UUIDold; -ALTER TABLE prims drop RegionUUIDold; -ALTER TABLE prims drop CreatorIDold; -ALTER TABLE prims drop OwnerIDold; -ALTER TABLE prims drop GroupIDold; -ALTER TABLE prims drop LastOwnerIDold; -ALTER TABLE prims add constraint primary key(UUID); -ALTER TABLE prims add index prims_regionuuid(RegionUUID); - -COMMIT; \ No newline at end of file diff --git a/OpenSim/Data/MySQL/Resources/007_UserStore.sql b/OpenSim/Data/MySQL/Resources/007_UserStore.sql deleted file mode 100644 index 3ab5261373..0000000000 --- a/OpenSim/Data/MySQL/Resources/007_UserStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN; - -ALTER TABLE users add email varchar(250); - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/008_RegionStore.sql b/OpenSim/Data/MySQL/Resources/008_RegionStore.sql deleted file mode 100644 index 7bc61c04e4..0000000000 --- a/OpenSim/Data/MySQL/Resources/008_RegionStore.sql +++ /dev/null @@ -1,9 +0,0 @@ -BEGIN; - -ALTER TABLE primshapes change UUID UUIDold varchar(255); -ALTER TABLE primshapes add UUID char(36); -UPDATE primshapes set UUID = UUIDold; -ALTER TABLE primshapes drop UUIDold; -ALTER TABLE primshapes add constraint primary key(UUID); - -COMMIT; \ No newline at end of file diff --git a/OpenSim/Data/MySQL/Resources/008_UserStore.sql b/OpenSim/Data/MySQL/Resources/008_UserStore.sql deleted file mode 100644 index 4500bd5d7b..0000000000 --- a/OpenSim/Data/MySQL/Resources/008_UserStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN; - -ALTER TABLE users add scopeID char(36) not null default '00000000-0000-0000-0000-000000000000'; - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/009_RegionStore.sql b/OpenSim/Data/MySQL/Resources/009_RegionStore.sql deleted file mode 100644 index 284732aa6f..0000000000 --- a/OpenSim/Data/MySQL/Resources/009_RegionStore.sql +++ /dev/null @@ -1,31 +0,0 @@ -BEGIN; - -ALTER TABLE primitems change itemID itemIDold varchar(255); -ALTER TABLE primitems change primID primIDold varchar(255); -ALTER TABLE primitems change assetID assetIDold varchar(255); -ALTER TABLE primitems change parentFolderID parentFolderIDold varchar(255); -ALTER TABLE primitems change creatorID creatorIDold varchar(255); -ALTER TABLE primitems change ownerID ownerIDold varchar(255); -ALTER TABLE primitems change groupID groupIDold varchar(255); -ALTER TABLE primitems change lastOwnerID lastOwnerIDold varchar(255); -ALTER TABLE primitems add itemID char(36); -ALTER TABLE primitems add primID char(36); -ALTER TABLE primitems add assetID char(36); -ALTER TABLE primitems add parentFolderID char(36); -ALTER TABLE primitems add creatorID char(36); -ALTER TABLE primitems add ownerID char(36); -ALTER TABLE primitems add groupID char(36); -ALTER TABLE primitems add lastOwnerID char(36); -UPDATE primitems set itemID = itemIDold, primID = primIDold, assetID = assetIDold, parentFolderID = parentFolderIDold, creatorID = creatorIDold, ownerID = ownerIDold, groupID = groupIDold, lastOwnerID = lastOwnerIDold; -ALTER TABLE primitems drop itemIDold; -ALTER TABLE primitems drop primIDold; -ALTER TABLE primitems drop assetIDold; -ALTER TABLE primitems drop parentFolderIDold; -ALTER TABLE primitems drop creatorIDold; -ALTER TABLE primitems drop ownerIDold; -ALTER TABLE primitems drop groupIDold; -ALTER TABLE primitems drop lastOwnerIDold; -ALTER TABLE primitems add constraint primary key(itemID); -ALTER TABLE primitems add index primitems_primid(primID); - -COMMIT; \ No newline at end of file diff --git a/OpenSim/Data/MySQL/Resources/010_RegionStore.sql b/OpenSim/Data/MySQL/Resources/010_RegionStore.sql deleted file mode 100644 index 031a746aeb..0000000000 --- a/OpenSim/Data/MySQL/Resources/010_RegionStore.sql +++ /dev/null @@ -1,9 +0,0 @@ -# 1 "010_RegionStore.sql" -# 1 "" -# 1 "" -# 1 "010_RegionStore.sql" -BEGIN; - -DELETE FROM regionsettings; - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/011_RegionStore.sql b/OpenSim/Data/MySQL/Resources/011_RegionStore.sql deleted file mode 100644 index ab0196934a..0000000000 --- a/OpenSim/Data/MySQL/Resources/011_RegionStore.sql +++ /dev/null @@ -1,9 +0,0 @@ -BEGIN; - -ALTER TABLE prims change SceneGroupID SceneGroupIDold varchar(255); -ALTER TABLE prims add SceneGroupID char(36); -UPDATE prims set SceneGroupID = SceneGroupIDold; -ALTER TABLE prims drop SceneGroupIDold; -ALTER TABLE prims add index prims_scenegroupid(SceneGroupID); - -COMMIT; \ No newline at end of file diff --git a/OpenSim/Data/MySQL/Resources/012_RegionStore.sql b/OpenSim/Data/MySQL/Resources/012_RegionStore.sql deleted file mode 100644 index 95c27573de..0000000000 --- a/OpenSim/Data/MySQL/Resources/012_RegionStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN; - -ALTER TABLE prims add index prims_parentid(ParentID); - -COMMIT; \ No newline at end of file diff --git a/OpenSim/Data/MySQL/Resources/014_RegionStore.sql b/OpenSim/Data/MySQL/Resources/014_RegionStore.sql deleted file mode 100644 index 788fd63c42..0000000000 --- a/OpenSim/Data/MySQL/Resources/014_RegionStore.sql +++ /dev/null @@ -1,8 +0,0 @@ -begin; - -alter table estate_settings add column AbuseEmail varchar(255) not null; - -alter table estate_settings add column EstateOwner varchar(36) not null; - -commit; - diff --git a/OpenSim/Data/MySQL/Resources/015_RegionStore.sql b/OpenSim/Data/MySQL/Resources/015_RegionStore.sql deleted file mode 100644 index 6d4f9f332f..0000000000 --- a/OpenSim/Data/MySQL/Resources/015_RegionStore.sql +++ /dev/null @@ -1,6 +0,0 @@ -begin; - -alter table estate_settings add column DenyMinors tinyint not null; - -commit; - diff --git a/OpenSim/Data/MySQL/Resources/016_RegionStore.sql b/OpenSim/Data/MySQL/Resources/016_RegionStore.sql deleted file mode 100644 index 9bc265e5ff..0000000000 --- a/OpenSim/Data/MySQL/Resources/016_RegionStore.sql +++ /dev/null @@ -1,27 +0,0 @@ -BEGIN; - -ALTER TABLE prims ADD COLUMN PayPrice integer not null default 0; -ALTER TABLE prims ADD COLUMN PayButton1 integer not null default 0; -ALTER TABLE prims ADD COLUMN PayButton2 integer not null default 0; -ALTER TABLE prims ADD COLUMN PayButton3 integer not null default 0; -ALTER TABLE prims ADD COLUMN PayButton4 integer not null default 0; -ALTER TABLE prims ADD COLUMN LoopedSound char(36) not null default '00000000-0000-0000-0000-000000000000'; -ALTER TABLE prims ADD COLUMN LoopedSoundGain float not null default 0.0; -ALTER TABLE prims ADD COLUMN TextureAnimation blob; -ALTER TABLE prims ADD COLUMN OmegaX float not null default 0.0; -ALTER TABLE prims ADD COLUMN OmegaY float not null default 0.0; -ALTER TABLE prims ADD COLUMN OmegaZ float not null default 0.0; -ALTER TABLE prims ADD COLUMN CameraEyeOffsetX float not null default 0.0; -ALTER TABLE prims ADD COLUMN CameraEyeOffsetY float not null default 0.0; -ALTER TABLE prims ADD COLUMN CameraEyeOffsetZ float not null default 0.0; -ALTER TABLE prims ADD COLUMN CameraAtOffsetX float not null default 0.0; -ALTER TABLE prims ADD COLUMN CameraAtOffsetY float not null default 0.0; -ALTER TABLE prims ADD COLUMN CameraAtOffsetZ float not null default 0.0; -ALTER TABLE prims ADD COLUMN ForceMouselook tinyint not null default 0; -ALTER TABLE prims ADD COLUMN ScriptAccessPin integer not null default 0; -ALTER TABLE prims ADD COLUMN AllowedDrop tinyint not null default 0; -ALTER TABLE prims ADD COLUMN DieAtEdge tinyint not null default 0; -ALTER TABLE prims ADD COLUMN SalePrice integer not null default 10; -ALTER TABLE prims ADD COLUMN SaleType tinyint not null default 0; - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/017_RegionStore.sql b/OpenSim/Data/MySQL/Resources/017_RegionStore.sql deleted file mode 100644 index 0304f30b72..0000000000 --- a/OpenSim/Data/MySQL/Resources/017_RegionStore.sql +++ /dev/null @@ -1,9 +0,0 @@ -BEGIN; - -ALTER TABLE prims ADD COLUMN ColorR integer not null default 0; -ALTER TABLE prims ADD COLUMN ColorG integer not null default 0; -ALTER TABLE prims ADD COLUMN ColorB integer not null default 0; -ALTER TABLE prims ADD COLUMN ColorA integer not null default 0; -ALTER TABLE prims ADD COLUMN ParticleSystem blob; - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/018_RegionStore.sql b/OpenSim/Data/MySQL/Resources/018_RegionStore.sql deleted file mode 100644 index 68c489c7bf..0000000000 --- a/OpenSim/Data/MySQL/Resources/018_RegionStore.sql +++ /dev/null @@ -1,6 +0,0 @@ -begin; - -ALTER TABLE prims ADD COLUMN ClickAction tinyint NOT NULL default 0; - -commit; - diff --git a/OpenSim/Data/MySQL/Resources/019_RegionStore.sql b/OpenSim/Data/MySQL/Resources/019_RegionStore.sql deleted file mode 100644 index 4c14f2a5f4..0000000000 --- a/OpenSim/Data/MySQL/Resources/019_RegionStore.sql +++ /dev/null @@ -1,6 +0,0 @@ -begin; - -ALTER TABLE prims ADD COLUMN Material tinyint NOT NULL default 3; - -commit; - diff --git a/OpenSim/Data/MySQL/Resources/020_RegionStore.sql b/OpenSim/Data/MySQL/Resources/020_RegionStore.sql deleted file mode 100644 index 814ef48bb6..0000000000 --- a/OpenSim/Data/MySQL/Resources/020_RegionStore.sql +++ /dev/null @@ -1,7 +0,0 @@ -begin; - -ALTER TABLE land ADD COLUMN OtherCleanTime integer NOT NULL default 0; -ALTER TABLE land ADD COLUMN Dwell integer NOT NULL default 0; - -commit; - diff --git a/OpenSim/Data/MySQL/Resources/021_RegionStore.sql b/OpenSim/Data/MySQL/Resources/021_RegionStore.sql deleted file mode 100644 index c59b27e745..0000000000 --- a/OpenSim/Data/MySQL/Resources/021_RegionStore.sql +++ /dev/null @@ -1,8 +0,0 @@ -begin; - -ALTER TABLE regionsettings ADD COLUMN sunvectorx double NOT NULL default 0; -ALTER TABLE regionsettings ADD COLUMN sunvectory double NOT NULL default 0; -ALTER TABLE regionsettings ADD COLUMN sunvectorz double NOT NULL default 0; - -commit; - diff --git a/OpenSim/Data/MySQL/Resources/022_RegionStore.sql b/OpenSim/Data/MySQL/Resources/022_RegionStore.sql deleted file mode 100644 index df0bb7dac9..0000000000 --- a/OpenSim/Data/MySQL/Resources/022_RegionStore.sql +++ /dev/null @@ -1,6 +0,0 @@ -BEGIN; - -ALTER TABLE prims ADD COLUMN CollisionSound char(36) not null default '00000000-0000-0000-0000-000000000000'; -ALTER TABLE prims ADD COLUMN CollisionSoundVolume float not null default 0.0; - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/023_RegionStore.sql b/OpenSim/Data/MySQL/Resources/023_RegionStore.sql deleted file mode 100644 index 559591fba5..0000000000 --- a/OpenSim/Data/MySQL/Resources/023_RegionStore.sql +++ /dev/null @@ -1,6 +0,0 @@ -BEGIN; - -ALTER TABLE prims ADD COLUMN LinkNumber integer not null default 0; - -COMMIT; - diff --git a/OpenSim/Data/MySQL/Resources/024_RegionStore.sql b/OpenSim/Data/MySQL/Resources/024_RegionStore.sql deleted file mode 100644 index defbf5cbb1..0000000000 --- a/OpenSim/Data/MySQL/Resources/024_RegionStore.sql +++ /dev/null @@ -1,18 +0,0 @@ -BEGIN; - -alter table regionsettings change column `object_bonus` `object_bonus` double NOT NULL; -alter table regionsettings change column `elevation_1_nw` `elevation_1_nw` double NOT NULL; -alter table regionsettings change column `elevation_2_nw` `elevation_2_nw` double NOT NULL; -alter table regionsettings change column `elevation_1_ne` `elevation_1_ne` double NOT NULL; -alter table regionsettings change column `elevation_2_ne` `elevation_2_ne` double NOT NULL; -alter table regionsettings change column `elevation_1_se` `elevation_1_se` double NOT NULL; -alter table regionsettings change column `elevation_2_se` `elevation_2_se` double NOT NULL; -alter table regionsettings change column `elevation_1_sw` `elevation_1_sw` double NOT NULL; -alter table regionsettings change column `elevation_2_sw` `elevation_2_sw` double NOT NULL; -alter table regionsettings change column `water_height` `water_height` double NOT NULL; -alter table regionsettings change column `terrain_raise_limit` `terrain_raise_limit` double NOT NULL; -alter table regionsettings change column `terrain_lower_limit` `terrain_lower_limit` double NOT NULL; -alter table regionsettings change column `sun_position` `sun_position` double NOT NULL; - -COMMIT; - diff --git a/OpenSim/Data/MySQL/Resources/025_RegionStore.sql b/OpenSim/Data/MySQL/Resources/025_RegionStore.sql deleted file mode 100644 index e8f5d70e47..0000000000 --- a/OpenSim/Data/MySQL/Resources/025_RegionStore.sql +++ /dev/null @@ -1,46 +0,0 @@ -BEGIN; - -alter table prims change column `PositionX` `PositionX` double default NULL; -alter table prims change column `PositionY` `PositionY` double default NULL; -alter table prims change column `PositionZ` `PositionZ` double default NULL; -alter table prims change column `GroupPositionX` `GroupPositionX` double default NULL; -alter table prims change column `GroupPositionY` `GroupPositionY` double default NULL; -alter table prims change column `GroupPositionZ` `GroupPositionZ` double default NULL; -alter table prims change column `VelocityX` `VelocityX` double default NULL; -alter table prims change column `VelocityY` `VelocityY` double default NULL; -alter table prims change column `VelocityZ` `VelocityZ` double default NULL; -alter table prims change column `AngularVelocityX` `AngularVelocityX` double default NULL; -alter table prims change column `AngularVelocityY` `AngularVelocityY` double default NULL; -alter table prims change column `AngularVelocityZ` `AngularVelocityZ` double default NULL; -alter table prims change column `AccelerationX` `AccelerationX` double default NULL; -alter table prims change column `AccelerationY` `AccelerationY` double default NULL; -alter table prims change column `AccelerationZ` `AccelerationZ` double default NULL; -alter table prims change column `RotationX` `RotationX` double default NULL; -alter table prims change column `RotationY` `RotationY` double default NULL; -alter table prims change column `RotationZ` `RotationZ` double default NULL; -alter table prims change column `RotationW` `RotationW` double default NULL; -alter table prims change column `SitTargetOffsetX` `SitTargetOffsetX` double default NULL; -alter table prims change column `SitTargetOffsetY` `SitTargetOffsetY` double default NULL; -alter table prims change column `SitTargetOffsetZ` `SitTargetOffsetZ` double default NULL; -alter table prims change column `SitTargetOrientW` `SitTargetOrientW` double default NULL; -alter table prims change column `SitTargetOrientX` `SitTargetOrientX` double default NULL; -alter table prims change column `SitTargetOrientY` `SitTargetOrientY` double default NULL; -alter table prims change column `SitTargetOrientZ` `SitTargetOrientZ` double default NULL; -alter table prims change column `LoopedSoundGain` `LoopedSoundGain` double NOT NULL default '0'; -alter table prims change column `OmegaX` `OmegaX` double NOT NULL default '0'; -alter table prims change column `OmegaY` `OmegaY` double NOT NULL default '0'; -alter table prims change column `OmegaZ` `OmegaZ` double NOT NULL default '0'; -alter table prims change column `CameraEyeOffsetX` `CameraEyeOffsetX` double NOT NULL default '0'; -alter table prims change column `CameraEyeOffsetY` `CameraEyeOffsetY` double NOT NULL default '0'; -alter table prims change column `CameraEyeOffsetZ` `CameraEyeOffsetZ` double NOT NULL default '0'; -alter table prims change column `CameraAtOffsetX` `CameraAtOffsetX` double NOT NULL default '0'; -alter table prims change column `CameraAtOffsetY` `CameraAtOffsetY` double NOT NULL default '0'; -alter table prims change column `CameraAtOffsetZ` `CameraAtOffsetZ` double NOT NULL default '0'; -alter table prims change column `CollisionSoundVolume` `CollisionSoundVolume` double NOT NULL default '0'; - -alter table primshapes change column `ScaleX` `ScaleX` double NOT NULL default '0'; -alter table primshapes change column `ScaleY` `ScaleY` double NOT NULL default '0'; -alter table primshapes change column `ScaleZ` `ScaleZ` double NOT NULL default '0'; - -COMMIT; - diff --git a/OpenSim/Data/MySQL/Resources/026_RegionStore.sql b/OpenSim/Data/MySQL/Resources/026_RegionStore.sql deleted file mode 100644 index 91af8a84c8..0000000000 --- a/OpenSim/Data/MySQL/Resources/026_RegionStore.sql +++ /dev/null @@ -1,41 +0,0 @@ -begin; - -alter table prims change column `PositionX` `PositionX` double default NULL; -alter table prims change column `PositionY` `PositionY` double default NULL; -alter table prims change column `PositionZ` `PositionZ` double default NULL; -alter table prims change column `GroupPositionX` `GroupPositionX` double default NULL; -alter table prims change column `GroupPositionY` `GroupPositionY` double default NULL; -alter table prims change column `GroupPositionZ` `GroupPositionZ` double default NULL; -alter table prims change column `VelocityX` `VelocityX` double default NULL; -alter table prims change column `VelocityY` `VelocityY` double default NULL; -alter table prims change column `VelocityZ` `VelocityZ` double default NULL; -alter table prims change column `AngularVelocityX` `AngularVelocityX` double default NULL; -alter table prims change column `AngularVelocityY` `AngularVelocityY` double default NULL; -alter table prims change column `AngularVelocityZ` `AngularVelocityZ` double default NULL; -alter table prims change column `AccelerationX` `AccelerationX` double default NULL; -alter table prims change column `AccelerationY` `AccelerationY` double default NULL; -alter table prims change column `AccelerationZ` `AccelerationZ` double default NULL; -alter table prims change column `RotationX` `RotationX` double default NULL; -alter table prims change column `RotationY` `RotationY` double default NULL; -alter table prims change column `RotationZ` `RotationZ` double default NULL; -alter table prims change column `RotationW` `RotationW` double default NULL; -alter table prims change column `SitTargetOffsetX` `SitTargetOffsetX` double default NULL; -alter table prims change column `SitTargetOffsetY` `SitTargetOffsetY` double default NULL; -alter table prims change column `SitTargetOffsetZ` `SitTargetOffsetZ` double default NULL; -alter table prims change column `SitTargetOrientW` `SitTargetOrientW` double default NULL; -alter table prims change column `SitTargetOrientX` `SitTargetOrientX` double default NULL; -alter table prims change column `SitTargetOrientY` `SitTargetOrientY` double default NULL; -alter table prims change column `SitTargetOrientZ` `SitTargetOrientZ` double default NULL; -alter table prims change column `LoopedSoundGain` `LoopedSoundGain` double NOT NULL default '0'; -alter table prims change column `OmegaX` `OmegaX` double NOT NULL default '0'; -alter table prims change column `OmegaY` `OmegaY` double NOT NULL default '0'; -alter table prims change column `OmegaZ` `OmegaZ` double NOT NULL default '0'; -alter table prims change column `CameraEyeOffsetX` `CameraEyeOffsetX` double NOT NULL default '0'; -alter table prims change column `CameraEyeOffsetY` `CameraEyeOffsetY` double NOT NULL default '0'; -alter table prims change column `CameraEyeOffsetZ` `CameraEyeOffsetZ` double NOT NULL default '0'; -alter table prims change column `CameraAtOffsetX` `CameraAtOffsetX` double NOT NULL default '0'; -alter table prims change column `CameraAtOffsetY` `CameraAtOffsetY` double NOT NULL default '0'; -alter table prims change column `CameraAtOffsetZ` `CameraAtOffsetZ` double NOT NULL default '0'; -alter table prims change column `CollisionSoundVolume` `CollisionSoundVolume` double NOT NULL default '0'; - -commit; diff --git a/OpenSim/Data/MySQL/Resources/027_RegionStore.sql b/OpenSim/Data/MySQL/Resources/027_RegionStore.sql deleted file mode 100644 index e1efab31c1..0000000000 --- a/OpenSim/Data/MySQL/Resources/027_RegionStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN; - -ALTER TABLE prims DROP COLUMN ParentID; - -COMMIT; \ No newline at end of file diff --git a/OpenSim/Data/MySQL/Resources/028_RegionStore.sql b/OpenSim/Data/MySQL/Resources/028_RegionStore.sql deleted file mode 100644 index 078394f80d..0000000000 --- a/OpenSim/Data/MySQL/Resources/028_RegionStore.sql +++ /dev/null @@ -1,79 +0,0 @@ -BEGIN; - -update terrain - set RegionUUID = concat(substr(RegionUUID, 1, 8), "-", substr(RegionUUID, 9, 4), "-", substr(RegionUUID, 13, 4), "-", substr(RegionUUID, 17, 4), "-", substr(RegionUUID, 21, 12)) - where RegionUUID not like '%-%'; - - -update landaccesslist - set LandUUID = concat(substr(LandUUID, 1, 8), "-", substr(LandUUID, 9, 4), "-", substr(LandUUID, 13, 4), "-", substr(LandUUID, 17, 4), "-", substr(LandUUID, 21, 12)) - where LandUUID not like '%-%'; - -update landaccesslist - set AccessUUID = concat(substr(AccessUUID, 1, 8), "-", substr(AccessUUID, 9, 4), "-", substr(AccessUUID, 13, 4), "-", substr(AccessUUID, 17, 4), "-", substr(AccessUUID, 21, 12)) - where AccessUUID not like '%-%'; - - -update prims - set UUID = concat(substr(UUID, 1, 8), "-", substr(UUID, 9, 4), "-", substr(UUID, 13, 4), "-", substr(UUID, 17, 4), "-", substr(UUID, 21, 12)) - where UUID not like '%-%'; - -update prims - set RegionUUID = concat(substr(RegionUUID, 1, 8), "-", substr(RegionUUID, 9, 4), "-", substr(RegionUUID, 13, 4), "-", substr(RegionUUID, 17, 4), "-", substr(RegionUUID, 21, 12)) - where RegionUUID not like '%-%'; - -update prims - set SceneGroupID = concat(substr(SceneGroupID, 1, 8), "-", substr(SceneGroupID, 9, 4), "-", substr(SceneGroupID, 13, 4), "-", substr(SceneGroupID, 17, 4), "-", substr(SceneGroupID, 21, 12)) - where SceneGroupID not like '%-%'; - -update prims - set CreatorID = concat(substr(CreatorID, 1, 8), "-", substr(CreatorID, 9, 4), "-", substr(CreatorID, 13, 4), "-", substr(CreatorID, 17, 4), "-", substr(CreatorID, 21, 12)) - where CreatorID not like '%-%'; - -update prims - set OwnerID = concat(substr(OwnerID, 1, 8), "-", substr(OwnerID, 9, 4), "-", substr(OwnerID, 13, 4), "-", substr(OwnerID, 17, 4), "-", substr(OwnerID, 21, 12)) - where OwnerID not like '%-%'; - -update prims - set GroupID = concat(substr(GroupID, 1, 8), "-", substr(GroupID, 9, 4), "-", substr(GroupID, 13, 4), "-", substr(GroupID, 17, 4), "-", substr(GroupID, 21, 12)) - where GroupID not like '%-%'; - -update prims - set LastOwnerID = concat(substr(LastOwnerID, 1, 8), "-", substr(LastOwnerID, 9, 4), "-", substr(LastOwnerID, 13, 4), "-", substr(LastOwnerID, 17, 4), "-", substr(LastOwnerID, 21, 12)) - where LastOwnerID not like '%-%'; - - -update primshapes - set UUID = concat(substr(UUID, 1, 8), "-", substr(UUID, 9, 4), "-", substr(UUID, 13, 4), "-", substr(UUID, 17, 4), "-", substr(UUID, 21, 12)) - where UUID not like '%-%'; - - -update land - set UUID = concat(substr(UUID, 1, 8), "-", substr(UUID, 9, 4), "-", substr(UUID, 13, 4), "-", substr(UUID, 17, 4), "-", substr(UUID, 21, 12)) - where UUID not like '%-%'; - -update land - set RegionUUID = concat(substr(RegionUUID, 1, 8), "-", substr(RegionUUID, 9, 4), "-", substr(RegionUUID, 13, 4), "-", substr(RegionUUID, 17, 4), "-", substr(RegionUUID, 21, 12)) - where RegionUUID not like '%-%'; - -update land - set OwnerUUID = concat(substr(OwnerUUID, 1, 8), "-", substr(OwnerUUID, 9, 4), "-", substr(OwnerUUID, 13, 4), "-", substr(OwnerUUID, 17, 4), "-", substr(OwnerUUID, 21, 12)) - where OwnerUUID not like '%-%'; - -update land - set GroupUUID = concat(substr(GroupUUID, 1, 8), "-", substr(GroupUUID, 9, 4), "-", substr(GroupUUID, 13, 4), "-", substr(GroupUUID, 17, 4), "-", substr(GroupUUID, 21, 12)) - where GroupUUID not like '%-%'; - -update land - set MediaTextureUUID = concat(substr(MediaTextureUUID, 1, 8), "-", substr(MediaTextureUUID, 9, 4), "-", substr(MediaTextureUUID, 13, 4), "-", substr(MediaTextureUUID, 17, 4), "-", substr(MediaTextureUUID, 21, 12)) - where MediaTextureUUID not like '%-%'; - -update land - set SnapshotUUID = concat(substr(SnapshotUUID, 1, 8), "-", substr(SnapshotUUID, 9, 4), "-", substr(SnapshotUUID, 13, 4), "-", substr(SnapshotUUID, 17, 4), "-", substr(SnapshotUUID, 21, 12)) - where SnapshotUUID not like '%-%'; - -update land - set AuthbuyerID = concat(substr(AuthbuyerID, 1, 8), "-", substr(AuthbuyerID, 9, 4), "-", substr(AuthbuyerID, 13, 4), "-", substr(AuthbuyerID, 17, 4), "-", substr(AuthbuyerID, 21, 12)) - where AuthbuyerID not like '%-%'; - -COMMIT; \ No newline at end of file diff --git a/OpenSim/Data/MySQL/Resources/029_RegionStore.sql b/OpenSim/Data/MySQL/Resources/029_RegionStore.sql deleted file mode 100644 index b5962a2e10..0000000000 --- a/OpenSim/Data/MySQL/Resources/029_RegionStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN; - -ALTER TABLE prims ADD COLUMN PassTouches tinyint not null default 0; - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/030_RegionStore.sql b/OpenSim/Data/MySQL/Resources/030_RegionStore.sql deleted file mode 100644 index dfdcf6d710..0000000000 --- a/OpenSim/Data/MySQL/Resources/030_RegionStore.sql +++ /dev/null @@ -1,7 +0,0 @@ -BEGIN; - -ALTER TABLE regionsettings ADD COLUMN loaded_creation_date varchar(20) default NULL; -ALTER TABLE regionsettings ADD COLUMN loaded_creation_time varchar(20) default NULL; -ALTER TABLE regionsettings ADD COLUMN loaded_creation_id varchar(64) default NULL; - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/031_RegionStore.sql b/OpenSim/Data/MySQL/Resources/031_RegionStore.sql deleted file mode 100644 index d069296039..0000000000 --- a/OpenSim/Data/MySQL/Resources/031_RegionStore.sql +++ /dev/null @@ -1,7 +0,0 @@ -BEGIN; - -ALTER TABLE regionsettings DROP COLUMN loaded_creation_date; -ALTER TABLE regionsettings DROP COLUMN loaded_creation_time; -ALTER TABLE regionsettings ADD COLUMN loaded_creation_datetime int unsigned NOT NULL default 0; - -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/032_RegionStore.sql b/OpenSim/Data/MySQL/Resources/032_RegionStore.sql deleted file mode 100644 index dca5de7144..0000000000 --- a/OpenSim/Data/MySQL/Resources/032_RegionStore.sql +++ /dev/null @@ -1,3 +0,0 @@ -BEGIN; -ALTER TABLE estate_settings AUTO_INCREMENT = 100; -COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/AssetStore.migrations b/OpenSim/Data/MySQL/Resources/AssetStore.migrations new file mode 100644 index 0000000000..9c5563038f --- /dev/null +++ b/OpenSim/Data/MySQL/Resources/AssetStore.migrations @@ -0,0 +1,77 @@ +# ----------------- +:VERSION 1 + +BEGIN; + +CREATE TABLE `assets` ( + `id` binary(16) NOT NULL, + `name` varchar(64) NOT NULL, + `description` varchar(64) NOT NULL, + `assetType` tinyint(4) NOT NULL, + `invType` tinyint(4) NOT NULL, + `local` tinyint(1) NOT NULL, + `temporary` tinyint(1) NOT NULL, + `data` longblob NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Rev. 1'; + +COMMIT; + +# ----------------- +:VERSION 2 + +BEGIN; + +ALTER TABLE assets change id oldid binary(16); +ALTER TABLE assets add id varchar(36) not null default ''; +UPDATE assets set id = concat(substr(hex(oldid),1,8),"-",substr(hex(oldid),9,4),"-",substr(hex(oldid),13,4),"-",substr(hex(oldid),17,4),"-",substr(hex(oldid),21,12)); +ALTER TABLE assets drop oldid; +ALTER TABLE assets add constraint primary key(id); + +COMMIT; + +# ----------------- +:VERSION 3 + +BEGIN; + +ALTER TABLE assets change id oldid varchar(36); +ALTER TABLE assets add id char(36) not null default '00000000-0000-0000-0000-000000000000'; +UPDATE assets set id = oldid; +ALTER TABLE assets drop oldid; +ALTER TABLE assets add constraint primary key(id); + +COMMIT; + +# ----------------- +:VERSION 4 + +BEGIN; + +ALTER TABLE assets drop InvType; + +COMMIT; + +# ----------------- +:VERSION 5 + +BEGIN; + +ALTER TABLE assets add create_time integer default 0; +ALTER TABLE assets add access_time integer default 0; + +COMMIT; + +# ----------------- +:VERSION 6 + +DELETE FROM assets WHERE id = 'dc4b9f0b-d008-45c6-96a4-01dd947ac621' + +:VERSION 7 + +ALTER TABLE assets ADD COLUMN asset_flags INTEGER NOT NULL DEFAULT 0; + +:VERSION 8 + +ALTER TABLE assets ADD COLUMN CreatorID varchar(36) NOT NULL DEFAULT ''; + diff --git a/OpenSim/Data/MySQL/Resources/001_AuthStore.sql b/OpenSim/Data/MySQL/Resources/AuthStore.migrations similarity index 51% rename from OpenSim/Data/MySQL/Resources/001_AuthStore.sql rename to OpenSim/Data/MySQL/Resources/AuthStore.migrations index c7e16fbdfb..023c786aa5 100644 --- a/OpenSim/Data/MySQL/Resources/001_AuthStore.sql +++ b/OpenSim/Data/MySQL/Resources/AuthStore.migrations @@ -1,3 +1,5 @@ +:VERSION 1 # ------------------------------- + begin; CREATE TABLE `auth` ( @@ -19,3 +21,19 @@ CREATE TABLE `tokens` ( ) ENGINE=InnoDB; commit; + +:VERSION 2 # ------------------------------- + +BEGIN; + +INSERT INTO auth (UUID, passwordHash, passwordSalt, webLoginKey) SELECT `UUID` AS UUID, `passwordHash` AS passwordHash, `passwordSalt` AS passwordSalt, `webLoginKey` AS webLoginKey FROM users; + +COMMIT; + +:VERSION 3 # ------------------------------- + +BEGIN; + +ALTER TABLE `auth` ADD COLUMN `accountType` VARCHAR(32) NOT NULL DEFAULT 'UserAccount'; + +COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/Avatar.migrations b/OpenSim/Data/MySQL/Resources/Avatar.migrations new file mode 100644 index 0000000000..8d0eee68a1 --- /dev/null +++ b/OpenSim/Data/MySQL/Resources/Avatar.migrations @@ -0,0 +1,12 @@ +:VERSION 1 + +BEGIN; + +CREATE TABLE Avatars ( + PrincipalID CHAR(36) NOT NULL, + Name VARCHAR(32) NOT NULL, + Value VARCHAR(255) NOT NULL DEFAULT '', + PRIMARY KEY(PrincipalID, Name), + KEY(PrincipalID)); + +COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/013_RegionStore.sql b/OpenSim/Data/MySQL/Resources/EstateStore.migrations similarity index 52% rename from OpenSim/Data/MySQL/Resources/013_RegionStore.sql rename to OpenSim/Data/MySQL/Resources/EstateStore.migrations index a6bd30da50..df82a2e1f8 100644 --- a/OpenSim/Data/MySQL/Resources/013_RegionStore.sql +++ b/OpenSim/Data/MySQL/Resources/EstateStore.migrations @@ -1,64 +1,30 @@ -begin; +:VERSION 13 -drop table regionsettings; +# The estate migrations used to be in Region store +# here they will do nothing (bad) if the tables are already there, +# just update the store version. -CREATE TABLE `regionsettings` ( - `regionUUID` char(36) NOT NULL, - `block_terraform` int(11) NOT NULL, - `block_fly` int(11) NOT NULL, - `allow_damage` int(11) NOT NULL, - `restrict_pushing` int(11) NOT NULL, - `allow_land_resell` int(11) NOT NULL, - `allow_land_join_divide` int(11) NOT NULL, - `block_show_in_search` int(11) NOT NULL, - `agent_limit` int(11) NOT NULL, - `object_bonus` float NOT NULL, - `maturity` int(11) NOT NULL, - `disable_scripts` int(11) NOT NULL, - `disable_collisions` int(11) NOT NULL, - `disable_physics` int(11) NOT NULL, - `terrain_texture_1` char(36) NOT NULL, - `terrain_texture_2` char(36) NOT NULL, - `terrain_texture_3` char(36) NOT NULL, - `terrain_texture_4` char(36) NOT NULL, - `elevation_1_nw` float NOT NULL, - `elevation_2_nw` float NOT NULL, - `elevation_1_ne` float NOT NULL, - `elevation_2_ne` float NOT NULL, - `elevation_1_se` float NOT NULL, - `elevation_2_se` float NOT NULL, - `elevation_1_sw` float NOT NULL, - `elevation_2_sw` float NOT NULL, - `water_height` float NOT NULL, - `terrain_raise_limit` float NOT NULL, - `terrain_lower_limit` float NOT NULL, - `use_estate_sun` int(11) NOT NULL, - `fixed_sun` int(11) NOT NULL, - `sun_position` float NOT NULL, - `covenant` char(36) default NULL, - `Sandbox` tinyint(4) NOT NULL, - PRIMARY KEY (`regionUUID`) -) ENGINE=InnoDB; +BEGIN; -CREATE TABLE `estate_managers` ( +CREATE TABLE IF NOT EXISTS `estate_managers` ( `EstateID` int(10) unsigned NOT NULL, `uuid` char(36) NOT NULL, KEY `EstateID` (`EstateID`) ) ENGINE=InnoDB; -CREATE TABLE `estate_groups` ( +CREATE TABLE IF NOT EXISTS `estate_groups` ( `EstateID` int(10) unsigned NOT NULL, `uuid` char(36) NOT NULL, KEY `EstateID` (`EstateID`) ) ENGINE=InnoDB; -CREATE TABLE `estate_users` ( +CREATE TABLE IF NOT EXISTS `estate_users` ( `EstateID` int(10) unsigned NOT NULL, `uuid` char(36) NOT NULL, KEY `EstateID` (`EstateID`) ) ENGINE=InnoDB; -CREATE TABLE `estateban` ( +CREATE TABLE IF NOT EXISTS `estateban` ( `EstateID` int(10) unsigned NOT NULL, `bannedUUID` varchar(36) NOT NULL, `bannedIp` varchar(16) NOT NULL, @@ -67,7 +33,7 @@ CREATE TABLE `estateban` ( KEY `estateban_EstateID` (`EstateID`) ) ENGINE=InnoDB; -CREATE TABLE `estate_settings` ( +CREATE TABLE IF NOT EXISTS `estate_settings` ( `EstateID` int(10) unsigned NOT NULL auto_increment, `EstateName` varchar(64) default NULL, `AbuseEmailToEstateOwner` tinyint(4) NOT NULL, @@ -89,15 +55,27 @@ CREATE TABLE `estate_settings` ( `EstateSkipScripts` tinyint(4) NOT NULL, `BillableFactor` float NOT NULL, `PublicAccess` tinyint(4) NOT NULL, + `AbuseEmail` varchar(255) not null, + `EstateOwner` varchar(36) not null, + `DenyMinors` tinyint not null, + PRIMARY KEY (`EstateID`) ) ENGINE=InnoDB AUTO_INCREMENT=100; -CREATE TABLE `estate_map` ( +CREATE TABLE IF NOT EXISTS `estate_map` ( `RegionID` char(36) NOT NULL default '00000000-0000-0000-0000-000000000000', `EstateID` int(11) NOT NULL, PRIMARY KEY (`RegionID`), KEY `EstateID` (`EstateID`) ) ENGINE=InnoDB; -commit; +COMMIT; + +:VERSION 32 #--------------------- (moved from RegionStore migr, just in case) + +BEGIN; +ALTER TABLE estate_settings AUTO_INCREMENT = 100; +COMMIT; + + diff --git a/OpenSim/Data/MySQL/Resources/FriendsStore.migrations b/OpenSim/Data/MySQL/Resources/FriendsStore.migrations new file mode 100644 index 0000000000..ce713bdb89 --- /dev/null +++ b/OpenSim/Data/MySQL/Resources/FriendsStore.migrations @@ -0,0 +1,25 @@ +:VERSION 1 # ------------------------- + +BEGIN; + +CREATE TABLE `Friends` ( + `PrincipalID` CHAR(36) NOT NULL, + `Friend` VARCHAR(255) NOT NULL, + `Flags` VARCHAR(16) NOT NULL DEFAULT 0, + `Offered` VARCHAR(32) NOT NULL DEFAULT 0, + PRIMARY KEY(`PrincipalID`, `Friend`), + KEY(`PrincipalID`) +); + +COMMIT; + +:VERSION 2 # ------------------------- + +BEGIN; + +INSERT INTO `Friends` SELECT `ownerID`, `friendID`, `friendPerms`, 0 FROM `userfriends`; + +COMMIT; + + + diff --git a/OpenSim/Data/MySQL/Resources/001_GridStore.sql b/OpenSim/Data/MySQL/Resources/GridStore.migrations similarity index 64% rename from OpenSim/Data/MySQL/Resources/001_GridStore.sql rename to OpenSim/Data/MySQL/Resources/GridStore.migrations index cb0f9bd2cd..523a8ac7dc 100644 --- a/OpenSim/Data/MySQL/Resources/001_GridStore.sql +++ b/OpenSim/Data/MySQL/Resources/GridStore.migrations @@ -1,3 +1,5 @@ +:VERSION 1 + CREATE TABLE `regions` ( `uuid` varchar(36) NOT NULL, `regionHandle` bigint(20) unsigned NOT NULL, @@ -30,3 +32,58 @@ CREATE TABLE `regions` ( KEY `regionHandle` (`regionHandle`), KEY `overrideHandles` (`eastOverrideHandle`,`westOverrideHandle`,`southOverrideHandle`,`northOverrideHandle`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=FIXED COMMENT='Rev. 3'; + +:VERSION 2 + +BEGIN; + +ALTER TABLE regions add column access integer unsigned default 1; + +COMMIT; + +:VERSION 3 + +BEGIN; + +ALTER TABLE regions add column ScopeID char(36) not null default '00000000-0000-0000-0000-000000000000'; + +create index ScopeID on regions(ScopeID); + +COMMIT; + +:VERSION 4 + +BEGIN; + +ALTER TABLE regions add column sizeX integer not null default 0; +ALTER TABLE regions add column sizeY integer not null default 0; + +COMMIT; + +:VERSION 5 + +BEGIN; + +ALTER TABLE `regions` ADD COLUMN `flags` integer NOT NULL DEFAULT 0; +CREATE INDEX flags ON regions(flags); + +COMMIT; + +:VERSION 6 + +BEGIN; + +ALTER TABLE `regions` ADD COLUMN `last_seen` integer NOT NULL DEFAULT 0; + +COMMIT; + +:VERSION 7 + +BEGIN; + +ALTER TABLE `regions` ADD COLUMN `PrincipalID` char(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000'; +ALTER TABLE `regions` ADD COLUMN `Token` varchar(255) NOT NULL; + +COMMIT; + + diff --git a/OpenSim/Data/MySQL/Resources/GridUserStore.migrations b/OpenSim/Data/MySQL/Resources/GridUserStore.migrations new file mode 100644 index 0000000000..32b85ee8c1 --- /dev/null +++ b/OpenSim/Data/MySQL/Resources/GridUserStore.migrations @@ -0,0 +1,19 @@ +:VERSION 1 # -------------------------- + +BEGIN; + +CREATE TABLE `GridUser` ( + `UserID` VARCHAR(255) NOT NULL, + `HomeRegionID` CHAR(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000', + `HomePosition` CHAR(64) NOT NULL DEFAULT '<0,0,0>', + `HomeLookAt` CHAR(64) NOT NULL DEFAULT '<0,0,0>', + `LastRegionID` CHAR(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000', + `LastPosition` CHAR(64) NOT NULL DEFAULT '<0,0,0>', + `LastLookAt` CHAR(64) NOT NULL DEFAULT '<0,0,0>', + `Online` CHAR(5) NOT NULL DEFAULT 'false', + `Login` CHAR(16) NOT NULL DEFAULT '0', + `Logout` CHAR(16) NOT NULL DEFAULT '0', + PRIMARY KEY (`UserID`) +) ENGINE=InnoDB; + +COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/InventoryStore.migrations b/OpenSim/Data/MySQL/Resources/InventoryStore.migrations new file mode 100644 index 0000000000..8c5864e97d --- /dev/null +++ b/OpenSim/Data/MySQL/Resources/InventoryStore.migrations @@ -0,0 +1,93 @@ +:VERSION 1 # ------------ +BEGIN; + +CREATE TABLE `inventoryfolders` ( + `folderID` varchar(36) NOT NULL default '', + `agentID` varchar(36) default NULL, + `parentFolderID` varchar(36) default NULL, + `folderName` varchar(64) default NULL, + `type` smallint NOT NULL default 0, + `version` int NOT NULL default 0, + PRIMARY KEY (`folderID`), + KEY `owner` (`agentID`), + KEY `parent` (`parentFolderID`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE `inventoryitems` ( + `inventoryID` varchar(36) NOT NULL default '', + `assetID` varchar(36) default NULL, + `assetType` int(11) default NULL, + `parentFolderID` varchar(36) default NULL, + `avatarID` varchar(36) default NULL, + `inventoryName` varchar(64) default NULL, + `inventoryDescription` varchar(128) default NULL, + `inventoryNextPermissions` int(10) unsigned default NULL, + `inventoryCurrentPermissions` int(10) unsigned default NULL, + `invType` int(11) default NULL, + `creatorID` varchar(36) default NULL, + `inventoryBasePermissions` int(10) unsigned NOT NULL default 0, + `inventoryEveryOnePermissions` int(10) unsigned NOT NULL default 0, + `salePrice` int(11) NOT NULL default 0, + `saleType` tinyint(4) NOT NULL default 0, + `creationDate` int(11) NOT NULL default 0, + `groupID` varchar(36) NOT NULL default '00000000-0000-0000-0000-000000000000', + `groupOwned` tinyint(4) NOT NULL default 0, + `flags` int(11) unsigned NOT NULL default 0, + PRIMARY KEY (`inventoryID`), + KEY `owner` (`avatarID`), + KEY `folder` (`parentFolderID`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +COMMIT; + +:VERSION 2 # ------------ + +BEGIN; + +ALTER TABLE inventoryfolders change folderID folderIDold varchar(36); +ALTER TABLE inventoryfolders change agentID agentIDold varchar(36); +ALTER TABLE inventoryfolders change parentFolderID parentFolderIDold varchar(36); +ALTER TABLE inventoryfolders add folderID char(36) not null default '00000000-0000-0000-0000-000000000000'; +ALTER TABLE inventoryfolders add agentID char(36) default NULL; +ALTER TABLE inventoryfolders add parentFolderID char(36) default NULL; +UPDATE inventoryfolders set folderID = folderIDold, agentID = agentIDold, parentFolderID = parentFolderIDold; +ALTER TABLE inventoryfolders drop folderIDold; +ALTER TABLE inventoryfolders drop agentIDold; +ALTER TABLE inventoryfolders drop parentFolderIDold; +ALTER TABLE inventoryfolders add constraint primary key(folderID); +ALTER TABLE inventoryfolders add index inventoryfolders_agentid(agentID); +ALTER TABLE inventoryfolders add index inventoryfolders_parentFolderid(parentFolderID); + +ALTER TABLE inventoryitems change inventoryID inventoryIDold varchar(36); +ALTER TABLE inventoryitems change avatarID avatarIDold varchar(36); +ALTER TABLE inventoryitems change parentFolderID parentFolderIDold varchar(36); +ALTER TABLE inventoryitems add inventoryID char(36) not null default '00000000-0000-0000-0000-000000000000'; +ALTER TABLE inventoryitems add avatarID char(36) default NULL; +ALTER TABLE inventoryitems add parentFolderID char(36) default NULL; +UPDATE inventoryitems set inventoryID = inventoryIDold, avatarID = avatarIDold, parentFolderID = parentFolderIDold; +ALTER TABLE inventoryitems drop inventoryIDold; +ALTER TABLE inventoryitems drop avatarIDold; +ALTER TABLE inventoryitems drop parentFolderIDold; +ALTER TABLE inventoryitems add constraint primary key(inventoryID); +ALTER TABLE inventoryitems add index inventoryitems_avatarid(avatarID); +ALTER TABLE inventoryitems add index inventoryitems_parentFolderid(parentFolderID); + +COMMIT; + +:VERSION 3 # ------------ + +BEGIN; + +alter table inventoryitems add column inventoryGroupPermissions integer unsigned not null default 0; + +COMMIT; + +:VERSION 4 # ------------ + +BEGIN; + +update inventoryitems set creatorID = '00000000-0000-0000-0000-000000000000' where creatorID is NULL; +update inventoryitems set creatorID = '00000000-0000-0000-0000-000000000000' where creatorID = ''; +alter table inventoryitems modify column creatorID varchar(36) not NULL default '00000000-0000-0000-0000-000000000000'; + +COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/001_LogStore.sql b/OpenSim/Data/MySQL/Resources/LogStore.migrations similarity index 95% rename from OpenSim/Data/MySQL/Resources/001_LogStore.sql rename to OpenSim/Data/MySQL/Resources/LogStore.migrations index b4c29fbef5..9ac26ac722 100644 --- a/OpenSim/Data/MySQL/Resources/001_LogStore.sql +++ b/OpenSim/Data/MySQL/Resources/LogStore.migrations @@ -1,3 +1,6 @@ + +:VERSION 1 + CREATE TABLE `logs` ( `logID` int(10) unsigned NOT NULL auto_increment, `target` varchar(36) default NULL, diff --git a/OpenSim/Data/MySQL/Resources/Presence.migrations b/OpenSim/Data/MySQL/Resources/Presence.migrations new file mode 100644 index 0000000000..91f7de55f7 --- /dev/null +++ b/OpenSim/Data/MySQL/Resources/Presence.migrations @@ -0,0 +1,15 @@ +:VERSION 1 # -------------------------- + +BEGIN; + +CREATE TABLE `Presence` ( + `UserID` VARCHAR(255) NOT NULL, + `RegionID` CHAR(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000', + `SessionID` CHAR(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000', + `SecureSessionID` CHAR(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000' +) ENGINE=InnoDB; + +CREATE UNIQUE INDEX SessionID ON Presence(SessionID); +CREATE INDEX UserID ON Presence(UserID); + +COMMIT; diff --git a/OpenSim/Data/MySQL/Resources/RegionStore.migrations b/OpenSim/Data/MySQL/Resources/RegionStore.migrations new file mode 100644 index 0000000000..d8a279dc71 --- /dev/null +++ b/OpenSim/Data/MySQL/Resources/RegionStore.migrations @@ -0,0 +1,725 @@ + +:VERSION 1 #--------------------- + +BEGIN; + +CREATE TABLE `prims` ( + `UUID` varchar(255) NOT NULL, + `RegionUUID` varchar(255) default NULL, + `ParentID` int(11) default NULL, + `CreationDate` int(11) default NULL, + `Name` varchar(255) default NULL, + `SceneGroupID` varchar(255) default NULL, + `Text` varchar(255) default NULL, + `Description` varchar(255) default NULL, + `SitName` varchar(255) default NULL, + `TouchName` varchar(255) default NULL, + `ObjectFlags` int(11) default NULL, + `CreatorID` varchar(255) default NULL, + `OwnerID` varchar(255) default NULL, + `GroupID` varchar(255) default NULL, + `LastOwnerID` varchar(255) default NULL, + `OwnerMask` int(11) default NULL, + `NextOwnerMask` int(11) default NULL, + `GroupMask` int(11) default NULL, + `EveryoneMask` int(11) default NULL, + `BaseMask` int(11) default NULL, + `PositionX` float default NULL, + `PositionY` float default NULL, + `PositionZ` float default NULL, + `GroupPositionX` float default NULL, + `GroupPositionY` float default NULL, + `GroupPositionZ` float default NULL, + `VelocityX` float default NULL, + `VelocityY` float default NULL, + `VelocityZ` float default NULL, + `AngularVelocityX` float default NULL, + `AngularVelocityY` float default NULL, + `AngularVelocityZ` float default NULL, + `AccelerationX` float default NULL, + `AccelerationY` float default NULL, + `AccelerationZ` float default NULL, + `RotationX` float default NULL, + `RotationY` float default NULL, + `RotationZ` float default NULL, + `RotationW` float default NULL, + `SitTargetOffsetX` float default NULL, + `SitTargetOffsetY` float default NULL, + `SitTargetOffsetZ` float default NULL, + `SitTargetOrientW` float default NULL, + `SitTargetOrientX` float default NULL, + `SitTargetOrientY` float default NULL, + `SitTargetOrientZ` float default NULL, + PRIMARY KEY (`UUID`) +) ENGINE=MyISAM DEFAULT CHARSET=latin1; + +CREATE TABLE `primshapes` ( + `UUID` varchar(255) NOT NULL, + `Shape` int(11) default NULL, + `ScaleX` float default NULL, + `ScaleY` float default NULL, + `ScaleZ` float default NULL, + `PCode` int(11) default NULL, + `PathBegin` int(11) default NULL, + `PathEnd` int(11) default NULL, + `PathScaleX` int(11) default NULL, + `PathScaleY` int(11) default NULL, + `PathShearX` int(11) default NULL, + `PathShearY` int(11) default NULL, + `PathSkew` int(11) default NULL, + `PathCurve` int(11) default NULL, + `PathRadiusOffset` int(11) default NULL, + `PathRevolutions` int(11) default NULL, + `PathTaperX` int(11) default NULL, + `PathTaperY` int(11) default NULL, + `PathTwist` int(11) default NULL, + `PathTwistBegin` int(11) default NULL, + `ProfileBegin` int(11) default NULL, + `ProfileEnd` int(11) default NULL, + `ProfileCurve` int(11) default NULL, + `ProfileHollow` int(11) default NULL, + `State` int(11) default NULL, + `Texture` longblob, + `ExtraParams` longblob, + PRIMARY KEY (`UUID`) +) ENGINE=MyISAM DEFAULT CHARSET=latin1; + +CREATE TABLE `primitems` ( + `itemID` varchar(255) NOT NULL, + `primID` varchar(255) default NULL, + `assetID` varchar(255) default NULL, + `parentFolderID` varchar(255) default NULL, + `invType` int(11) default NULL, + `assetType` int(11) default NULL, + `name` varchar(255) default NULL, + `description` varchar(255) default NULL, + `creationDate` bigint(20) default NULL, + `creatorID` varchar(255) default NULL, + `ownerID` varchar(255) default NULL, + `lastOwnerID` varchar(255) default NULL, + `groupID` varchar(255) default NULL, + `nextPermissions` int(11) default NULL, + `currentPermissions` int(11) default NULL, + `basePermissions` int(11) default NULL, + `everyonePermissions` int(11) default NULL, + `groupPermissions` int(11) default NULL, + PRIMARY KEY (`itemID`) +) ENGINE=MyISAM DEFAULT CHARSET=latin1; + +CREATE TABLE `terrain` ( + `RegionUUID` varchar(255) default NULL, + `Revision` int(11) default NULL, + `Heightfield` longblob +) ENGINE=MyISAM DEFAULT CHARSET=latin1; + +CREATE TABLE `land` ( + `UUID` varchar(255) NOT NULL, + `RegionUUID` varchar(255) default NULL, + `LocalLandID` int(11) default NULL, + `Bitmap` longblob, + `Name` varchar(255) default NULL, + `Description` varchar(255) default NULL, + `OwnerUUID` varchar(255) default NULL, + `IsGroupOwned` int(11) default NULL, + `Area` int(11) default NULL, + `AuctionID` int(11) default NULL, + `Category` int(11) default NULL, + `ClaimDate` int(11) default NULL, + `ClaimPrice` int(11) default NULL, + `GroupUUID` varchar(255) default NULL, + `SalePrice` int(11) default NULL, + `LandStatus` int(11) default NULL, + `LandFlags` int(11) default NULL, + `LandingType` int(11) default NULL, + `MediaAutoScale` int(11) default NULL, + `MediaTextureUUID` varchar(255) default NULL, + `MediaURL` varchar(255) default NULL, + `MusicURL` varchar(255) default NULL, + `PassHours` float default NULL, + `PassPrice` int(11) default NULL, + `SnapshotUUID` varchar(255) default NULL, + `UserLocationX` float default NULL, + `UserLocationY` float default NULL, + `UserLocationZ` float default NULL, + `UserLookAtX` float default NULL, + `UserLookAtY` float default NULL, + `UserLookAtZ` float default NULL, + `AuthbuyerID` varchar(36) NOT NULL default '00000000-0000-0000-0000-000000000000', + PRIMARY KEY (`UUID`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE `landaccesslist` ( + `LandUUID` varchar(255) default NULL, + `AccessUUID` varchar(255) default NULL, + `Flags` int(11) default NULL +) ENGINE=MyISAM DEFAULT CHARSET=latin1; + +COMMIT; + +:VERSION 2 #--------------------- + +BEGIN; + +CREATE index prims_regionuuid on prims(RegionUUID); +CREATE index primitems_primid on primitems(primID); + +COMMIT; + +:VERSION 3 #--------------------- + +BEGIN; + CREATE TABLE regionban (regionUUID VARCHAR(36) NOT NULL, bannedUUID VARCHAR(36) NOT NULL, bannedIp VARCHAR(16) NOT NULL, bannedIpHostMask VARCHAR(16) NOT NULL) ENGINE=INNODB DEFAULT CHARSET=utf8 COMMENT='Rev. 1'; +COMMIT; + +:VERSION 4 #--------------------- + +BEGIN; + +ALTER TABLE primitems add flags integer not null default 0; + +COMMIT; + +:VERSION 5 #--------------------- +BEGIN; + +create table regionsettings ( + regionUUID char(36) not null, + block_terraform integer not null, + block_fly integer not null, + allow_damage integer not null, + restrict_pushing integer not null, + allow_land_resell integer not null, + allow_land_join_divide integer not null, + block_show_in_search integer not null, + agent_limit integer not null, + object_bonus float not null, + maturity integer not null, + disable_scripts integer not null, + disable_collisions integer not null, + disable_physics integer not null, + terrain_texture_1 char(36) not null, + terrain_texture_2 char(36) not null, + terrain_texture_3 char(36) not null, + terrain_texture_4 char(36) not null, + elevation_1_nw float not null, + elevation_2_nw float not null, + elevation_1_ne float not null, + elevation_2_ne float not null, + elevation_1_se float not null, + elevation_2_se float not null, + elevation_1_sw float not null, + elevation_2_sw float not null, + water_height float not null, + terrain_raise_limit float not null, + terrain_lower_limit float not null, + use_estate_sun integer not null, + fixed_sun integer not null, + sun_position float not null, + covenant char(36), + primary key(regionUUID) +); + +COMMIT; + + +:VERSION 6 #--------------------- + +BEGIN; + +alter table landaccesslist ENGINE = InnoDB; +alter table migrations ENGINE = InnoDB; +alter table primitems ENGINE = InnoDB; +alter table prims ENGINE = InnoDB; +alter table primshapes ENGINE = InnoDB; +alter table regionsettings ENGINE = InnoDB; +alter table terrain ENGINE = InnoDB; + +COMMIT; + +:VERSION 7 #--------------------- + +BEGIN; + +ALTER TABLE prims change UUID UUIDold varchar(255); +ALTER TABLE prims change RegionUUID RegionUUIDold varchar(255); +ALTER TABLE prims change CreatorID CreatorIDold varchar(255); +ALTER TABLE prims change OwnerID OwnerIDold varchar(255); +ALTER TABLE prims change GroupID GroupIDold varchar(255); +ALTER TABLE prims change LastOwnerID LastOwnerIDold varchar(255); +ALTER TABLE prims add UUID char(36); +ALTER TABLE prims add RegionUUID char(36); +ALTER TABLE prims add CreatorID char(36); +ALTER TABLE prims add OwnerID char(36); +ALTER TABLE prims add GroupID char(36); +ALTER TABLE prims add LastOwnerID char(36); +UPDATE prims set UUID = UUIDold, RegionUUID = RegionUUIDold, CreatorID = CreatorIDold, OwnerID = OwnerIDold, GroupID = GroupIDold, LastOwnerID = LastOwnerIDold; +ALTER TABLE prims drop UUIDold; +ALTER TABLE prims drop RegionUUIDold; +ALTER TABLE prims drop CreatorIDold; +ALTER TABLE prims drop OwnerIDold; +ALTER TABLE prims drop GroupIDold; +ALTER TABLE prims drop LastOwnerIDold; +ALTER TABLE prims add constraint primary key(UUID); +ALTER TABLE prims add index prims_regionuuid(RegionUUID); + +COMMIT; + +:VERSION 8 #--------------------- + +BEGIN; + +ALTER TABLE primshapes change UUID UUIDold varchar(255); +ALTER TABLE primshapes add UUID char(36); +UPDATE primshapes set UUID = UUIDold; +ALTER TABLE primshapes drop UUIDold; +ALTER TABLE primshapes add constraint primary key(UUID); + +COMMIT; + +:VERSION 9 #--------------------- + +BEGIN; + +ALTER TABLE primitems change itemID itemIDold varchar(255); +ALTER TABLE primitems change primID primIDold varchar(255); +ALTER TABLE primitems change assetID assetIDold varchar(255); +ALTER TABLE primitems change parentFolderID parentFolderIDold varchar(255); +ALTER TABLE primitems change creatorID creatorIDold varchar(255); +ALTER TABLE primitems change ownerID ownerIDold varchar(255); +ALTER TABLE primitems change groupID groupIDold varchar(255); +ALTER TABLE primitems change lastOwnerID lastOwnerIDold varchar(255); +ALTER TABLE primitems add itemID char(36); +ALTER TABLE primitems add primID char(36); +ALTER TABLE primitems add assetID char(36); +ALTER TABLE primitems add parentFolderID char(36); +ALTER TABLE primitems add creatorID char(36); +ALTER TABLE primitems add ownerID char(36); +ALTER TABLE primitems add groupID char(36); +ALTER TABLE primitems add lastOwnerID char(36); +UPDATE primitems set itemID = itemIDold, primID = primIDold, assetID = assetIDold, parentFolderID = parentFolderIDold, creatorID = creatorIDold, ownerID = ownerIDold, groupID = groupIDold, lastOwnerID = lastOwnerIDold; +ALTER TABLE primitems drop itemIDold; +ALTER TABLE primitems drop primIDold; +ALTER TABLE primitems drop assetIDold; +ALTER TABLE primitems drop parentFolderIDold; +ALTER TABLE primitems drop creatorIDold; +ALTER TABLE primitems drop ownerIDold; +ALTER TABLE primitems drop groupIDold; +ALTER TABLE primitems drop lastOwnerIDold; +ALTER TABLE primitems add constraint primary key(itemID); +ALTER TABLE primitems add index primitems_primid(primID); + +COMMIT; + +:VERSION 10 #--------------------- + +# 1 "010_RegionStore.sql" +# 1 "" +# 1 "" +# 1 "010_RegionStore.sql" +BEGIN; + +DELETE FROM regionsettings; + +COMMIT; + + +:VERSION 11 #--------------------- + +BEGIN; + +ALTER TABLE prims change SceneGroupID SceneGroupIDold varchar(255); +ALTER TABLE prims add SceneGroupID char(36); +UPDATE prims set SceneGroupID = SceneGroupIDold; +ALTER TABLE prims drop SceneGroupIDold; +ALTER TABLE prims add index prims_scenegroupid(SceneGroupID); + +COMMIT; + +:VERSION 12 #--------------------- + +BEGIN; + +ALTER TABLE prims add index prims_parentid(ParentID); + +COMMIT; + +:VERSION 13 #--------------------- +begin; + +drop table regionsettings; + +CREATE TABLE `regionsettings` ( + `regionUUID` char(36) NOT NULL, + `block_terraform` int(11) NOT NULL, + `block_fly` int(11) NOT NULL, + `allow_damage` int(11) NOT NULL, + `restrict_pushing` int(11) NOT NULL, + `allow_land_resell` int(11) NOT NULL, + `allow_land_join_divide` int(11) NOT NULL, + `block_show_in_search` int(11) NOT NULL, + `agent_limit` int(11) NOT NULL, + `object_bonus` float NOT NULL, + `maturity` int(11) NOT NULL, + `disable_scripts` int(11) NOT NULL, + `disable_collisions` int(11) NOT NULL, + `disable_physics` int(11) NOT NULL, + `terrain_texture_1` char(36) NOT NULL, + `terrain_texture_2` char(36) NOT NULL, + `terrain_texture_3` char(36) NOT NULL, + `terrain_texture_4` char(36) NOT NULL, + `elevation_1_nw` float NOT NULL, + `elevation_2_nw` float NOT NULL, + `elevation_1_ne` float NOT NULL, + `elevation_2_ne` float NOT NULL, + `elevation_1_se` float NOT NULL, + `elevation_2_se` float NOT NULL, + `elevation_1_sw` float NOT NULL, + `elevation_2_sw` float NOT NULL, + `water_height` float NOT NULL, + `terrain_raise_limit` float NOT NULL, + `terrain_lower_limit` float NOT NULL, + `use_estate_sun` int(11) NOT NULL, + `fixed_sun` int(11) NOT NULL, + `sun_position` float NOT NULL, + `covenant` char(36) default NULL, + `Sandbox` tinyint(4) NOT NULL, + PRIMARY KEY (`regionUUID`) +) ENGINE=InnoDB; + +commit; + +:VERSION 16 #--------------------- + +BEGIN; + +ALTER TABLE prims ADD COLUMN PayPrice integer not null default 0; +ALTER TABLE prims ADD COLUMN PayButton1 integer not null default 0; +ALTER TABLE prims ADD COLUMN PayButton2 integer not null default 0; +ALTER TABLE prims ADD COLUMN PayButton3 integer not null default 0; +ALTER TABLE prims ADD COLUMN PayButton4 integer not null default 0; +ALTER TABLE prims ADD COLUMN LoopedSound char(36) not null default '00000000-0000-0000-0000-000000000000'; +ALTER TABLE prims ADD COLUMN LoopedSoundGain float not null default 0.0; +ALTER TABLE prims ADD COLUMN TextureAnimation blob; +ALTER TABLE prims ADD COLUMN OmegaX float not null default 0.0; +ALTER TABLE prims ADD COLUMN OmegaY float not null default 0.0; +ALTER TABLE prims ADD COLUMN OmegaZ float not null default 0.0; +ALTER TABLE prims ADD COLUMN CameraEyeOffsetX float not null default 0.0; +ALTER TABLE prims ADD COLUMN CameraEyeOffsetY float not null default 0.0; +ALTER TABLE prims ADD COLUMN CameraEyeOffsetZ float not null default 0.0; +ALTER TABLE prims ADD COLUMN CameraAtOffsetX float not null default 0.0; +ALTER TABLE prims ADD COLUMN CameraAtOffsetY float not null default 0.0; +ALTER TABLE prims ADD COLUMN CameraAtOffsetZ float not null default 0.0; +ALTER TABLE prims ADD COLUMN ForceMouselook tinyint not null default 0; +ALTER TABLE prims ADD COLUMN ScriptAccessPin integer not null default 0; +ALTER TABLE prims ADD COLUMN AllowedDrop tinyint not null default 0; +ALTER TABLE prims ADD COLUMN DieAtEdge tinyint not null default 0; +ALTER TABLE prims ADD COLUMN SalePrice integer not null default 10; +ALTER TABLE prims ADD COLUMN SaleType tinyint not null default 0; + +COMMIT; + + +:VERSION 17 #--------------------- + +BEGIN; + +ALTER TABLE prims ADD COLUMN ColorR integer not null default 0; +ALTER TABLE prims ADD COLUMN ColorG integer not null default 0; +ALTER TABLE prims ADD COLUMN ColorB integer not null default 0; +ALTER TABLE prims ADD COLUMN ColorA integer not null default 0; +ALTER TABLE prims ADD COLUMN ParticleSystem blob; + +COMMIT; + + +:VERSION 18 #--------------------- + +begin; + +ALTER TABLE prims ADD COLUMN ClickAction tinyint NOT NULL default 0; + +commit; + +:VERSION 19 #--------------------- + +begin; + +ALTER TABLE prims ADD COLUMN Material tinyint NOT NULL default 3; + +commit; + + +:VERSION 20 #--------------------- + +begin; + +ALTER TABLE land ADD COLUMN OtherCleanTime integer NOT NULL default 0; +ALTER TABLE land ADD COLUMN Dwell integer NOT NULL default 0; + +commit; + +:VERSION 21 #--------------------- + +begin; + +ALTER TABLE regionsettings ADD COLUMN sunvectorx double NOT NULL default 0; +ALTER TABLE regionsettings ADD COLUMN sunvectory double NOT NULL default 0; +ALTER TABLE regionsettings ADD COLUMN sunvectorz double NOT NULL default 0; + +commit; + + +:VERSION 22 #--------------------- + +BEGIN; + +ALTER TABLE prims ADD COLUMN CollisionSound char(36) not null default '00000000-0000-0000-0000-000000000000'; +ALTER TABLE prims ADD COLUMN CollisionSoundVolume float not null default 0.0; + +COMMIT; + +:VERSION 23 #--------------------- + +BEGIN; + +ALTER TABLE prims ADD COLUMN LinkNumber integer not null default 0; + +COMMIT; + +:VERSION 24 #--------------------- + +BEGIN; + +alter table regionsettings change column `object_bonus` `object_bonus` double NOT NULL; +alter table regionsettings change column `elevation_1_nw` `elevation_1_nw` double NOT NULL; +alter table regionsettings change column `elevation_2_nw` `elevation_2_nw` double NOT NULL; +alter table regionsettings change column `elevation_1_ne` `elevation_1_ne` double NOT NULL; +alter table regionsettings change column `elevation_2_ne` `elevation_2_ne` double NOT NULL; +alter table regionsettings change column `elevation_1_se` `elevation_1_se` double NOT NULL; +alter table regionsettings change column `elevation_2_se` `elevation_2_se` double NOT NULL; +alter table regionsettings change column `elevation_1_sw` `elevation_1_sw` double NOT NULL; +alter table regionsettings change column `elevation_2_sw` `elevation_2_sw` double NOT NULL; +alter table regionsettings change column `water_height` `water_height` double NOT NULL; +alter table regionsettings change column `terrain_raise_limit` `terrain_raise_limit` double NOT NULL; +alter table regionsettings change column `terrain_lower_limit` `terrain_lower_limit` double NOT NULL; +alter table regionsettings change column `sun_position` `sun_position` double NOT NULL; + +COMMIT; + + +:VERSION 25 #--------------------- + +BEGIN; + +alter table prims change column `PositionX` `PositionX` double default NULL; +alter table prims change column `PositionY` `PositionY` double default NULL; +alter table prims change column `PositionZ` `PositionZ` double default NULL; +alter table prims change column `GroupPositionX` `GroupPositionX` double default NULL; +alter table prims change column `GroupPositionY` `GroupPositionY` double default NULL; +alter table prims change column `GroupPositionZ` `GroupPositionZ` double default NULL; +alter table prims change column `VelocityX` `VelocityX` double default NULL; +alter table prims change column `VelocityY` `VelocityY` double default NULL; +alter table prims change column `VelocityZ` `VelocityZ` double default NULL; +alter table prims change column `AngularVelocityX` `AngularVelocityX` double default NULL; +alter table prims change column `AngularVelocityY` `AngularVelocityY` double default NULL; +alter table prims change column `AngularVelocityZ` `AngularVelocityZ` double default NULL; +alter table prims change column `AccelerationX` `AccelerationX` double default NULL; +alter table prims change column `AccelerationY` `AccelerationY` double default NULL; +alter table prims change column `AccelerationZ` `AccelerationZ` double default NULL; +alter table prims change column `RotationX` `RotationX` double default NULL; +alter table prims change column `RotationY` `RotationY` double default NULL; +alter table prims change column `RotationZ` `RotationZ` double default NULL; +alter table prims change column `RotationW` `RotationW` double default NULL; +alter table prims change column `SitTargetOffsetX` `SitTargetOffsetX` double default NULL; +alter table prims change column `SitTargetOffsetY` `SitTargetOffsetY` double default NULL; +alter table prims change column `SitTargetOffsetZ` `SitTargetOffsetZ` double default NULL; +alter table prims change column `SitTargetOrientW` `SitTargetOrientW` double default NULL; +alter table prims change column `SitTargetOrientX` `SitTargetOrientX` double default NULL; +alter table prims change column `SitTargetOrientY` `SitTargetOrientY` double default NULL; +alter table prims change column `SitTargetOrientZ` `SitTargetOrientZ` double default NULL; +alter table prims change column `LoopedSoundGain` `LoopedSoundGain` double NOT NULL default '0'; +alter table prims change column `OmegaX` `OmegaX` double NOT NULL default '0'; +alter table prims change column `OmegaY` `OmegaY` double NOT NULL default '0'; +alter table prims change column `OmegaZ` `OmegaZ` double NOT NULL default '0'; +alter table prims change column `CameraEyeOffsetX` `CameraEyeOffsetX` double NOT NULL default '0'; +alter table prims change column `CameraEyeOffsetY` `CameraEyeOffsetY` double NOT NULL default '0'; +alter table prims change column `CameraEyeOffsetZ` `CameraEyeOffsetZ` double NOT NULL default '0'; +alter table prims change column `CameraAtOffsetX` `CameraAtOffsetX` double NOT NULL default '0'; +alter table prims change column `CameraAtOffsetY` `CameraAtOffsetY` double NOT NULL default '0'; +alter table prims change column `CameraAtOffsetZ` `CameraAtOffsetZ` double NOT NULL default '0'; +alter table prims change column `CollisionSoundVolume` `CollisionSoundVolume` double NOT NULL default '0'; + +alter table primshapes change column `ScaleX` `ScaleX` double NOT NULL default '0'; +alter table primshapes change column `ScaleY` `ScaleY` double NOT NULL default '0'; +alter table primshapes change column `ScaleZ` `ScaleZ` double NOT NULL default '0'; + +COMMIT; + +:VERSION 26 #--------------------- + +begin; + +alter table prims change column `PositionX` `PositionX` double default NULL; +alter table prims change column `PositionY` `PositionY` double default NULL; +alter table prims change column `PositionZ` `PositionZ` double default NULL; +alter table prims change column `GroupPositionX` `GroupPositionX` double default NULL; +alter table prims change column `GroupPositionY` `GroupPositionY` double default NULL; +alter table prims change column `GroupPositionZ` `GroupPositionZ` double default NULL; +alter table prims change column `VelocityX` `VelocityX` double default NULL; +alter table prims change column `VelocityY` `VelocityY` double default NULL; +alter table prims change column `VelocityZ` `VelocityZ` double default NULL; +alter table prims change column `AngularVelocityX` `AngularVelocityX` double default NULL; +alter table prims change column `AngularVelocityY` `AngularVelocityY` double default NULL; +alter table prims change column `AngularVelocityZ` `AngularVelocityZ` double default NULL; +alter table prims change column `AccelerationX` `AccelerationX` double default NULL; +alter table prims change column `AccelerationY` `AccelerationY` double default NULL; +alter table prims change column `AccelerationZ` `AccelerationZ` double default NULL; +alter table prims change column `RotationX` `RotationX` double default NULL; +alter table prims change column `RotationY` `RotationY` double default NULL; +alter table prims change column `RotationZ` `RotationZ` double default NULL; +alter table prims change column `RotationW` `RotationW` double default NULL; +alter table prims change column `SitTargetOffsetX` `SitTargetOffsetX` double default NULL; +alter table prims change column `SitTargetOffsetY` `SitTargetOffsetY` double default NULL; +alter table prims change column `SitTargetOffsetZ` `SitTargetOffsetZ` double default NULL; +alter table prims change column `SitTargetOrientW` `SitTargetOrientW` double default NULL; +alter table prims change column `SitTargetOrientX` `SitTargetOrientX` double default NULL; +alter table prims change column `SitTargetOrientY` `SitTargetOrientY` double default NULL; +alter table prims change column `SitTargetOrientZ` `SitTargetOrientZ` double default NULL; +alter table prims change column `LoopedSoundGain` `LoopedSoundGain` double NOT NULL default '0'; +alter table prims change column `OmegaX` `OmegaX` double NOT NULL default '0'; +alter table prims change column `OmegaY` `OmegaY` double NOT NULL default '0'; +alter table prims change column `OmegaZ` `OmegaZ` double NOT NULL default '0'; +alter table prims change column `CameraEyeOffsetX` `CameraEyeOffsetX` double NOT NULL default '0'; +alter table prims change column `CameraEyeOffsetY` `CameraEyeOffsetY` double NOT NULL default '0'; +alter table prims change column `CameraEyeOffsetZ` `CameraEyeOffsetZ` double NOT NULL default '0'; +alter table prims change column `CameraAtOffsetX` `CameraAtOffsetX` double NOT NULL default '0'; +alter table prims change column `CameraAtOffsetY` `CameraAtOffsetY` double NOT NULL default '0'; +alter table prims change column `CameraAtOffsetZ` `CameraAtOffsetZ` double NOT NULL default '0'; +alter table prims change column `CollisionSoundVolume` `CollisionSoundVolume` double NOT NULL default '0'; + +commit; + +:VERSION 27 #--------------------- + +BEGIN; + +ALTER TABLE prims DROP COLUMN ParentID; + +COMMIT; + +:VERSION 28 #--------------------- + +BEGIN; + +update terrain + set RegionUUID = concat(substr(RegionUUID, 1, 8), "-", substr(RegionUUID, 9, 4), "-", substr(RegionUUID, 13, 4), "-", substr(RegionUUID, 17, 4), "-", substr(RegionUUID, 21, 12)) + where RegionUUID not like '%-%'; + + +update landaccesslist + set LandUUID = concat(substr(LandUUID, 1, 8), "-", substr(LandUUID, 9, 4), "-", substr(LandUUID, 13, 4), "-", substr(LandUUID, 17, 4), "-", substr(LandUUID, 21, 12)) + where LandUUID not like '%-%'; + +update landaccesslist + set AccessUUID = concat(substr(AccessUUID, 1, 8), "-", substr(AccessUUID, 9, 4), "-", substr(AccessUUID, 13, 4), "-", substr(AccessUUID, 17, 4), "-", substr(AccessUUID, 21, 12)) + where AccessUUID not like '%-%'; + + +update prims + set UUID = concat(substr(UUID, 1, 8), "-", substr(UUID, 9, 4), "-", substr(UUID, 13, 4), "-", substr(UUID, 17, 4), "-", substr(UUID, 21, 12)) + where UUID not like '%-%'; + +update prims + set RegionUUID = concat(substr(RegionUUID, 1, 8), "-", substr(RegionUUID, 9, 4), "-", substr(RegionUUID, 13, 4), "-", substr(RegionUUID, 17, 4), "-", substr(RegionUUID, 21, 12)) + where RegionUUID not like '%-%'; + +update prims + set SceneGroupID = concat(substr(SceneGroupID, 1, 8), "-", substr(SceneGroupID, 9, 4), "-", substr(SceneGroupID, 13, 4), "-", substr(SceneGroupID, 17, 4), "-", substr(SceneGroupID, 21, 12)) + where SceneGroupID not like '%-%'; + +update prims + set CreatorID = concat(substr(CreatorID, 1, 8), "-", substr(CreatorID, 9, 4), "-", substr(CreatorID, 13, 4), "-", substr(CreatorID, 17, 4), "-", substr(CreatorID, 21, 12)) + where CreatorID not like '%-%'; + +update prims + set OwnerID = concat(substr(OwnerID, 1, 8), "-", substr(OwnerID, 9, 4), "-", substr(OwnerID, 13, 4), "-", substr(OwnerID, 17, 4), "-", substr(OwnerID, 21, 12)) + where OwnerID not like '%-%'; + +update prims + set GroupID = concat(substr(GroupID, 1, 8), "-", substr(GroupID, 9, 4), "-", substr(GroupID, 13, 4), "-", substr(GroupID, 17, 4), "-", substr(GroupID, 21, 12)) + where GroupID not like '%-%'; + +update prims + set LastOwnerID = concat(substr(LastOwnerID, 1, 8), "-", substr(LastOwnerID, 9, 4), "-", substr(LastOwnerID, 13, 4), "-", substr(LastOwnerID, 17, 4), "-", substr(LastOwnerID, 21, 12)) + where LastOwnerID not like '%-%'; + + +update primshapes + set UUID = concat(substr(UUID, 1, 8), "-", substr(UUID, 9, 4), "-", substr(UUID, 13, 4), "-", substr(UUID, 17, 4), "-", substr(UUID, 21, 12)) + where UUID not like '%-%'; + + +update land + set UUID = concat(substr(UUID, 1, 8), "-", substr(UUID, 9, 4), "-", substr(UUID, 13, 4), "-", substr(UUID, 17, 4), "-", substr(UUID, 21, 12)) + where UUID not like '%-%'; + +update land + set RegionUUID = concat(substr(RegionUUID, 1, 8), "-", substr(RegionUUID, 9, 4), "-", substr(RegionUUID, 13, 4), "-", substr(RegionUUID, 17, 4), "-", substr(RegionUUID, 21, 12)) + where RegionUUID not like '%-%'; + +update land + set OwnerUUID = concat(substr(OwnerUUID, 1, 8), "-", substr(OwnerUUID, 9, 4), "-", substr(OwnerUUID, 13, 4), "-", substr(OwnerUUID, 17, 4), "-", substr(OwnerUUID, 21, 12)) + where OwnerUUID not like '%-%'; + +update land + set GroupUUID = concat(substr(GroupUUID, 1, 8), "-", substr(GroupUUID, 9, 4), "-", substr(GroupUUID, 13, 4), "-", substr(GroupUUID, 17, 4), "-", substr(GroupUUID, 21, 12)) + where GroupUUID not like '%-%'; + +update land + set MediaTextureUUID = concat(substr(MediaTextureUUID, 1, 8), "-", substr(MediaTextureUUID, 9, 4), "-", substr(MediaTextureUUID, 13, 4), "-", substr(MediaTextureUUID, 17, 4), "-", substr(MediaTextureUUID, 21, 12)) + where MediaTextureUUID not like '%-%'; + +update land + set SnapshotUUID = concat(substr(SnapshotUUID, 1, 8), "-", substr(SnapshotUUID, 9, 4), "-", substr(SnapshotUUID, 13, 4), "-", substr(SnapshotUUID, 17, 4), "-", substr(SnapshotUUID, 21, 12)) + where SnapshotUUID not like '%-%'; + +update land + set AuthbuyerID = concat(substr(AuthbuyerID, 1, 8), "-", substr(AuthbuyerID, 9, 4), "-", substr(AuthbuyerID, 13, 4), "-", substr(AuthbuyerID, 17, 4), "-", substr(AuthbuyerID, 21, 12)) + where AuthbuyerID not like '%-%'; + +COMMIT; + +:VERSION 29 #--------------------- + +BEGIN; + +ALTER TABLE prims ADD COLUMN PassTouches tinyint not null default 0; + +COMMIT; + +:VERSION 30 #--------------------- + +BEGIN; + +ALTER TABLE regionsettings ADD COLUMN loaded_creation_date varchar(20) default NULL; +ALTER TABLE regionsettings ADD COLUMN loaded_creation_time varchar(20) default NULL; +ALTER TABLE regionsettings ADD COLUMN loaded_creation_id varchar(64) default NULL; + +COMMIT; + +:VERSION 31 #--------------------- + +BEGIN; + +ALTER TABLE regionsettings DROP COLUMN loaded_creation_date; +ALTER TABLE regionsettings DROP COLUMN loaded_creation_time; +ALTER TABLE regionsettings ADD COLUMN loaded_creation_datetime int unsigned NOT NULL default 0; + +COMMIT; + +:VERSION 33 #--------------------- + +BEGIN; +ALTER TABLE regionsettings ADD map_tile_ID CHAR(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000'; +COMMIT; + diff --git a/OpenSim/Data/MySQL/Resources/UserAccount.migrations b/OpenSim/Data/MySQL/Resources/UserAccount.migrations new file mode 100644 index 0000000000..84011e6e49 --- /dev/null +++ b/OpenSim/Data/MySQL/Resources/UserAccount.migrations @@ -0,0 +1,47 @@ +:VERSION 1 # ------------------------- + +BEGIN; + +CREATE TABLE `UserAccounts` ( + `PrincipalID` CHAR(36) NOT NULL, + `ScopeID` CHAR(36) NOT NULL, + `FirstName` VARCHAR(64) NOT NULL, + `LastName` VARCHAR(64) NOT NULL, + `Email` VARCHAR(64), + `ServiceURLs` TEXT, + `Created` INT(11) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +COMMIT; + +:VERSION 2 # ------------------------- + +BEGIN; + +INSERT INTO UserAccounts (PrincipalID, ScopeID, FirstName, LastName, Email, ServiceURLs, Created) SELECT `UUID` AS PrincipalID, '00000000-0000-0000-0000-000000000000' AS ScopeID, username AS FirstName, lastname AS LastName, email as Email, CONCAT('AssetServerURI=', userAssetURI, ' InventoryServerURI=', userInventoryURI, ' GatewayURI= HomeURI=') AS ServiceURLs, created as Created FROM users; + +COMMIT; + +:VERSION 3 # ------------------------- + +BEGIN; + +CREATE UNIQUE INDEX PrincipalID ON UserAccounts(PrincipalID); +CREATE INDEX Email ON UserAccounts(Email); +CREATE INDEX FirstName ON UserAccounts(FirstName); +CREATE INDEX LastName ON UserAccounts(LastName); +CREATE INDEX Name ON UserAccounts(FirstName,LastName); + +COMMIT; + +:VERSION 4 # ------------------------- + +BEGIN; + +ALTER TABLE UserAccounts ADD COLUMN UserLevel integer NOT NULL DEFAULT 0; +ALTER TABLE UserAccounts ADD COLUMN UserFlags integer NOT NULL DEFAULT 0; +ALTER TABLE UserAccounts ADD COLUMN UserTitle varchar(64) NOT NULL DEFAULT ''; + +COMMIT; + + diff --git a/OpenSim/Data/MySQL/Resources/001_UserStore.sql b/OpenSim/Data/MySQL/Resources/UserStore.migrations similarity index 72% rename from OpenSim/Data/MySQL/Resources/001_UserStore.sql rename to OpenSim/Data/MySQL/Resources/UserStore.migrations index 29ebc7d88b..f054611f04 100644 --- a/OpenSim/Data/MySQL/Resources/001_UserStore.sql +++ b/OpenSim/Data/MySQL/Resources/UserStore.migrations @@ -1,3 +1,5 @@ +:VERSION 1 # ----------------------------- + BEGIN; SET FOREIGN_KEY_CHECKS=0; @@ -104,4 +106,63 @@ CREATE TABLE `users` ( -- ---------------------------- -- Records -- ---------------------------- -COMMIT; \ No newline at end of file +COMMIT; + +:VERSION 2 # ----------------------------- + +BEGIN; + +ALTER TABLE users add homeRegionID char(36) NOT NULL default '00000000-0000-0000-0000-000000000000'; + +COMMIT; + +:VERSION 3 # ----------------------------- + +BEGIN; + +ALTER TABLE users add userFlags integer NOT NULL default 0; +ALTER TABLE users add godLevel integer NOT NULL default 0; + +COMMIT; + +:VERSION 4 # ----------------------------- + +BEGIN; + +ALTER TABLE users add customType varchar(32) not null default ''; +ALTER TABLE users add partner char(36) not null default '00000000-0000-0000-0000-000000000000'; + +COMMIT; + +:VERSION 5 # ----------------------------- + +BEGIN; + +CREATE TABLE `avatarattachments` (`UUID` char(36) NOT NULL, `attachpoint` int(11) NOT NULL, `item` char(36) NOT NULL, `asset` char(36) NOT NULL) ENGINE=InnoDB; + +COMMIT; + +:VERSION 6 # ----------------------------- + +BEGIN; + +ALTER TABLE agents add currentLookAt varchar(36) not null default ''; + +COMMIT; + +:VERSION 7 # ----------------------------- + +BEGIN; + +ALTER TABLE users add email varchar(250); + +COMMIT; + +:VERSION 8 # ----------------------------- + +BEGIN; + +ALTER TABLE users add scopeID char(36) not null default '00000000-0000-0000-0000-000000000000'; + +COMMIT; + diff --git a/OpenSim/Data/MySQL/Tests/MySQLEstateTest.cs b/OpenSim/Data/MySQL/Tests/MySQLEstateTest.cs deleted file mode 100644 index 01afcae34d..0000000000 --- a/OpenSim/Data/MySQL/Tests/MySQLEstateTest.cs +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using NUnit.Framework; -using OpenSim.Data.Tests; -using log4net; -using System.Reflection; -using OpenSim.Tests.Common; -using MySql.Data.MySqlClient; - - -namespace OpenSim.Data.MySQL.Tests -{ - [TestFixture, DatabaseTest] - public class MySQLEstateTest : BasicEstateTest - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - public string file; - public string connect = "Server=localhost;Port=3306;Database=opensim-nunit;User ID=opensim-nunit;Password=opensim-nunit;Pooling=false;"; - - [TestFixtureSetUp] - public void Init() - { - SuperInit(); - // If we manage to connect to the database with the user - // and password above it is our test database, and run - // these tests. If anything goes wrong, ignore these - // tests. - try - { - // clear db incase to ensure we are in a clean state - ClearDB(); - - regionDb = new MySQLDataStore(); - regionDb.Initialise(connect); - db = new MySQLEstateStore(); - db.Initialise(connect); - } - catch (Exception e) - { - m_log.Error("Exception {0}", e); - Assert.Ignore(); - } - } - - [TestFixtureTearDown] - public void Cleanup() - { - if (regionDb != null) - { - regionDb.Dispose(); - } - ClearDB(); - } - - private void ClearDB() - { - // if a new table is added, it has to be dropped here - ExecuteSql("drop table if exists migrations"); - ExecuteSql("drop table if exists prims"); - ExecuteSql("drop table if exists primshapes"); - ExecuteSql("drop table if exists primitems"); - ExecuteSql("drop table if exists terrain"); - ExecuteSql("drop table if exists land"); - ExecuteSql("drop table if exists landaccesslist"); - ExecuteSql("drop table if exists regionban"); - ExecuteSql("drop table if exists regionsettings"); - ExecuteSql("drop table if exists estate_managers"); - ExecuteSql("drop table if exists estate_groups"); - ExecuteSql("drop table if exists estate_users"); - ExecuteSql("drop table if exists estateban"); - ExecuteSql("drop table if exists estate_settings"); - ExecuteSql("drop table if exists estate_map"); - } - - /// - /// Execute a MySqlCommand - /// - /// sql string to execute - private void ExecuteSql(string sql) - { - using (MySqlConnection dbcon = new MySqlConnection(connect)) - { - dbcon.Open(); - - MySqlCommand cmd = new MySqlCommand(sql, dbcon); - cmd.ExecuteNonQuery(); - } - } - } -} diff --git a/OpenSim/Data/MySQL/Tests/MySQLInventoryTest.cs b/OpenSim/Data/MySQL/Tests/MySQLInventoryTest.cs deleted file mode 100644 index 4575493bd7..0000000000 --- a/OpenSim/Data/MySQL/Tests/MySQLInventoryTest.cs +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using NUnit.Framework; -using OpenSim.Data.Tests; -using log4net; -using System.Reflection; -using OpenSim.Tests.Common; -using MySql.Data.MySqlClient; - - -namespace OpenSim.Data.MySQL.Tests -{ - [TestFixture, DatabaseTest] - public class MySQLInventoryTest : BasicInventoryTest - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - public string file; - public string connect = "Server=localhost;Port=3306;Database=opensim-nunit;User ID=opensim-nunit;Password=opensim-nunit;Pooling=false;"; - - [TestFixtureSetUp] - public void Init() - { - SuperInit(); - // If we manage to connect to the database with the user - // and password above it is our test database, and run - // these tests. If anything goes wrong, ignore these - // tests. - try - { - DropTables(); - db = new MySQLInventoryData(); - db.Initialise(connect); - } - catch (Exception e) - { - m_log.Error("Exception {0}", e); - Assert.Ignore(); - } - } - - [TestFixtureTearDown] - public void Cleanup() - { - if (db != null) - { - db.Dispose(); - } - DropTables(); - } - - private void DropTables() - { - ExecuteSql("drop table IF EXISTS inventoryitems"); - ExecuteSql("drop table IF EXISTS inventoryfolders"); - ExecuteSql("drop table IF EXISTS migrations"); - } - - /// - /// Execute a MySqlCommand - /// - /// sql string to execute - private void ExecuteSql(string sql) - { - using (MySqlConnection dbcon = new MySqlConnection(connect)) - { - dbcon.Open(); - - MySqlCommand cmd = new MySqlCommand(sql, dbcon); - cmd.ExecuteNonQuery(); - } - } - } -} diff --git a/OpenSim/Data/MySQL/Tests/MySQLRegionTest.cs b/OpenSim/Data/MySQL/Tests/MySQLRegionTest.cs deleted file mode 100644 index e7e57e477e..0000000000 --- a/OpenSim/Data/MySQL/Tests/MySQLRegionTest.cs +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using NUnit.Framework; -using OpenSim.Data.Tests; -using log4net; -using System.Reflection; -using OpenSim.Tests.Common; -using MySql.Data.MySqlClient; - -namespace OpenSim.Data.MySQL.Tests -{ - [TestFixture, DatabaseTest] - public class MySQLRegionTest : BasicRegionTest - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - public string file; - public string connect = "Server=localhost;Port=3306;Database=opensim-nunit;User ID=opensim-nunit;Password=opensim-nunit;Pooling=false;"; - - [TestFixtureSetUp] - public void Init() - { - SuperInit(); - // If we manage to connect to the database with the user - // and password above it is our test database, and run - // these tests. If anything goes wrong, ignore these - // tests. - try - { - // this is important in case a previous run ended badly - ClearDB(); - - db = new MySQLDataStore(); - db.Initialise(connect); - } - catch (Exception e) - { - m_log.Error("Exception {0}", e); - Assert.Ignore(); - } - } - - [TestFixtureTearDown] - public void Cleanup() - { - if (db != null) - { - db.Dispose(); - } - ClearDB(); - } - - private void ClearDB() - { - ExecuteSql("drop table if exists migrations"); - ExecuteSql("drop table if exists prims"); - ExecuteSql("drop table if exists primshapes"); - ExecuteSql("drop table if exists primitems"); - ExecuteSql("drop table if exists terrain"); - ExecuteSql("drop table if exists land"); - ExecuteSql("drop table if exists landaccesslist"); - ExecuteSql("drop table if exists regionban"); - ExecuteSql("drop table if exists regionsettings"); - ExecuteSql("drop table if exists estate_managers"); - ExecuteSql("drop table if exists estate_groups"); - ExecuteSql("drop table if exists estate_users"); - ExecuteSql("drop table if exists estateban"); - ExecuteSql("drop table if exists estate_settings"); - ExecuteSql("drop table if exists estate_map"); - } - - /// - /// Execute a MySqlCommand - /// - /// sql string to execute - private void ExecuteSql(string sql) - { - using (MySqlConnection dbcon = new MySqlConnection(connect)) - { - dbcon.Open(); - - MySqlCommand cmd = new MySqlCommand(sql, dbcon); - cmd.ExecuteNonQuery(); - } - } - } -} diff --git a/OpenSim/Data/Null/NullPresenceData.cs b/OpenSim/Data/Null/NullPresenceData.cs index b98b5c92b5..91f1cc561e 100644 --- a/OpenSim/Data/Null/NullPresenceData.cs +++ b/OpenSim/Data/Null/NullPresenceData.cs @@ -96,45 +96,20 @@ namespace OpenSim.Data.Null m_presenceData.Remove(u); } - public bool ReportAgent(UUID sessionID, UUID regionID, string position, string lookAt) + public bool ReportAgent(UUID sessionID, UUID regionID) { if (Instance != this) - return Instance.ReportAgent(sessionID, regionID, position, lookAt); + return Instance.ReportAgent(sessionID, regionID); if (m_presenceData.ContainsKey(sessionID)) { m_presenceData[sessionID].RegionID = regionID; - m_presenceData[sessionID].Data["Position"] = position; - m_presenceData[sessionID].Data["LookAt"] = lookAt; return true; } return false; } - public bool SetHomeLocation(string userID, UUID regionID, Vector3 position, Vector3 lookAt) - { - if (Instance != this) - return Instance.SetHomeLocation(userID, regionID, position, lookAt); - - bool foundone = false; - foreach (PresenceData p in m_presenceData.Values) - { - if (p.UserID == userID) - { -// m_log.DebugFormat( -// "[NULL PRESENCE DATA]: Setting home location {0} {1} {2} for {3}", -// regionID, position, lookAt, p.UserID); - - p.Data["HomeRegionID"] = regionID.ToString(); - p.Data["HomePosition"] = position.ToString(); - p.Data["HomeLookAt"] = lookAt.ToString(); - foundone = true; - } - } - - return foundone; - } public PresenceData[] Get(string field, string data) { @@ -193,39 +168,6 @@ namespace OpenSim.Data.Null return presences.ToArray(); } - public void Prune(string userID) - { - if (Instance != this) - { - Instance.Prune(userID); - return; - } - -// m_log.DebugFormat("[NULL PRESENCE DATA]: Prune called for {0}", userID); - - List deleteSessions = new List(); - int online = 0; - - foreach (KeyValuePair kvp in m_presenceData) - { -// m_log.DebugFormat("Online: {0}", kvp.Value.Data["Online"]); - - bool on = false; - if (bool.TryParse(kvp.Value.Data["Online"], out on) && on) - online++; - else - deleteSessions.Add(kvp.Key); - } - -// m_log.DebugFormat("[NULL PRESENCE DATA]: online [{0}], deleteSession.Count [{1}]", online, deleteSessions.Count); - - // Leave one session behind so that we can pick up details such as home location - if (online == 0 && deleteSessions.Count > 0) - deleteSessions.RemoveAt(0); - - foreach (UUID s in deleteSessions) - m_presenceData.Remove(s); - } public bool Delete(string field, string data) { diff --git a/OpenSim/Data/Null/NullRegionData.cs b/OpenSim/Data/Null/NullRegionData.cs index 30ad747d25..d596698127 100644 --- a/OpenSim/Data/Null/NullRegionData.cs +++ b/OpenSim/Data/Null/NullRegionData.cs @@ -40,7 +40,7 @@ namespace OpenSim.Data.Null { private static NullRegionData Instance = null; -// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); Dictionary m_regionData = new Dictionary(); @@ -62,12 +62,14 @@ namespace OpenSim.Data.Null { if (regionName.Contains("%")) { - if (r.RegionName.Contains(regionName.Replace("%", ""))) + string cleanname = regionName.Replace("%", ""); + m_log.DebugFormat("[NULL REGION DATA]: comparing {0} to {1}", cleanname.ToLower(), r.RegionName.ToLower()); + if (r.RegionName.ToLower().Contains(cleanname.ToLower())) ret.Add(r); } else { - if (r.RegionName == regionName) + if (r.RegionName.ToLower() == regionName.ToLower()) ret.Add(r); } } diff --git a/OpenSim/Data/SQLite/Resources/001_GridUserStore.sql b/OpenSim/Data/SQLite/Resources/001_GridUserStore.sql new file mode 100644 index 0000000000..1a24613275 --- /dev/null +++ b/OpenSim/Data/SQLite/Resources/001_GridUserStore.sql @@ -0,0 +1,16 @@ +BEGIN TRANSACTION; + +CREATE TABLE GridUser ( + UserID VARCHAR(255) primary key, + HomeRegionID CHAR(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000', + HomePosition CHAR(64) NOT NULL DEFAULT '<0,0,0>', + HomeLookAt CHAR(64) NOT NULL DEFAULT '<0,0,0>', + LastRegionID CHAR(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000', + LastPosition CHAR(64) NOT NULL DEFAULT '<0,0,0>', + LastLookAt CHAR(64) NOT NULL DEFAULT '<0,0,0>', + Online CHAR(5) NOT NULL DEFAULT 'false', + Login CHAR(16) NOT NULL DEFAULT '0', + Logout CHAR(16) NOT NULL DEFAULT '0' +) ; + +COMMIT; diff --git a/OpenSim/Data/SQLite/Resources/001_XInventoryStore.sql b/OpenSim/Data/SQLite/Resources/001_XInventoryStore.sql new file mode 100644 index 0000000000..7e21996ed9 --- /dev/null +++ b/OpenSim/Data/SQLite/Resources/001_XInventoryStore.sql @@ -0,0 +1,38 @@ +BEGIN TRANSACTION; + +CREATE TABLE inventoryfolders( + folderName varchar(255), + type integer, + version integer, + folderID varchar(255) primary key, + agentID varchar(255) not null default '00000000-0000-0000-0000-000000000000', + parentFolderID varchar(255) not null default '00000000-0000-0000-0000-000000000000'); + +CREATE TABLE inventoryitems( + assetID varchar(255), + assetType integer, + inventoryName varchar(255), + inventoryDescription varchar(255), + inventoryNextPermissions integer, + inventoryCurrentPermissions integer, + invType integer, + creatorID varchar(255), + inventoryBasePermissions integer, + inventoryEveryOnePermissions integer, + salePrice integer default 99, + saleType integer default 0, + creationDate integer default 2000, + groupID varchar(255) default '00000000-0000-0000-0000-000000000000', + groupOwned integer default 0, + flags integer default 0, + inventoryID varchar(255) primary key, + parentFolderID varchar(255) not null default '00000000-0000-0000-0000-000000000000', + avatarID varchar(255) not null default '00000000-0000-0000-0000-000000000000', + inventoryGroupPermissions integer not null default 0); + +create index inventoryfolders_agentid on inventoryfolders(agentID); +create index inventoryfolders_parentid on inventoryfolders(parentFolderID); +create index inventoryitems_parentfolderid on inventoryitems(parentFolderID); +create index inventoryitems_avatarid on inventoryitems(avatarID); + +COMMIT; diff --git a/OpenSim/Data/SQLite/Resources/002_XInventoryStore.sql b/OpenSim/Data/SQLite/Resources/002_XInventoryStore.sql new file mode 100644 index 0000000000..d38e2b77cc --- /dev/null +++ b/OpenSim/Data/SQLite/Resources/002_XInventoryStore.sql @@ -0,0 +1,8 @@ +ATTACH 'inventoryStore.db' AS old; + +BEGIN TRANSACTION; + +INSERT INTO inventoryfolders (folderName, type, version, folderID, agentID, parentFolderID) SELECT `name` AS folderName, `type` AS type, `version` AS version, `UUID` AS folderID, `agentID` AS agentID, `parentID` AS parentFolderID from old.inventoryfolders; +INSERT INTO inventoryitems (assetID, assetType, inventoryName, inventoryDescription, inventoryNextPermissions, inventoryCurrentPermissions, invType, creatorID, inventoryBasePermissions, inventoryEveryOnePermissions, salePrice, saleType, creationDate, groupID, groupOwned, flags, inventoryID, parentFolderID, avatarID, inventoryGroupPermissions) SELECT `assetID`, `assetType` AS assetType, `inventoryName` AS inventoryName, `inventoryDescription` AS inventoryDescription, `inventoryNextPermissions` AS inventoryNextPermissions, `inventoryCurrentPermissions` AS inventoryCurrentPermissions, `invType` AS invType, `creatorsID` AS creatorID, `inventoryBasePermissions` AS inventoryBasePermissions, `inventoryEveryOnePermissions` AS inventoryEveryOnePermissions, `salePrice` AS salePrice, `saleType` AS saleType, `creationDate` AS creationDate, `groupID` AS groupID, `groupOwned` AS groupOwned, `flags` AS flags, `UUID` AS inventoryID, `parentFolderID` AS parentFolderID, `avatarID` AS avatarID, `inventoryGroupPermissions` AS inventoryGroupPermissions FROM old.inventoryitems; + +COMMIT; diff --git a/OpenSim/Data/SQLite/Resources/003_InventoryStore.sql b/OpenSim/Data/SQLite/Resources/003_InventoryStore.sql deleted file mode 100644 index 4c6da91aab..0000000000 --- a/OpenSim/Data/SQLite/Resources/003_InventoryStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN; - -alter table inventoryitems add column inventoryGroupPermissions integer unsigned not null default 0; - -COMMIT; diff --git a/OpenSim/Data/SQLite/Resources/003_UserStore.sql b/OpenSim/Data/SQLite/Resources/003_UserStore.sql deleted file mode 100644 index 6f890eeec1..0000000000 --- a/OpenSim/Data/SQLite/Resources/003_UserStore.sql +++ /dev/null @@ -1,6 +0,0 @@ -BEGIN; - -ALTER TABLE users add userFlags integer NOT NULL default 0; -ALTER TABLE users add godLevel integer NOT NULL default 0; - -COMMIT; diff --git a/OpenSim/Data/SQLite/Resources/004_UserStore.sql b/OpenSim/Data/SQLite/Resources/004_UserStore.sql deleted file mode 100644 index 03142afa37..0000000000 --- a/OpenSim/Data/SQLite/Resources/004_UserStore.sql +++ /dev/null @@ -1,6 +0,0 @@ -BEGIN; - -ALTER TABLE users add customType varchar(32) not null default ''; -ALTER TABLE users add partner char(36) not null default '00000000-0000-0000-0000-000000000000'; - -COMMIT; diff --git a/OpenSim/Data/SQLite/Resources/005_AssetStore.sql b/OpenSim/Data/SQLite/Resources/005_AssetStore.sql new file mode 100644 index 0000000000..f06121abc1 --- /dev/null +++ b/OpenSim/Data/SQLite/Resources/005_AssetStore.sql @@ -0,0 +1,5 @@ +BEGIN; + +ALTER TABLE assets ADD COLUMN asset_flags INTEGER NOT NULL DEFAULT 0; + +COMMIT; diff --git a/OpenSim/Data/SQLite/Resources/019_RegionStore.sql b/OpenSim/Data/SQLite/Resources/019_RegionStore.sql new file mode 100644 index 0000000000..d62f8484b8 --- /dev/null +++ b/OpenSim/Data/SQLite/Resources/019_RegionStore.sql @@ -0,0 +1,5 @@ +BEGIN; + +ALTER TABLE regionsettings ADD COLUMN map_tile_ID varchar(36) NOT NULL default '00000000-0000-0000-0000-000000000000'; + +COMMIT; \ No newline at end of file diff --git a/OpenSim/Data/SQLite/Resources/AssetStore.migrations b/OpenSim/Data/SQLite/Resources/AssetStore.migrations new file mode 100644 index 0000000000..bc11e13d38 --- /dev/null +++ b/OpenSim/Data/SQLite/Resources/AssetStore.migrations @@ -0,0 +1,66 @@ +:VERSION 1 + +BEGIN TRANSACTION; +CREATE TABLE assets( + UUID varchar(255) primary key, + Name varchar(255), + Description varchar(255), + Type integer, + InvType integer, + Local integer, + Temporary integer, + Data blob); + +COMMIT; + +:VERSION 2 + +BEGIN TRANSACTION; + +CREATE TEMPORARY TABLE assets_backup(UUID,Name,Description,Type,Local,Temporary,Data); +INSERT INTO assets_backup SELECT UUID,Name,Description,Type,Local,Temporary,Data FROM assets; +DROP TABLE assets; +CREATE TABLE assets(UUID,Name,Description,Type,Local,Temporary,Data); +INSERT INTO assets SELECT UUID,Name,Description,Type,Local,Temporary,Data FROM assets_backup; +DROP TABLE assets_backup; + +COMMIT; + +:VERSION 3 + +DELETE FROM assets WHERE UUID = 'dc4b9f0bd00845c696a401dd947ac621' + +:VERSION 4 + +BEGIN; + +update assets + set UUID = substr(UUID, 1, 8) || "-" || substr(UUID, 9, 4) || "-" || substr(UUID, 13, 4) || "-" || substr(UUID, 17, 4) || "-" || substr(UUID, 21, 12) + where UUID not like '%-%'; + +COMMIT; + +:VERSION 5 + +BEGIN TRANSACTION; + +CREATE TEMPORARY TABLE assets_backup(UUID,Name,Description,Type,Local,Temporary,Data); +INSERT INTO assets_backup SELECT UUID,Name,Description,Type,Local,Temporary,Data FROM assets; +DROP TABLE assets; +CREATE TABLE assets( + UUID NOT NULL PRIMARY KEY, + Name, + Description, + Type, + Local, + Temporary, + asset_flags INTEGER NOT NULL DEFAULT 0, + CreatorID varchar(36) default '', + Data); + +INSERT INTO assets(UUID,Name,Description,Type,Local,Temporary,Data) +SELECT UUID,Name,Description,Type,Local,Temporary,Data FROM assets_backup; +DROP TABLE assets_backup; + +COMMIT; + diff --git a/OpenSim/Data/SQLite/Resources/AuthStore.migrations b/OpenSim/Data/SQLite/Resources/AuthStore.migrations new file mode 100644 index 0000000000..ca6bdf55a5 --- /dev/null +++ b/OpenSim/Data/SQLite/Resources/AuthStore.migrations @@ -0,0 +1,29 @@ +:VERSION 1 + +BEGIN TRANSACTION; + +CREATE TABLE auth ( + UUID char(36) NOT NULL, + passwordHash char(32) NOT NULL default '', + passwordSalt char(32) NOT NULL default '', + webLoginKey varchar(255) NOT NULL default '', + accountType VARCHAR(32) NOT NULL DEFAULT 'UserAccount', + PRIMARY KEY (`UUID`) +); + +CREATE TABLE tokens ( + UUID char(36) NOT NULL, + token varchar(255) NOT NULL, + validity datetime NOT NULL +); + +COMMIT; + +:VERSION 2 + +BEGIN TRANSACTION; + +INSERT INTO auth (UUID, passwordHash, passwordSalt, webLoginKey) SELECT `UUID` AS UUID, `passwordHash` AS passwordHash, `passwordSalt` AS passwordSalt, `webLoginKey` AS webLoginKey FROM users; + +COMMIT; + diff --git a/OpenSim/Data/SQLite/Resources/Avatar.migrations b/OpenSim/Data/SQLite/Resources/Avatar.migrations new file mode 100644 index 0000000000..13b41969ec --- /dev/null +++ b/OpenSim/Data/SQLite/Resources/Avatar.migrations @@ -0,0 +1,11 @@ +:VERSION 1 + +BEGIN TRANSACTION; + +CREATE TABLE Avatars ( + PrincipalID CHAR(36) NOT NULL, + Name VARCHAR(32) NOT NULL, + Value VARCHAR(255) NOT NULL DEFAULT '', + PRIMARY KEY(PrincipalID, Name)); + +COMMIT; diff --git a/OpenSim/Data/SQLite/Resources/EstateStore.migrations b/OpenSim/Data/SQLite/Resources/EstateStore.migrations new file mode 100644 index 0000000000..62f6464460 --- /dev/null +++ b/OpenSim/Data/SQLite/Resources/EstateStore.migrations @@ -0,0 +1,88 @@ +:VERSION 6 + +BEGIN TRANSACTION; + +CREATE TABLE estate_groups ( + EstateID int(10) NOT NULL, + uuid char(36) NOT NULL +); + +CREATE TABLE estate_managers ( + EstateID int(10) NOT NULL, + uuid char(36) NOT NULL +); + +CREATE TABLE estate_map ( + RegionID char(36) NOT NULL default '00000000-0000-0000-0000-000000000000', + EstateID int(11) NOT NULL +); + +CREATE TABLE estate_settings ( + EstateID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, + EstateName varchar(64) default NULL, + AbuseEmailToEstateOwner tinyint(4) NOT NULL, + DenyAnonymous tinyint(4) NOT NULL, + ResetHomeOnTeleport tinyint(4) NOT NULL, + FixedSun tinyint(4) NOT NULL, + DenyTransacted tinyint(4) NOT NULL, + BlockDwell tinyint(4) NOT NULL, + DenyIdentified tinyint(4) NOT NULL, + AllowVoice tinyint(4) NOT NULL, + UseGlobalTime tinyint(4) NOT NULL, + PricePerMeter int(11) NOT NULL, + TaxFree tinyint(4) NOT NULL, + AllowDirectTeleport tinyint(4) NOT NULL, + RedirectGridX int(11) NOT NULL, + RedirectGridY int(11) NOT NULL, + ParentEstateID int(10) NOT NULL, + SunPosition double NOT NULL, + EstateSkipScripts tinyint(4) NOT NULL, + BillableFactor float NOT NULL, + PublicAccess tinyint(4) NOT NULL +); + +insert into estate_settings ( + EstateID,EstateName,AbuseEmailToEstateOwner,DenyAnonymous,ResetHomeOnTeleport,FixedSun,DenyTransacted,BlockDwell,DenyIdentified,AllowVoice,UseGlobalTime,PricePerMeter,TaxFree,AllowDirectTeleport,RedirectGridX,RedirectGridY,ParentEstateID,SunPosition,PublicAccess,EstateSkipScripts,BillableFactor) + values ( 99, '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''); +delete from estate_settings; + +CREATE TABLE estate_users ( + EstateID int(10) NOT NULL, + uuid char(36) NOT NULL +); + +CREATE TABLE estateban ( + EstateID int(10) NOT NULL, + bannedUUID varchar(36) NOT NULL, + bannedIp varchar(16) NOT NULL, + bannedIpHostMask varchar(16) NOT NULL, + bannedNameMask varchar(64) default NULL +); + +CREATE INDEX estate_ban_estate_id on estateban(EstateID); +CREATE INDEX estate_groups_estate_id on estate_groups(EstateID); +CREATE INDEX estate_managers_estate_id on estate_managers(EstateID); +CREATE INDEX estate_map_estate_id on estate_map(EstateID); +CREATE UNIQUE INDEX estate_map_region_id on estate_map(RegionID); +CREATE INDEX estate_users_estate_id on estate_users(EstateID); + +COMMIT; + + +:VERSION 7 + +begin; + +alter table estate_settings add column AbuseEmail varchar(255) not null default ''; + +alter table estate_settings add column EstateOwner varchar(36) not null default ''; + +commit; + +:VERSION 8 + +begin; + +alter table estate_settings add column DenyMinors tinyint not null default 0; + +commit; diff --git a/OpenSim/Data/SQLite/Resources/FriendsStore.migrations b/OpenSim/Data/SQLite/Resources/FriendsStore.migrations new file mode 100644 index 0000000000..3eb4352a0c --- /dev/null +++ b/OpenSim/Data/SQLite/Resources/FriendsStore.migrations @@ -0,0 +1,20 @@ +:VERSION 1 + +BEGIN TRANSACTION; + +CREATE TABLE `Friends` ( + `PrincipalID` CHAR(36) NOT NULL, + `Friend` VARCHAR(255) NOT NULL, + `Flags` VARCHAR(16) NOT NULL DEFAULT 0, + `Offered` VARCHAR(32) NOT NULL DEFAULT 0, + PRIMARY KEY(`PrincipalID`, `Friend`)); + +COMMIT; + +:VERSION 2 + +BEGIN TRANSACTION; + +INSERT INTO `Friends` SELECT `ownerID`, `friendID`, `friendPerms`, 0 FROM `userfriends`; + +COMMIT; diff --git a/OpenSim/Data/SQLite/Resources/InventoryStore.migrations b/OpenSim/Data/SQLite/Resources/InventoryStore.migrations new file mode 100644 index 0000000000..585ac498e6 --- /dev/null +++ b/OpenSim/Data/SQLite/Resources/InventoryStore.migrations @@ -0,0 +1,92 @@ +:VERSION 1 + +BEGIN TRANSACTION; + +CREATE TABLE inventoryfolders( + UUID varchar(255) primary key, + name varchar(255), + agentID varchar(255), + parentID varchar(255), + type integer, + version integer); + +CREATE TABLE inventoryitems( + UUID varchar(255) primary key, + assetID varchar(255), + assetType integer, + invType integer, + parentFolderID varchar(255), + avatarID varchar(255), + creatorsID varchar(255), + inventoryName varchar(255), + inventoryDescription varchar(255), + inventoryNextPermissions integer, + inventoryCurrentPermissions integer, + inventoryBasePermissions integer, + inventoryEveryOnePermissions integer, + salePrice integer default 99, + saleType integer default 0, + creationDate integer default 2000, + groupID varchar(255) default '00000000-0000-0000-0000-000000000000', + groupOwned integer default 0, + flags integer default 0); + +COMMIT; + +:VERSION 2 + +BEGIN TRANSACTION; + +create index inventoryfolders_agentid on inventoryfolders(agentid); +create index inventoryfolders_parentid on inventoryfolders(parentid); +create index inventoryitems_parentfolderid on inventoryitems(parentfolderid); +create index inventoryitems_avatarid on inventoryitems(avatarid); + +COMMIT; + +:VERSION 3 + +BEGIN; + +alter table inventoryitems add column inventoryGroupPermissions integer unsigned not null default 0; + +COMMIT; + +:VERSION 4 + +BEGIN; + +update inventoryitems + set UUID = substr(UUID, 1, 8) || "-" || substr(UUID, 9, 4) || "-" || substr(UUID, 13, 4) || "-" || substr(UUID, 17, 4) || "-" || substr(UUID, 21, 12) + where UUID not like '%-%'; + +update inventoryitems + set assetID = substr(assetID, 1, 8) || "-" || substr(assetID, 9, 4) || "-" || substr(assetID, 13, 4) || "-" || substr(assetID, 17, 4) || "-" || substr(assetID, 21, 12) + where assetID not like '%-%'; + +update inventoryitems + set parentFolderID = substr(parentFolderID, 1, 8) || "-" || substr(parentFolderID, 9, 4) || "-" || substr(parentFolderID, 13, 4) || "-" || substr(parentFolderID, 17, 4) || "-" || substr(parentFolderID, 21, 12) + where parentFolderID not like '%-%'; + +update inventoryitems + set avatarID = substr(avatarID, 1, 8) || "-" || substr(avatarID, 9, 4) || "-" || substr(avatarID, 13, 4) || "-" || substr(avatarID, 17, 4) || "-" || substr(avatarID, 21, 12) + where avatarID not like '%-%'; + +update inventoryitems + set creatorsID = substr(creatorsID, 1, 8) || "-" || substr(creatorsID, 9, 4) || "-" || substr(creatorsID, 13, 4) || "-" || substr(creatorsID, 17, 4) || "-" || substr(creatorsID, 21, 12) + where creatorsID not like '%-%'; + + +update inventoryfolders + set UUID = substr(UUID, 1, 8) || "-" || substr(UUID, 9, 4) || "-" || substr(UUID, 13, 4) || "-" || substr(UUID, 17, 4) || "-" || substr(UUID, 21, 12) + where UUID not like '%-%'; + +update inventoryfolders + set agentID = substr(agentID, 1, 8) || "-" || substr(agentID, 9, 4) || "-" || substr(agentID, 13, 4) || "-" || substr(agentID, 17, 4) || "-" || substr(agentID, 21, 12) + where agentID not like '%-%'; + +update inventoryfolders + set parentID = substr(parentID, 1, 8) || "-" || substr(parentID, 9, 4) || "-" || substr(parentID, 13, 4) || "-" || substr(parentID, 17, 4) || "-" || substr(parentID, 21, 12) + where parentID not like '%-%'; + +COMMIT; diff --git a/OpenSim/Data/SQLite/Resources/RegionStore.migrations b/OpenSim/Data/SQLite/Resources/RegionStore.migrations new file mode 100644 index 0000000000..c47a85d026 --- /dev/null +++ b/OpenSim/Data/SQLite/Resources/RegionStore.migrations @@ -0,0 +1,501 @@ +:VERSION 1 + +BEGIN TRANSACTION; + +CREATE TABLE prims( + UUID varchar(255) primary key, + RegionUUID varchar(255), + ParentID integer, + CreationDate integer, + Name varchar(255), + SceneGroupID varchar(255), + Text varchar(255), + Description varchar(255), + SitName varchar(255), + TouchName varchar(255), + CreatorID varchar(255), + OwnerID varchar(255), + GroupID varchar(255), + LastOwnerID varchar(255), + OwnerMask integer, + NextOwnerMask integer, + GroupMask integer, + EveryoneMask integer, + BaseMask integer, + PositionX float, + PositionY float, + PositionZ float, + GroupPositionX float, + GroupPositionY float, + GroupPositionZ float, + VelocityX float, + VelocityY float, + VelocityZ float, + AngularVelocityX float, + AngularVelocityY float, + AngularVelocityZ float, + AccelerationX float, + AccelerationY float, + AccelerationZ float, + RotationX float, + RotationY float, + RotationZ float, + RotationW float, + ObjectFlags integer, + SitTargetOffsetX float NOT NULL default 0, + SitTargetOffsetY float NOT NULL default 0, + SitTargetOffsetZ float NOT NULL default 0, + SitTargetOrientW float NOT NULL default 0, + SitTargetOrientX float NOT NULL default 0, + SitTargetOrientY float NOT NULL default 0, + SitTargetOrientZ float NOT NULL default 0); + +CREATE TABLE primshapes( + UUID varchar(255) primary key, + Shape integer, + ScaleX float, + ScaleY float, + ScaleZ float, + PCode integer, + PathBegin integer, + PathEnd integer, + PathScaleX integer, + PathScaleY integer, + PathShearX integer, + PathShearY integer, + PathSkew integer, + PathCurve integer, + PathRadiusOffset integer, + PathRevolutions integer, + PathTaperX integer, + PathTaperY integer, + PathTwist integer, + PathTwistBegin integer, + ProfileBegin integer, + ProfileEnd integer, + ProfileCurve integer, + ProfileHollow integer, + Texture blob, + ExtraParams blob, + State Integer NOT NULL default 0); + +CREATE TABLE primitems( + itemID varchar(255) primary key, + primID varchar(255), + assetID varchar(255), + parentFolderID varchar(255), + invType integer, + assetType integer, + name varchar(255), + description varchar(255), + creationDate integer, + creatorID varchar(255), + ownerID varchar(255), + lastOwnerID varchar(255), + groupID varchar(255), + nextPermissions string, + currentPermissions string, + basePermissions string, + everyonePermissions string, + groupPermissions string); + +CREATE TABLE terrain( + RegionUUID varchar(255), + Revision integer, + Heightfield blob); + +CREATE TABLE land( + UUID varchar(255) primary key, + RegionUUID varchar(255), + LocalLandID string, + Bitmap blob, + Name varchar(255), + Desc varchar(255), + OwnerUUID varchar(255), + IsGroupOwned string, + Area integer, + AuctionID integer, + Category integer, + ClaimDate integer, + ClaimPrice integer, + GroupUUID varchar(255), + SalePrice integer, + LandStatus integer, + LandFlags string, + LandingType string, + MediaAutoScale string, + MediaTextureUUID varchar(255), + MediaURL varchar(255), + MusicURL varchar(255), + PassHours float, + PassPrice string, + SnapshotUUID varchar(255), + UserLocationX float, + UserLocationY float, + UserLocationZ float, + UserLookAtX float, + UserLookAtY float, + UserLookAtZ float, + AuthbuyerID varchar(36) NOT NULL default '00000000-0000-0000-0000-000000000000'); + +CREATE TABLE landaccesslist( + LandUUID varchar(255), + AccessUUID varchar(255), + Flags string); + +COMMIT; + +:VERSION 2 + +BEGIN TRANSACTION; + +CREATE TABLE regionban( + regionUUID varchar (255), + bannedUUID varchar (255), + bannedIp varchar (255), + bannedIpHostMask varchar (255) + ); + +COMMIT; + +:VERSION 3 + +BEGIN; + +ALTER TABLE primitems add flags integer not null default 0; + +COMMIT; + +:VERSION 4 + +BEGIN; + +create table regionsettings ( + regionUUID char(36) not null, + block_terraform integer not null, + block_fly integer not null, + allow_damage integer not null, + restrict_pushing integer not null, + allow_land_resell integer not null, + allow_land_join_divide integer not null, + block_show_in_search integer not null, + agent_limit integer not null, + object_bonus float not null, + maturity integer not null, + disable_scripts integer not null, + disable_collisions integer not null, + disable_physics integer not null, + terrain_texture_1 char(36) not null, + terrain_texture_2 char(36) not null, + terrain_texture_3 char(36) not null, + terrain_texture_4 char(36) not null, + elevation_1_nw float not null, + elevation_2_nw float not null, + elevation_1_ne float not null, + elevation_2_ne float not null, + elevation_1_se float not null, + elevation_2_se float not null, + elevation_1_sw float not null, + elevation_2_sw float not null, + water_height float not null, + terrain_raise_limit float not null, + terrain_lower_limit float not null, + use_estate_sun integer not null, + fixed_sun integer not null, + sun_position float not null, + covenant char(36)); + +COMMIT; + +:VERSION 5 + +BEGIN; + +delete from regionsettings; + +COMMIT; + +:VERSION 6 + +BEGIN TRANSACTION; + +CREATE TABLE estate_groups ( + EstateID int(10) NOT NULL, + uuid char(36) NOT NULL +); + +CREATE TABLE estate_managers ( + EstateID int(10) NOT NULL, + uuid char(36) NOT NULL +); + +CREATE TABLE estate_map ( + RegionID char(36) NOT NULL default '00000000-0000-0000-0000-000000000000', + EstateID int(11) NOT NULL +); + +CREATE TABLE estate_settings ( + EstateID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, + EstateName varchar(64) default NULL, + AbuseEmailToEstateOwner tinyint(4) NOT NULL, + DenyAnonymous tinyint(4) NOT NULL, + ResetHomeOnTeleport tinyint(4) NOT NULL, + FixedSun tinyint(4) NOT NULL, + DenyTransacted tinyint(4) NOT NULL, + BlockDwell tinyint(4) NOT NULL, + DenyIdentified tinyint(4) NOT NULL, + AllowVoice tinyint(4) NOT NULL, + UseGlobalTime tinyint(4) NOT NULL, + PricePerMeter int(11) NOT NULL, + TaxFree tinyint(4) NOT NULL, + AllowDirectTeleport tinyint(4) NOT NULL, + RedirectGridX int(11) NOT NULL, + RedirectGridY int(11) NOT NULL, + ParentEstateID int(10) NOT NULL, + SunPosition double NOT NULL, + EstateSkipScripts tinyint(4) NOT NULL, + BillableFactor float NOT NULL, + PublicAccess tinyint(4) NOT NULL +); +insert into estate_settings (EstateID,EstateName,AbuseEmailToEstateOwner,DenyAnonymous,ResetHomeOnTeleport,FixedSun,DenyTransacted,BlockDwell,DenyIdentified,AllowVoice,UseGlobalTime,PricePerMeter,TaxFree,AllowDirectTeleport,RedirectGridX,RedirectGridY,ParentEstateID,SunPosition,PublicAccess,EstateSkipScripts,BillableFactor) values ( 99, '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''); +delete from estate_settings; +CREATE TABLE estate_users ( + EstateID int(10) NOT NULL, + uuid char(36) NOT NULL +); + +CREATE TABLE estateban ( + EstateID int(10) NOT NULL, + bannedUUID varchar(36) NOT NULL, + bannedIp varchar(16) NOT NULL, + bannedIpHostMask varchar(16) NOT NULL, + bannedNameMask varchar(64) default NULL +); + +drop table regionsettings; +CREATE TABLE regionsettings ( + regionUUID char(36) NOT NULL, + block_terraform int(11) NOT NULL, + block_fly int(11) NOT NULL, + allow_damage int(11) NOT NULL, + restrict_pushing int(11) NOT NULL, + allow_land_resell int(11) NOT NULL, + allow_land_join_divide int(11) NOT NULL, + block_show_in_search int(11) NOT NULL, + agent_limit int(11) NOT NULL, + object_bonus float NOT NULL, + maturity int(11) NOT NULL, + disable_scripts int(11) NOT NULL, + disable_collisions int(11) NOT NULL, + disable_physics int(11) NOT NULL, + terrain_texture_1 char(36) NOT NULL, + terrain_texture_2 char(36) NOT NULL, + terrain_texture_3 char(36) NOT NULL, + terrain_texture_4 char(36) NOT NULL, + elevation_1_nw float NOT NULL, + elevation_2_nw float NOT NULL, + elevation_1_ne float NOT NULL, + elevation_2_ne float NOT NULL, + elevation_1_se float NOT NULL, + elevation_2_se float NOT NULL, + elevation_1_sw float NOT NULL, + elevation_2_sw float NOT NULL, + water_height float NOT NULL, + terrain_raise_limit float NOT NULL, + terrain_lower_limit float NOT NULL, + use_estate_sun int(11) NOT NULL, + fixed_sun int(11) NOT NULL, + sun_position float NOT NULL, + covenant char(36) default NULL, + Sandbox tinyint(4) NOT NULL, + PRIMARY KEY (regionUUID) +); + +COMMIT; + +:VERSION 9 + +BEGIN; + +ALTER TABLE prims ADD COLUMN ColorR integer not null default 0; +ALTER TABLE prims ADD COLUMN ColorG integer not null default 0; +ALTER TABLE prims ADD COLUMN ColorB integer not null default 0; +ALTER TABLE prims ADD COLUMN ColorA integer not null default 0; + +COMMIT; + +:VERSION 10 + +BEGIN; + +ALTER TABLE prims ADD COLUMN ClickAction INTEGER NOT NULL default 0; + +COMMIT; + +:VERSION 11 + +BEGIN; + +ALTER TABLE prims ADD COLUMN PayPrice INTEGER NOT NULL default 0; +ALTER TABLE prims ADD COLUMN PayButton1 INTEGER NOT NULL default 0; +ALTER TABLE prims ADD COLUMN PayButton2 INTEGER NOT NULL default 0; +ALTER TABLE prims ADD COLUMN PayButton3 INTEGER NOT NULL default 0; +ALTER TABLE prims ADD COLUMN PayButton4 INTEGER NOT NULL default 0; +ALTER TABLE prims ADD COLUMN LoopedSound varchar(36) NOT NULL default '00000000-0000-0000-0000-000000000000'; +ALTER TABLE prims ADD COLUMN LoopedSoundGain float NOT NULL default 0; +ALTER TABLE prims ADD COLUMN TextureAnimation string; +ALTER TABLE prims ADD COLUMN ParticleSystem string; +ALTER TABLE prims ADD COLUMN OmegaX float NOT NULL default 0; +ALTER TABLE prims ADD COLUMN OmegaY float NOT NULL default 0; +ALTER TABLE prims ADD COLUMN OmegaZ float NOT NULL default 0; +ALTER TABLE prims ADD COLUMN CameraEyeOffsetX float NOT NULL default 0; +ALTER TABLE prims ADD COLUMN CameraEyeOffsetY float NOT NULL default 0; +ALTER TABLE prims ADD COLUMN CameraEyeOffsetZ float NOT NULL default 0; +ALTER TABLE prims ADD COLUMN CameraAtOffsetX float NOT NULL default 0; +ALTER TABLE prims ADD COLUMN CameraAtOffsetY float NOT NULL default 0; +ALTER TABLE prims ADD COLUMN CameraAtOffsetZ float NOT NULL default 0; +ALTER TABLE prims ADD COLUMN ForceMouselook string NOT NULL default 0; +ALTER TABLE prims ADD COLUMN ScriptAccessPin INTEGER NOT NULL default 0; +ALTER TABLE prims ADD COLUMN AllowedDrop INTEGER NOT NULL default 0; +ALTER TABLE prims ADD COLUMN DieAtEdge string NOT NULL default 0; +ALTER TABLE prims ADD COLUMN SalePrice INTEGER NOT NULL default 0; +ALTER TABLE prims ADD COLUMN SaleType string NOT NULL default 0; + +COMMIT; + +:VERSION 12 + +BEGIN; + +ALTER TABLE prims ADD COLUMN Material INTEGER NOT NULL default 3; + +COMMIT; + +:VERSION 13 + +BEGIN; + +ALTER TABLE land ADD COLUMN OtherCleanTime INTEGER NOT NULL default 0; +ALTER TABLE land ADD COLUMN Dwell INTEGER NOT NULL default 0; + +COMMIT; + +:VERSION 14 + +begin; + +ALTER TABLE regionsettings ADD COLUMN sunvectorx double NOT NULL default 0; +ALTER TABLE regionsettings ADD COLUMN sunvectory double NOT NULL default 0; +ALTER TABLE regionsettings ADD COLUMN sunvectorz double NOT NULL default 0; + +commit; + +:VERSION 15 + +BEGIN; + +ALTER TABLE prims ADD COLUMN CollisionSound varchar(36) NOT NULL default '00000000-0000-0000-0000-000000000000'; +ALTER TABLE prims ADD COLUMN CollisionSoundVolume float NOT NULL default 0; + +COMMIT; + +:VERSION 16 + +BEGIN; + +ALTER TABLE prims ADD COLUMN VolumeDetect INTEGER NOT NULL DEFAULT 0; + +COMMIT; + +:VERSION 17 + +BEGIN; +CREATE TEMPORARY TABLE prims_backup(UUID,RegionUUID,CreationDate,Name,SceneGroupID,Text,Description,SitName,TouchName,CreatorID,OwnerID,GroupID,LastOwnerID,OwnerMask,NextOwnerMask,GroupMask,EveryoneMask,BaseMask,PositionX,PositionY,PositionZ,GroupPositionX,GroupPositionY,GroupPositionZ,VelocityX,VelocityY,VelocityZ,AngularVelocityX,AngularVelocityY,AngularVelocityZ,AccelerationX,AccelerationY,AccelerationZ,RotationX,RotationY,RotationZ,RotationW,ObjectFlags,SitTargetOffsetX,SitTargetOffsetY,SitTargetOffsetZ,SitTargetOrientW,SitTargetOrientX,SitTargetOrientY,SitTargetOrientZ,ColorR,ColorG,ColorB,ColorA,ClickAction,PayPrice,PayButton1,PayButton2,PayButton3,PayButton4,LoopedSound,LoopedSoundGain,TextureAnimation,ParticleSystem,OmegaX,OmegaY,OmegaZ,CameraEyeOffsetX,CameraEyeOffsetY,CameraEyeOffsetZ,CameraAtOffsetX,CameraAtOffsetY,CameraAtOffsetZ,ForceMouselook,ScriptAccessPin,AllowedDrop,DieAtEdge,SalePrice,SaleType,Material,CollisionSound,CollisionSoundVolume,VolumeDetect); +INSERT INTO prims_backup SELECT UUID,RegionUUID,CreationDate,Name,SceneGroupID,Text,Description,SitName,TouchName,CreatorID,OwnerID,GroupID,LastOwnerID,OwnerMask,NextOwnerMask,GroupMask,EveryoneMask,BaseMask,PositionX,PositionY,PositionZ,GroupPositionX,GroupPositionY,GroupPositionZ,VelocityX,VelocityY,VelocityZ,AngularVelocityX,AngularVelocityY,AngularVelocityZ,AccelerationX,AccelerationY,AccelerationZ,RotationX,RotationY,RotationZ,RotationW,ObjectFlags,SitTargetOffsetX,SitTargetOffsetY,SitTargetOffsetZ,SitTargetOrientW,SitTargetOrientX,SitTargetOrientY,SitTargetOrientZ,ColorR,ColorG,ColorB,ColorA,ClickAction,PayPrice,PayButton1,PayButton2,PayButton3,PayButton4,LoopedSound,LoopedSoundGain,TextureAnimation,ParticleSystem,OmegaX,OmegaY,OmegaZ,CameraEyeOffsetX,CameraEyeOffsetY,CameraEyeOffsetZ,CameraAtOffsetX,CameraAtOffsetY,CameraAtOffsetZ,ForceMouselook,ScriptAccessPin,AllowedDrop,DieAtEdge,SalePrice,SaleType,Material,CollisionSound,CollisionSoundVolume,VolumeDetect FROM prims; +DROP TABLE prims; +CREATE TABLE prims(UUID,RegionUUID,CreationDate,Name,SceneGroupID,Text,Description,SitName,TouchName,CreatorID,OwnerID,GroupID,LastOwnerID,OwnerMask,NextOwnerMask,GroupMask,EveryoneMask,BaseMask,PositionX,PositionY,PositionZ,GroupPositionX,GroupPositionY,GroupPositionZ,VelocityX,VelocityY,VelocityZ,AngularVelocityX,AngularVelocityY,AngularVelocityZ,AccelerationX,AccelerationY,AccelerationZ,RotationX,RotationY,RotationZ,RotationW,ObjectFlags,SitTargetOffsetX,SitTargetOffsetY,SitTargetOffsetZ,SitTargetOrientW,SitTargetOrientX,SitTargetOrientY,SitTargetOrientZ,ColorR,ColorG,ColorB,ColorA,ClickAction,PayPrice,PayButton1,PayButton2,PayButton3,PayButton4,LoopedSound,LoopedSoundGain,TextureAnimation,ParticleSystem,OmegaX,OmegaY,OmegaZ,CameraEyeOffsetX,CameraEyeOffsetY,CameraEyeOffsetZ,CameraAtOffsetX,CameraAtOffsetY,CameraAtOffsetZ,ForceMouselook,ScriptAccessPin,AllowedDrop,DieAtEdge,SalePrice,SaleType,Material,CollisionSound,CollisionSoundVolume,VolumeDetect); +INSERT INTO prims SELECT UUID,RegionUUID,CreationDate,Name,SceneGroupID,Text,Description,SitName,TouchName,CreatorID,OwnerID,GroupID,LastOwnerID,OwnerMask,NextOwnerMask,GroupMask,EveryoneMask,BaseMask,PositionX,PositionY,PositionZ,GroupPositionX,GroupPositionY,GroupPositionZ,VelocityX,VelocityY,VelocityZ,AngularVelocityX,AngularVelocityY,AngularVelocityZ,AccelerationX,AccelerationY,AccelerationZ,RotationX,RotationY,RotationZ,RotationW,ObjectFlags,SitTargetOffsetX,SitTargetOffsetY,SitTargetOffsetZ,SitTargetOrientW,SitTargetOrientX,SitTargetOrientY,SitTargetOrientZ,ColorR,ColorG,ColorB,ColorA,ClickAction,PayPrice,PayButton1,PayButton2,PayButton3,PayButton4,LoopedSound,LoopedSoundGain,TextureAnimation,ParticleSystem,OmegaX,OmegaY,OmegaZ,CameraEyeOffsetX,CameraEyeOffsetY,CameraEyeOffsetZ,CameraAtOffsetX,CameraAtOffsetY,CameraAtOffsetZ,ForceMouselook,ScriptAccessPin,AllowedDrop,DieAtEdge,SalePrice,SaleType,Material,CollisionSound,CollisionSoundVolume,VolumeDetect FROM prims_backup; +DROP TABLE prims_backup; +COMMIT; + +:VERSION 18 + +BEGIN; + +update terrain + set RegionUUID = substr(RegionUUID, 1, 8) || "-" || substr(RegionUUID, 9, 4) || "-" || substr(RegionUUID, 13, 4) || "-" || substr(RegionUUID, 17, 4) || "-" || substr(RegionUUID, 21, 12) + where RegionUUID not like '%-%'; + + +update landaccesslist + set LandUUID = substr(LandUUID, 1, 8) || "-" || substr(LandUUID, 9, 4) || "-" || substr(LandUUID, 13, 4) || "-" || substr(LandUUID, 17, 4) || "-" || substr(LandUUID, 21, 12) + where LandUUID not like '%-%'; + +update landaccesslist + set AccessUUID = substr(AccessUUID, 1, 8) || "-" || substr(AccessUUID, 9, 4) || "-" || substr(AccessUUID, 13, 4) || "-" || substr(AccessUUID, 17, 4) || "-" || substr(AccessUUID, 21, 12) + where AccessUUID not like '%-%'; + + +update prims + set UUID = substr(UUID, 1, 8) || "-" || substr(UUID, 9, 4) || "-" || substr(UUID, 13, 4) || "-" || substr(UUID, 17, 4) || "-" || substr(UUID, 21, 12) + where UUID not like '%-%'; + +update prims + set RegionUUID = substr(RegionUUID, 1, 8) || "-" || substr(RegionUUID, 9, 4) || "-" || substr(RegionUUID, 13, 4) || "-" || substr(RegionUUID, 17, 4) || "-" || substr(RegionUUID, 21, 12) + where RegionUUID not like '%-%'; + +update prims + set SceneGroupID = substr(SceneGroupID, 1, 8) || "-" || substr(SceneGroupID, 9, 4) || "-" || substr(SceneGroupID, 13, 4) || "-" || substr(SceneGroupID, 17, 4) || "-" || substr(SceneGroupID, 21, 12) + where SceneGroupID not like '%-%'; + +update prims + set CreatorID = substr(CreatorID, 1, 8) || "-" || substr(CreatorID, 9, 4) || "-" || substr(CreatorID, 13, 4) || "-" || substr(CreatorID, 17, 4) || "-" || substr(CreatorID, 21, 12) + where CreatorID not like '%-%'; + +update prims + set OwnerID = substr(OwnerID, 1, 8) || "-" || substr(OwnerID, 9, 4) || "-" || substr(OwnerID, 13, 4) || "-" || substr(OwnerID, 17, 4) || "-" || substr(OwnerID, 21, 12) + where OwnerID not like '%-%'; + +update prims + set GroupID = substr(GroupID, 1, 8) || "-" || substr(GroupID, 9, 4) || "-" || substr(GroupID, 13, 4) || "-" || substr(GroupID, 17, 4) || "-" || substr(GroupID, 21, 12) + where GroupID not like '%-%'; + +update prims + set LastOwnerID = substr(LastOwnerID, 1, 8) || "-" || substr(LastOwnerID, 9, 4) || "-" || substr(LastOwnerID, 13, 4) || "-" || substr(LastOwnerID, 17, 4) || "-" || substr(LastOwnerID, 21, 12) + where LastOwnerID not like '%-%'; + + +update primshapes + set UUID = substr(UUID, 1, 8) || "-" || substr(UUID, 9, 4) || "-" || substr(UUID, 13, 4) || "-" || substr(UUID, 17, 4) || "-" || substr(UUID, 21, 12) + where UUID not like '%-%'; + + +update land + set UUID = substr(UUID, 1, 8) || "-" || substr(UUID, 9, 4) || "-" || substr(UUID, 13, 4) || "-" || substr(UUID, 17, 4) || "-" || substr(UUID, 21, 12) + where UUID not like '%-%'; + +update land + set RegionUUID = substr(RegionUUID, 1, 8) || "-" || substr(RegionUUID, 9, 4) || "-" || substr(RegionUUID, 13, 4) || "-" || substr(RegionUUID, 17, 4) || "-" || substr(RegionUUID, 21, 12) + where RegionUUID not like '%-%'; + +update land + set OwnerUUID = substr(OwnerUUID, 1, 8) || "-" || substr(OwnerUUID, 9, 4) || "-" || substr(OwnerUUID, 13, 4) || "-" || substr(OwnerUUID, 17, 4) || "-" || substr(OwnerUUID, 21, 12) + where OwnerUUID not like '%-%'; + +update land + set GroupUUID = substr(GroupUUID, 1, 8) || "-" || substr(GroupUUID, 9, 4) || "-" || substr(GroupUUID, 13, 4) || "-" || substr(GroupUUID, 17, 4) || "-" || substr(GroupUUID, 21, 12) + where GroupUUID not like '%-%'; + +update land + set MediaTextureUUID = substr(MediaTextureUUID, 1, 8) || "-" || substr(MediaTextureUUID, 9, 4) || "-" || substr(MediaTextureUUID, 13, 4) || "-" || substr(MediaTextureUUID, 17, 4) || "-" || substr(MediaTextureUUID, 21, 12) + where MediaTextureUUID not like '%-%'; + +update land + set SnapshotUUID = substr(SnapshotUUID, 1, 8) || "-" || substr(SnapshotUUID, 9, 4) || "-" || substr(SnapshotUUID, 13, 4) || "-" || substr(SnapshotUUID, 17, 4) || "-" || substr(SnapshotUUID, 21, 12) + where SnapshotUUID not like '%-%'; + +update land + set AuthbuyerID = substr(AuthbuyerID, 1, 8) || "-" || substr(AuthbuyerID, 9, 4) || "-" || substr(AuthbuyerID, 13, 4) || "-" || substr(AuthbuyerID, 17, 4) || "-" || substr(AuthbuyerID, 21, 12) + where AuthbuyerID not like '%-%'; + +COMMIT; diff --git a/OpenSim/Data/SQLite/Resources/UserAccount.migrations b/OpenSim/Data/SQLite/Resources/UserAccount.migrations new file mode 100644 index 0000000000..854fe694c2 --- /dev/null +++ b/OpenSim/Data/SQLite/Resources/UserAccount.migrations @@ -0,0 +1,27 @@ +:VERSION 1 + +BEGIN TRANSACTION; + +-- useraccounts table +CREATE TABLE UserAccounts ( + PrincipalID CHAR(36) primary key, + ScopeID CHAR(36) NOT NULL, + FirstName VARCHAR(64) NOT NULL, + LastName VARCHAR(64) NOT NULL, + Email VARCHAR(64), + ServiceURLs TEXT, + Created INT(11), + UserLevel integer NOT NULL DEFAULT 0, + UserFlags integer NOT NULL DEFAULT 0, + UserTitle varchar(64) NOT NULL DEFAULT '' +); + +COMMIT; + +:VERSION 2 + +BEGIN TRANSACTION; + +INSERT INTO UserAccounts (PrincipalID, ScopeID, FirstName, LastName, Email, ServiceURLs, Created) SELECT `UUID` AS PrincipalID, '00000000-0000-0000-0000-000000000000' AS ScopeID, username AS FirstName, surname AS LastName, '' as Email, '' AS ServiceURLs, created as Created FROM users; + +COMMIT; diff --git a/OpenSim/Data/SQLite/Resources/UserStore.migrations b/OpenSim/Data/SQLite/Resources/UserStore.migrations new file mode 100644 index 0000000000..73d35e83c3 --- /dev/null +++ b/OpenSim/Data/SQLite/Resources/UserStore.migrations @@ -0,0 +1,169 @@ +:VERSION 1 + +BEGIN TRANSACTION; + +-- users table +CREATE TABLE users( + UUID varchar(255) primary key, + username varchar(255), + surname varchar(255), + passwordHash varchar(255), + passwordSalt varchar(255), + homeRegionX integer, + homeRegionY integer, + homeLocationX float, + homeLocationY float, + homeLocationZ float, + homeLookAtX float, + homeLookAtY float, + homeLookAtZ float, + created integer, + lastLogin integer, + rootInventoryFolderID varchar(255), + userInventoryURI varchar(255), + userAssetURI varchar(255), + profileCanDoMask integer, + profileWantDoMask integer, + profileAboutText varchar(255), + profileFirstText varchar(255), + profileImage varchar(255), + profileFirstImage varchar(255), + webLoginKey text default '00000000-0000-0000-0000-000000000000'); +-- friends table +CREATE TABLE userfriends( + ownerID varchar(255), + friendID varchar(255), + friendPerms integer, + ownerPerms integer, + datetimestamp integer); + +COMMIT; + +:VERSION 2 + +BEGIN; + +ALTER TABLE users add homeRegionID varchar(36) NOT NULL default '00000000-0000-0000-0000-000000000000'; + +COMMIT; + +:VERSION 3 + +BEGIN; + +ALTER TABLE users add userFlags integer NOT NULL default 0; +ALTER TABLE users add godLevel integer NOT NULL default 0; + +COMMIT; + +:VERSION 4 + +BEGIN; + +ALTER TABLE users add customType varchar(32) not null default ''; +ALTER TABLE users add partner char(36) not null default '00000000-0000-0000-0000-000000000000'; + +COMMIT; + +:VERSION 5 + +BEGIN; + +CREATE TABLE `avatarattachments` (`UUID` char(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000', `attachpoint` int(11) NOT NULL DEFAULT 0, `item` char(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000', `asset` char(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000'); + +COMMIT; + +:VERSION 6 + +BEGIN TRANSACTION; + +-- usersagents table +CREATE TABLE IF NOT EXISTS useragents( + UUID varchar(255) primary key, + agentIP varchar(255), + agentPort integer, + agentOnline boolean, + sessionID varchar(255), + secureSessionID varchar(255), + regionID varchar(255), + loginTime integer, + logoutTime integer, + currentRegion varchar(255), + currentHandle varchar(255), + currentPosX float, + currentPosY float, + currentPosZ float); + +COMMIT; + +:VERSION 7 + +BEGIN TRANSACTION; + +ALTER TABLE useragents add currentLookAtX float not null default 128; +ALTER TABLE useragents add currentLookAtY float not null default 128; +ALTER TABLE useragents add currentLookAtZ float not null default 70; + +COMMIT; + +:VERSION 8 + +BEGIN TRANSACTION; + +ALTER TABLE users add email varchar(250); + +COMMIT; + +:VERSION 9 + +BEGIN; + +update users + set UUID = substr(UUID, 1, 8) || "-" || substr(UUID, 9, 4) || "-" || substr(UUID, 13, 4) || "-" || substr(UUID, 17, 4) || "-" || substr(UUID, 21, 12) + where UUID not like '%-%'; + +update useragents + set UUID = substr(UUID, 1, 8) || "-" || substr(UUID, 9, 4) || "-" || substr(UUID, 13, 4) || "-" || substr(UUID, 17, 4) || "-" || substr(UUID, 21, 12) + where UUID not like '%-%'; + +COMMIT; + +:VERSION 10 + +BEGIN TRANSACTION; + +CREATE TABLE IF NOT EXISTS avatarappearance( + Owner varchar(36) NOT NULL primary key, + BodyItem varchar(36) DEFAULT NULL, + BodyAsset varchar(36) DEFAULT NULL, + SkinItem varchar(36) DEFAULT NULL, + SkinAsset varchar(36) DEFAULT NULL, + HairItem varchar(36) DEFAULT NULL, + HairAsset varchar(36) DEFAULT NULL, + EyesItem varchar(36) DEFAULT NULL, + EyesAsset varchar(36) DEFAULT NULL, + ShirtItem varchar(36) DEFAULT NULL, + ShirtAsset varchar(36) DEFAULT NULL, + PantsItem varchar(36) DEFAULT NULL, + PantsAsset varchar(36) DEFAULT NULL, + ShoesItem varchar(36) DEFAULT NULL, + ShoesAsset varchar(36) DEFAULT NULL, + SocksItem varchar(36) DEFAULT NULL, + SocksAsset varchar(36) DEFAULT NULL, + JacketItem varchar(36) DEFAULT NULL, + JacketAsset varchar(36) DEFAULT NULL, + GlovesItem varchar(36) DEFAULT NULL, + GlovesAsset varchar(36) DEFAULT NULL, + UnderShirtItem varchar(36) DEFAULT NULL, + UnderShirtAsset varchar(36) DEFAULT NULL, + UnderPantsItem varchar(36) DEFAULT NULL, + UnderPantsAsset varchar(36) DEFAULT NULL, + SkirtItem varchar(36) DEFAULT NULL, + SkirtAsset varchar(36) DEFAULT NULL, + Texture blob, + VisualParams blob, + Serial int DEFAULT NULL, + AvatarHeight float DEFAULT NULL +); + +COMMIT; diff --git a/OpenSim/Data/SQLite/SQLiteAssetData.cs b/OpenSim/Data/SQLite/SQLiteAssetData.cs index a032670588..16e560c6df 100644 --- a/OpenSim/Data/SQLite/SQLiteAssetData.cs +++ b/OpenSim/Data/SQLite/SQLiteAssetData.cs @@ -30,7 +30,7 @@ using System.Data; using System.Reflection; using System.Collections.Generic; using log4net; -using Mono.Data.SqliteClient; +using Mono.Data.Sqlite; using OpenMetaverse; using OpenSim.Framework; @@ -44,10 +44,10 @@ namespace OpenSim.Data.SQLite // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private const string SelectAssetSQL = "select * from assets where UUID=:UUID"; - private const string SelectAssetMetadataSQL = "select Name, Description, Type, Temporary, UUID from assets limit :start, :count"; + private const string SelectAssetMetadataSQL = "select Name, Description, Type, Temporary, asset_flags, UUID, CreatorID from assets limit :start, :count"; private const string DeleteAssetSQL = "delete from assets where UUID=:UUID"; - private const string InsertAssetSQL = "insert into assets(UUID, Name, Description, Type, Local, Temporary, Data) values(:UUID, :Name, :Description, :Type, :Local, :Temporary, :Data)"; - private const string UpdateAssetSQL = "update assets set Name=:Name, Description=:Description, Type=:Type, Local=:Local, Temporary=:Temporary, Data=:Data where UUID=:UUID"; + private const string InsertAssetSQL = "insert into assets(UUID, Name, Description, Type, Local, Temporary, asset_flags, CreatorID, Data) values(:UUID, :Name, :Description, :Type, :Local, :Temporary, :Flags, :CreatorID, :Data)"; + private const string UpdateAssetSQL = "update assets set Name=:Name, Description=:Description, Type=:Type, Local=:Local, Temporary=:Temporary, asset_flags=:Flags, CreatorID=:CreatorID, Data=:Data where UUID=:UUID"; private const string assetSelect = "select * from assets"; private SqliteConnection m_conn; @@ -136,8 +136,10 @@ namespace OpenSim.Data.SQLite cmd.Parameters.Add(new SqliteParameter(":Type", asset.Type)); cmd.Parameters.Add(new SqliteParameter(":Local", asset.Local)); cmd.Parameters.Add(new SqliteParameter(":Temporary", asset.Temporary)); + cmd.Parameters.Add(new SqliteParameter(":Flags", asset.Flags)); + cmd.Parameters.Add(new SqliteParameter(":CreatorID", asset.Metadata.CreatorID)); cmd.Parameters.Add(new SqliteParameter(":Data", asset.Data)); - + cmd.ExecuteNonQuery(); } } @@ -154,6 +156,8 @@ namespace OpenSim.Data.SQLite cmd.Parameters.Add(new SqliteParameter(":Type", asset.Type)); cmd.Parameters.Add(new SqliteParameter(":Local", asset.Local)); cmd.Parameters.Add(new SqliteParameter(":Temporary", asset.Temporary)); + cmd.Parameters.Add(new SqliteParameter(":Flags", asset.Flags)); + cmd.Parameters.Add(new SqliteParameter(":CreatorID", asset.Metadata.CreatorID)); cmd.Parameters.Add(new SqliteParameter(":Data", asset.Data)); cmd.ExecuteNonQuery(); @@ -207,20 +211,6 @@ namespace OpenSim.Data.SQLite } } - /// - /// Delete an asset from database - /// - /// - public void DeleteAsset(UUID uuid) - { - using (SqliteCommand cmd = new SqliteCommand(DeleteAssetSQL, m_conn)) - { - cmd.Parameters.Add(new SqliteParameter(":UUID", uuid.ToString())); - - cmd.ExecuteNonQuery(); - } - } - /// /// /// @@ -235,13 +225,14 @@ namespace OpenSim.Data.SQLite new UUID((String)row["UUID"]), (String)row["Name"], Convert.ToSByte(row["Type"]), - UUID.Zero.ToString() + (String)row["CreatorID"] ); asset.Description = (String) row["Description"]; asset.Local = Convert.ToBoolean(row["Local"]); asset.Temporary = Convert.ToBoolean(row["Temporary"]); - asset.Data = (byte[]) row["Data"]; + asset.Flags = (AssetFlags)Convert.ToInt32(row["asset_flags"]); + asset.Data = (byte[])row["Data"]; return asset; } @@ -254,6 +245,8 @@ namespace OpenSim.Data.SQLite metadata.Description = (string) row["Description"]; metadata.Type = Convert.ToSByte(row["Type"]); metadata.Temporary = Convert.ToBoolean(row["Temporary"]); // Not sure if this is correct. + metadata.Flags = (AssetFlags)Convert.ToInt32(row["asset_flags"]); + metadata.CreatorID = row["CreatorID"].ToString(); // Current SHA1s are not stored/computed. metadata.SHA1 = new byte[] {}; @@ -338,6 +331,35 @@ namespace OpenSim.Data.SQLite get { return "SQLite Asset storage engine"; } } + // TODO: (AlexRa): one of these is to be removed eventually (?) + + /// + /// Delete an asset from database + /// + /// + public bool DeleteAsset(UUID uuid) + { + lock (this) + { + using (SqliteCommand cmd = new SqliteCommand(DeleteAssetSQL, m_conn)) + { + cmd.Parameters.Add(new SqliteParameter(":UUID", uuid.ToString())); + cmd.ExecuteNonQuery(); + } + } + return true; + } + + public override bool Delete(string id) + { + UUID assetID; + + if (!UUID.TryParse(id, out assetID)) + return false; + + return DeleteAsset(assetID); + } + #endregion } -} \ No newline at end of file +} diff --git a/OpenSim/Data/SQLite/SQLiteAuthenticationData.cs b/OpenSim/Data/SQLite/SQLiteAuthenticationData.cs index aa10734d50..a1412ff0fa 100644 --- a/OpenSim/Data/SQLite/SQLiteAuthenticationData.cs +++ b/OpenSim/Data/SQLite/SQLiteAuthenticationData.cs @@ -29,14 +29,18 @@ using System; using System.Collections; using System.Collections.Generic; using System.Data; +using System.Reflection; +using log4net; using OpenMetaverse; using OpenSim.Framework; -using Mono.Data.SqliteClient; +using Mono.Data.Sqlite; namespace OpenSim.Data.SQLite { public class SQLiteAuthenticationData : SQLiteFramework, IAuthenticationData { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + private string m_Realm; private List m_ColumnNames; private int m_LastExpire; @@ -56,13 +60,8 @@ namespace OpenSim.Data.SQLite m_Connection = new SqliteConnection(connectionString); m_Connection.Open(); - using (SqliteConnection dbcon = (SqliteConnection)((ICloneable)m_Connection).Clone()) - { - dbcon.Open(); - Migration m = new Migration(dbcon, GetType().Assembly, "AuthStore"); - m.Update(); - dbcon.Close(); - } + Migration m = new Migration(m_Connection, GetType().Assembly, "AuthStore"); + m.Update(); m_initialized = true; } @@ -113,7 +112,7 @@ namespace OpenSim.Data.SQLite } finally { - CloseCommand(cmd); + //CloseCommand(cmd); } return null; @@ -156,14 +155,14 @@ namespace OpenSim.Data.SQLite { if (ExecuteNonQuery(cmd, m_Connection) < 1) { - CloseCommand(cmd); + //CloseCommand(cmd); return false; } } catch (Exception e) { - Console.WriteLine(e.ToString()); - CloseCommand(cmd); + m_log.Error("[SQLITE]: Exception storing authentication data", e); + //CloseCommand(cmd); return false; } } @@ -184,19 +183,19 @@ namespace OpenSim.Data.SQLite { if (ExecuteNonQuery(cmd, m_Connection) < 1) { - CloseCommand(cmd); + //CloseCommand(cmd); return false; } } catch (Exception e) { Console.WriteLine(e.ToString()); - CloseCommand(cmd); + //CloseCommand(cmd); return false; } } - CloseCommand(cmd); + //CloseCommand(cmd); return true; } diff --git a/OpenSim/Data/SQLite/SQLiteAvatarData.cs b/OpenSim/Data/SQLite/SQLiteAvatarData.cs index b3f4a4c077..c093884db4 100644 --- a/OpenSim/Data/SQLite/SQLiteAvatarData.cs +++ b/OpenSim/Data/SQLite/SQLiteAvatarData.cs @@ -33,7 +33,7 @@ using System.Threading; using log4net; using OpenMetaverse; using OpenSim.Framework; -using Mono.Data.SqliteClient; +using Mono.Data.Sqlite; namespace OpenSim.Data.SQLite { @@ -55,8 +55,8 @@ namespace OpenSim.Data.SQLite SqliteCommand cmd = new SqliteCommand(); cmd.CommandText = String.Format("delete from {0} where `PrincipalID` = :PrincipalID and `Name` = :Name", m_Realm); - cmd.Parameters.Add(":PrincipalID", principalID.ToString()); - cmd.Parameters.Add(":Name", name); + cmd.Parameters.AddWithValue(":PrincipalID", principalID.ToString()); + cmd.Parameters.AddWithValue(":Name", name); try { @@ -67,7 +67,7 @@ namespace OpenSim.Data.SQLite } finally { - CloseCommand(cmd); + //CloseCommand(cmd); } } } diff --git a/OpenSim/Data/SQLite/SQLiteEstateData.cs b/OpenSim/Data/SQLite/SQLiteEstateData.cs index bd6b776f80..9dd4a2e69b 100644 --- a/OpenSim/Data/SQLite/SQLiteEstateData.cs +++ b/OpenSim/Data/SQLite/SQLiteEstateData.cs @@ -30,7 +30,7 @@ using System.Collections.Generic; using System.Data; using System.Reflection; using log4net; -using Mono.Data.SqliteClient; +using Mono.Data.Sqlite; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; @@ -62,8 +62,8 @@ namespace OpenSim.Data.SQLite Migration m = new Migration(m_connection, assem, "EstateStore"); m.Update(); - m_connection.Close(); - m_connection.Open(); + //m_connection.Close(); + // m_connection.Open(); Type t = typeof(EstateSettings); m_Fields = t.GetFields(BindingFlags.NonPublic | @@ -87,7 +87,7 @@ namespace OpenSim.Data.SQLite SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand(); cmd.CommandText = sql; - cmd.Parameters.Add(":RegionID", regionID.ToString()); + cmd.Parameters.AddWithValue(":RegionID", regionID.ToString()); return DoLoad(cmd, regionID, create); } @@ -143,13 +143,13 @@ namespace OpenSim.Data.SQLite if (m_FieldMap[name].GetValue(es) is bool) { if ((bool)m_FieldMap[name].GetValue(es)) - cmd.Parameters.Add(":"+name, "1"); + cmd.Parameters.AddWithValue(":"+name, "1"); else - cmd.Parameters.Add(":"+name, "0"); + cmd.Parameters.AddWithValue(":"+name, "0"); } else { - cmd.Parameters.Add(":"+name, m_FieldMap[name].GetValue(es).ToString()); + cmd.Parameters.AddWithValue(":"+name, m_FieldMap[name].GetValue(es).ToString()); } } @@ -167,8 +167,8 @@ namespace OpenSim.Data.SQLite r.Close(); cmd.CommandText = "insert into estate_map values (:RegionID, :EstateID)"; - cmd.Parameters.Add(":RegionID", regionID.ToString()); - cmd.Parameters.Add(":EstateID", es.EstateID.ToString()); + cmd.Parameters.AddWithValue(":RegionID", regionID.ToString()); + cmd.Parameters.AddWithValue(":EstateID", es.EstateID.ToString()); // This will throw on dupe key try @@ -211,13 +211,13 @@ namespace OpenSim.Data.SQLite if (m_FieldMap[name].GetValue(es) is bool) { if ((bool)m_FieldMap[name].GetValue(es)) - cmd.Parameters.Add(":"+name, "1"); + cmd.Parameters.AddWithValue(":"+name, "1"); else - cmd.Parameters.Add(":"+name, "0"); + cmd.Parameters.AddWithValue(":"+name, "0"); } else { - cmd.Parameters.Add(":"+name, m_FieldMap[name].GetValue(es).ToString()); + cmd.Parameters.AddWithValue(":"+name, m_FieldMap[name].GetValue(es).ToString()); } } @@ -236,7 +236,7 @@ namespace OpenSim.Data.SQLite SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand(); cmd.CommandText = "select bannedUUID from estateban where EstateID = :EstateID"; - cmd.Parameters.Add(":EstateID", es.EstateID); + cmd.Parameters.AddWithValue(":EstateID", es.EstateID); IDataReader r = cmd.ExecuteReader(); @@ -260,7 +260,7 @@ namespace OpenSim.Data.SQLite SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand(); cmd.CommandText = "delete from estateban where EstateID = :EstateID"; - cmd.Parameters.Add(":EstateID", es.EstateID.ToString()); + cmd.Parameters.AddWithValue(":EstateID", es.EstateID.ToString()); cmd.ExecuteNonQuery(); @@ -270,8 +270,8 @@ namespace OpenSim.Data.SQLite foreach (EstateBan b in es.EstateBans) { - cmd.Parameters.Add(":EstateID", es.EstateID.ToString()); - cmd.Parameters.Add(":bannedUUID", b.BannedUserID.ToString()); + cmd.Parameters.AddWithValue(":EstateID", es.EstateID.ToString()); + cmd.Parameters.AddWithValue(":bannedUUID", b.BannedUserID.ToString()); cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); @@ -283,7 +283,7 @@ namespace OpenSim.Data.SQLite SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand(); cmd.CommandText = "delete from "+table+" where EstateID = :EstateID"; - cmd.Parameters.Add(":EstateID", EstateID.ToString()); + cmd.Parameters.AddWithValue(":EstateID", EstateID.ToString()); cmd.ExecuteNonQuery(); @@ -293,8 +293,8 @@ namespace OpenSim.Data.SQLite foreach (UUID uuid in data) { - cmd.Parameters.Add(":EstateID", EstateID.ToString()); - cmd.Parameters.Add(":uuid", uuid.ToString()); + cmd.Parameters.AddWithValue(":EstateID", EstateID.ToString()); + cmd.Parameters.AddWithValue(":uuid", uuid.ToString()); cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); @@ -308,7 +308,7 @@ namespace OpenSim.Data.SQLite SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand(); cmd.CommandText = "select uuid from "+table+" where EstateID = :EstateID"; - cmd.Parameters.Add(":EstateID", EstateID); + cmd.Parameters.AddWithValue(":EstateID", EstateID); IDataReader r = cmd.ExecuteReader(); @@ -333,7 +333,7 @@ namespace OpenSim.Data.SQLite SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand(); cmd.CommandText = sql; - cmd.Parameters.Add(":EstateID", estateID.ToString()); + cmd.Parameters.AddWithValue(":EstateID", estateID.ToString()); return DoLoad(cmd, UUID.Zero, false); } @@ -347,7 +347,7 @@ namespace OpenSim.Data.SQLite SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand(); cmd.CommandText = sql; - cmd.Parameters.Add(":EstateName", search); + cmd.Parameters.AddWithValue(":EstateName", search); IDataReader r = cmd.ExecuteReader(); @@ -365,8 +365,8 @@ namespace OpenSim.Data.SQLite SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand(); cmd.CommandText = "insert into estate_map values (:RegionID, :EstateID)"; - cmd.Parameters.Add(":RegionID", regionID.ToString()); - cmd.Parameters.Add(":EstateID", estateID.ToString()); + cmd.Parameters.AddWithValue(":RegionID", regionID.ToString()); + cmd.Parameters.AddWithValue(":EstateID", estateID.ToString()); if (cmd.ExecuteNonQuery() == 0) return false; diff --git a/OpenSim/Data/SQLite/SQLiteFramework.cs b/OpenSim/Data/SQLite/SQLiteFramework.cs index 20b508515a..cf114d1a07 100644 --- a/OpenSim/Data/SQLite/SQLiteFramework.cs +++ b/OpenSim/Data/SQLite/SQLiteFramework.cs @@ -31,7 +31,7 @@ using System.Collections.Generic; using System.Data; using OpenMetaverse; using OpenSim.Framework; -using Mono.Data.SqliteClient; +using Mono.Data.Sqlite; namespace OpenSim.Data.SQLite { @@ -55,11 +55,14 @@ namespace OpenSim.Data.SQLite { lock (connection) { +/* SqliteConnection newConnection = (SqliteConnection)((ICloneable)connection).Clone(); newConnection.Open(); cmd.Connection = newConnection; +*/ + cmd.Connection = connection; //Console.WriteLine("XXX " + cmd.CommandText); return cmd.ExecuteNonQuery(); @@ -70,11 +73,12 @@ namespace OpenSim.Data.SQLite { lock (connection) { - SqliteConnection newConnection = - (SqliteConnection)((ICloneable)connection).Clone(); - newConnection.Open(); + //SqliteConnection newConnection = + // (SqliteConnection)((ICloneable)connection).Clone(); + //newConnection.Open(); - cmd.Connection = newConnection; + //cmd.Connection = newConnection; + cmd.Connection = connection; //Console.WriteLine("XXX " + cmd.CommandText); return cmd.ExecuteReader(); diff --git a/OpenSim/Data/SQLite/SQLiteFriendsData.cs b/OpenSim/Data/SQLite/SQLiteFriendsData.cs index 0b121826d6..b06853ce68 100644 --- a/OpenSim/Data/SQLite/SQLiteFriendsData.cs +++ b/OpenSim/Data/SQLite/SQLiteFriendsData.cs @@ -31,7 +31,7 @@ using System.Collections.Generic; using System.Data; using OpenMetaverse; using OpenSim.Framework; -using Mono.Data.SqliteClient; +using Mono.Data.Sqlite; namespace OpenSim.Data.SQLite { @@ -47,7 +47,7 @@ namespace OpenSim.Data.SQLite SqliteCommand cmd = new SqliteCommand(); cmd.CommandText = String.Format("select a.*,case when b.Flags is null then -1 else b.Flags end as TheirFlags from {0} as a left join {0} as b on a.PrincipalID = b.Friend and a.Friend = b.PrincipalID where a.PrincipalID = :PrincipalID", m_Realm); - cmd.Parameters.Add(":PrincipalID", userID.ToString()); + cmd.Parameters.AddWithValue(":PrincipalID", userID.ToString()); return DoQuery(cmd); @@ -58,8 +58,8 @@ namespace OpenSim.Data.SQLite SqliteCommand cmd = new SqliteCommand(); cmd.CommandText = String.Format("delete from {0} where PrincipalID = :PrincipalID and Friend = :Friend", m_Realm); - cmd.Parameters.Add(":PrincipalID", principalID.ToString()); - cmd.Parameters.Add(":Friend", friend); + cmd.Parameters.AddWithValue(":PrincipalID", principalID.ToString()); + cmd.Parameters.AddWithValue(":Friend", friend); ExecuteNonQuery(cmd, cmd.Connection); diff --git a/OpenSim/Data/SQLite/SQLiteGenericTableHandler.cs b/OpenSim/Data/SQLite/SQLiteGenericTableHandler.cs index b39bb19fb7..9b8e2fa7f3 100644 --- a/OpenSim/Data/SQLite/SQLiteGenericTableHandler.cs +++ b/OpenSim/Data/SQLite/SQLiteGenericTableHandler.cs @@ -30,7 +30,7 @@ using System.Collections.Generic; using System.Data; using System.Reflection; using log4net; -using Mono.Data.SqliteClient; +using Mono.Data.Sqlite; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; @@ -59,19 +59,21 @@ namespace OpenSim.Data.SQLite if (!m_initialized) { m_Connection = new SqliteConnection(connectionString); + //Console.WriteLine(string.Format("OPENING CONNECTION FOR {0} USING {1}", storeName, connectionString)); m_Connection.Open(); if (storeName != String.Empty) { Assembly assem = GetType().Assembly; - SqliteConnection newConnection = - (SqliteConnection)((ICloneable)m_Connection).Clone(); - newConnection.Open(); + //SqliteConnection newConnection = + // (SqliteConnection)((ICloneable)m_Connection).Clone(); + //newConnection.Open(); - Migration m = new Migration(newConnection, assem, storeName); + //Migration m = new Migration(newConnection, assem, storeName); + Migration m = new Migration(m_Connection, assem, storeName); m.Update(); - newConnection.Close(); - newConnection.Dispose(); + //newConnection.Close(); + //newConnection.Dispose(); } m_initialized = true; @@ -197,7 +199,7 @@ namespace OpenSim.Data.SQLite result.Add(row); } - CloseCommand(cmd); + //CloseCommand(cmd); return result.ToArray(); } diff --git a/OpenSim/Data/SQLite/Tests/SQLiteAssetTest.cs b/OpenSim/Data/SQLite/SQLiteGridUserData.cs similarity index 65% rename from OpenSim/Data/SQLite/Tests/SQLiteAssetTest.cs rename to OpenSim/Data/SQLite/SQLiteGridUserData.cs index 0c2f5dfefc..1bb5ed87d6 100644 --- a/OpenSim/Data/SQLite/Tests/SQLiteAssetTest.cs +++ b/OpenSim/Data/SQLite/SQLiteGridUserData.cs @@ -25,40 +25,37 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -using System.IO; -using NUnit.Framework; -using OpenSim.Data.Tests; -using OpenSim.Tests.Common; +using System; +using System.Collections.Generic; +using System.Data; +using System.Reflection; +using System.Threading; +using log4net; +using OpenMetaverse; +using OpenSim.Framework; -namespace OpenSim.Data.SQLite.Tests +namespace OpenSim.Data.SQLite { - [TestFixture, DatabaseTest] - public class SQLiteAssetTest : BasicAssetTest + /// + /// A SQL Interface for user grid data + /// + public class SQLiteGridUserData : SQLiteGenericTableHandler, IGridUserData { - public string file; - public string connect; - - [TestFixtureSetUp] - public void Init() - { - // SQLite doesn't work on power or z linux - if (Directory.Exists("/proc/ppc64") || Directory.Exists("/proc/dasd")) - { - Assert.Ignore(); - } +// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - SuperInit(); - file = Path.GetTempFileName() + ".db"; - connect = "URI=file:" + file + ",version=3"; - db = new SQLiteAssetData(); - db.Initialise(connect); + public SQLiteGridUserData(string connectionString, string realm) + : base(connectionString, realm, "GridUserStore") {} + + public new GridUserData Get(string userID) + { + GridUserData[] ret = Get("UserID", userID); + + if (ret.Length == 0) + return null; + + return ret[0]; } - [TestFixtureTearDown] - public void Cleanup() - { - db.Dispose(); - File.Delete(file); - } + } -} +} \ No newline at end of file diff --git a/OpenSim/Data/SQLite/SQLiteInventoryStore.cs b/OpenSim/Data/SQLite/SQLiteInventoryStore.cs index a5e051726e..ece2495c2b 100644 --- a/OpenSim/Data/SQLite/SQLiteInventoryStore.cs +++ b/OpenSim/Data/SQLite/SQLiteInventoryStore.cs @@ -30,7 +30,7 @@ using System.Collections.Generic; using System.Data; using System.Reflection; using log4net; -using Mono.Data.SqliteClient; +using Mono.Data.Sqlite; using OpenMetaverse; using OpenSim.Framework; @@ -98,11 +98,13 @@ namespace OpenSim.Data.SQLite ds.Tables.Add(createInventoryFoldersTable()); invFoldersDa.Fill(ds.Tables["inventoryfolders"]); setupFoldersCommands(invFoldersDa, conn); + CreateDataSetMapping(invFoldersDa, "inventoryfolders"); m_log.Info("[INVENTORY DB]: Populated Inventory Folders Definitions"); ds.Tables.Add(createInventoryItemsTable()); invItemsDa.Fill(ds.Tables["inventoryitems"]); setupItemsCommands(invItemsDa, conn); + CreateDataSetMapping(invItemsDa, "inventoryitems"); m_log.Info("[INVENTORY DB]: Populated Inventory Items Definitions"); ds.AcceptChanges(); @@ -728,6 +730,15 @@ namespace OpenSim.Data.SQLite * **********************************************************************/ + protected void CreateDataSetMapping(IDataAdapter da, string tableName) + { + ITableMapping dbMapping = da.TableMappings.Add(tableName, tableName); + foreach (DataColumn col in ds.Tables[tableName].Columns) + { + dbMapping.ColumnMappings.Add(col.ColumnName, col.ColumnName); + } + } + /// /// Create the "inventoryitems" table /// diff --git a/OpenSim/Data/SQLite/SQLiteRegionData.cs b/OpenSim/Data/SQLite/SQLiteRegionData.cs index d2ba9ae298..85703dc2ca 100644 --- a/OpenSim/Data/SQLite/SQLiteRegionData.cs +++ b/OpenSim/Data/SQLite/SQLiteRegionData.cs @@ -32,7 +32,7 @@ using System.Drawing; using System.IO; using System.Reflection; using log4net; -using Mono.Data.SqliteClient; +using Mono.Data.Sqlite; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; @@ -87,119 +87,142 @@ namespace OpenSim.Data.SQLite /// the connection string public void Initialise(string connectionString) { - m_connectionString = connectionString; - - ds = new DataSet(); - - m_log.Info("[REGION DB]: Sqlite - connecting: " + connectionString); - m_conn = new SqliteConnection(m_connectionString); - m_conn.Open(); - - - - SqliteCommand primSelectCmd = new SqliteCommand(primSelect, m_conn); - primDa = new SqliteDataAdapter(primSelectCmd); - // SqliteCommandBuilder primCb = new SqliteCommandBuilder(primDa); - - SqliteCommand shapeSelectCmd = new SqliteCommand(shapeSelect, m_conn); - shapeDa = new SqliteDataAdapter(shapeSelectCmd); - // SqliteCommandBuilder shapeCb = new SqliteCommandBuilder(shapeDa); - - SqliteCommand itemsSelectCmd = new SqliteCommand(itemsSelect, m_conn); - itemsDa = new SqliteDataAdapter(itemsSelectCmd); - - SqliteCommand terrainSelectCmd = new SqliteCommand(terrainSelect, m_conn); - terrainDa = new SqliteDataAdapter(terrainSelectCmd); - - SqliteCommand landSelectCmd = new SqliteCommand(landSelect, m_conn); - landDa = new SqliteDataAdapter(landSelectCmd); - - SqliteCommand landAccessListSelectCmd = new SqliteCommand(landAccessListSelect, m_conn); - landAccessListDa = new SqliteDataAdapter(landAccessListSelectCmd); - - SqliteCommand regionSettingsSelectCmd = new SqliteCommand(regionSettingsSelect, m_conn); - regionSettingsDa = new SqliteDataAdapter(regionSettingsSelectCmd); - // This actually does the roll forward assembly stuff - Assembly assem = GetType().Assembly; - Migration m = new Migration(m_conn, assem, "RegionStore"); - m.Update(); - - lock (ds) + try { - ds.Tables.Add(createPrimTable()); - setupPrimCommands(primDa, m_conn); - primDa.Fill(ds.Tables["prims"]); + m_connectionString = connectionString; - ds.Tables.Add(createShapeTable()); - setupShapeCommands(shapeDa, m_conn); + ds = new DataSet("Region"); - ds.Tables.Add(createItemsTable()); - setupItemsCommands(itemsDa, m_conn); - itemsDa.Fill(ds.Tables["primitems"]); + m_log.Info("[REGION DB]: Sqlite - connecting: " + connectionString); + m_conn = new SqliteConnection(m_connectionString); + m_conn.Open(); - ds.Tables.Add(createTerrainTable()); - setupTerrainCommands(terrainDa, m_conn); + SqliteCommand primSelectCmd = new SqliteCommand(primSelect, m_conn); + primDa = new SqliteDataAdapter(primSelectCmd); - ds.Tables.Add(createLandTable()); - setupLandCommands(landDa, m_conn); + SqliteCommand shapeSelectCmd = new SqliteCommand(shapeSelect, m_conn); + shapeDa = new SqliteDataAdapter(shapeSelectCmd); + // SqliteCommandBuilder shapeCb = new SqliteCommandBuilder(shapeDa); - ds.Tables.Add(createLandAccessListTable()); - setupLandAccessCommands(landAccessListDa, m_conn); + SqliteCommand itemsSelectCmd = new SqliteCommand(itemsSelect, m_conn); + itemsDa = new SqliteDataAdapter(itemsSelectCmd); - ds.Tables.Add(createRegionSettingsTable()); - - setupRegionSettingsCommands(regionSettingsDa, m_conn); + SqliteCommand terrainSelectCmd = new SqliteCommand(terrainSelect, m_conn); + terrainDa = new SqliteDataAdapter(terrainSelectCmd); - // WORKAROUND: This is a work around for sqlite on - // windows, which gets really unhappy with blob columns - // that have no sample data in them. At some point we - // need to actually find a proper way to handle this. - try + SqliteCommand landSelectCmd = new SqliteCommand(landSelect, m_conn); + landDa = new SqliteDataAdapter(landSelectCmd); + + SqliteCommand landAccessListSelectCmd = new SqliteCommand(landAccessListSelect, m_conn); + landAccessListDa = new SqliteDataAdapter(landAccessListSelectCmd); + + SqliteCommand regionSettingsSelectCmd = new SqliteCommand(regionSettingsSelect, m_conn); + regionSettingsDa = new SqliteDataAdapter(regionSettingsSelectCmd); + // This actually does the roll forward assembly stuff + Assembly assem = GetType().Assembly; + Migration m = new Migration(m_conn, assem, "RegionStore"); + m.Update(); + + lock (ds) { - shapeDa.Fill(ds.Tables["primshapes"]); - } - catch (Exception) - { - m_log.Info("[REGION DB]: Caught fill error on primshapes table"); - } + ds.Tables.Add(createPrimTable()); + setupPrimCommands(primDa, m_conn); - try - { - terrainDa.Fill(ds.Tables["terrain"]); - } - catch (Exception) - { - m_log.Info("[REGION DB]: Caught fill error on terrain table"); - } + ds.Tables.Add(createShapeTable()); + setupShapeCommands(shapeDa, m_conn); - try - { - landDa.Fill(ds.Tables["land"]); - } - catch (Exception) - { - m_log.Info("[REGION DB]: Caught fill error on land table"); - } + ds.Tables.Add(createItemsTable()); + setupItemsCommands(itemsDa, m_conn); - try - { - landAccessListDa.Fill(ds.Tables["landaccesslist"]); - } - catch (Exception) - { - m_log.Info("[REGION DB]: Caught fill error on landaccesslist table"); - } + ds.Tables.Add(createTerrainTable()); + setupTerrainCommands(terrainDa, m_conn); - try - { - regionSettingsDa.Fill(ds.Tables["regionsettings"]); + ds.Tables.Add(createLandTable()); + setupLandCommands(landDa, m_conn); + + ds.Tables.Add(createLandAccessListTable()); + setupLandAccessCommands(landAccessListDa, m_conn); + + ds.Tables.Add(createRegionSettingsTable()); + setupRegionSettingsCommands(regionSettingsDa, m_conn); + + // WORKAROUND: This is a work around for sqlite on + // windows, which gets really unhappy with blob columns + // that have no sample data in them. At some point we + // need to actually find a proper way to handle this. + try + { + primDa.Fill(ds.Tables["prims"]); + } + catch (Exception) + { + m_log.Info("[REGION DB]: Caught fill error on prims table"); + } + + try + { + shapeDa.Fill(ds.Tables["primshapes"]); + } + catch (Exception) + { + m_log.Info("[REGION DB]: Caught fill error on primshapes table"); + } + + try + { + terrainDa.Fill(ds.Tables["terrain"]); + } + catch (Exception) + { + m_log.Info("[REGION DB]: Caught fill error on terrain table"); + } + + try + { + landDa.Fill(ds.Tables["land"]); + } + catch (Exception) + { + m_log.Info("[REGION DB]: Caught fill error on land table"); + } + + try + { + landAccessListDa.Fill(ds.Tables["landaccesslist"]); + } + catch (Exception) + { + m_log.Info("[REGION DB]: Caught fill error on landaccesslist table"); + } + + try + { + regionSettingsDa.Fill(ds.Tables["regionsettings"]); + } + catch (Exception) + { + m_log.Info("[REGION DB]: Caught fill error on regionsettings table"); + } + + // We have to create a data set mapping for every table, otherwise the IDataAdaptor.Update() will not populate rows with values! + // Not sure exactly why this is - this kind of thing was not necessary before - justincc 20100409 + // Possibly because we manually set up our own DataTables before connecting to the database + CreateDataSetMapping(primDa, "prims"); + CreateDataSetMapping(shapeDa, "primshapes"); + CreateDataSetMapping(itemsDa, "primitems"); + CreateDataSetMapping(terrainDa, "terrain"); + CreateDataSetMapping(landDa, "land"); + CreateDataSetMapping(landAccessListDa, "landaccesslist"); + CreateDataSetMapping(regionSettingsDa, "regionsettings"); } - catch (Exception) - { - m_log.Info("[REGION DB]: Caught fill error on regionsettings table"); - } - return; } + catch (Exception e) + { + m_log.Error(e); + Environment.Exit(23); + } + + return; } public void Dispose() @@ -603,7 +626,7 @@ namespace OpenSim.Data.SQLite } } } - rev = (int) row["Revision"]; + rev = Convert.ToInt32(row["Revision"]); } else { @@ -755,6 +778,7 @@ namespace OpenSim.Data.SQLite /// public void Commit() { + //m_log.Debug("[SQLITE]: Starting commit"); lock (ds) { primDa.Update(ds, "prims"); @@ -769,18 +793,11 @@ namespace OpenSim.Data.SQLite { regionSettingsDa.Update(ds, "regionsettings"); } - catch (SqliteExecutionException SqlEx) + catch (SqliteException SqlEx) { - if (SqlEx.Message.Contains("logic error")) - { - throw new Exception( - "There was a SQL error or connection string configuration error when saving the region settings. This could be a bug, it could also happen if ConnectionString is defined in the [DatabaseService] section of StandaloneCommon.ini in the config_include folder. This could also happen if the config_include folder doesn't exist or if the OpenSim.ini [Architecture] section isn't set. If this is your first time running OpenSimulator, please restart the simulator and bug a developer to fix this!", - SqlEx); - } - else - { - throw SqlEx; - } + throw new Exception( + "There was a SQL error or connection string configuration error when saving the region settings. This could be a bug, it could also happen if ConnectionString is defined in the [DatabaseService] section of StandaloneCommon.ini in the config_include folder. This could also happen if the config_include folder doesn't exist or if the OpenSim.ini [Architecture] section isn't set. If this is your first time running OpenSimulator, please restart the simulator and bug a developer to fix this!", + SqlEx); } ds.AcceptChanges(); } @@ -802,6 +819,15 @@ namespace OpenSim.Data.SQLite * **********************************************************************/ + protected void CreateDataSetMapping(IDataAdapter da, string tableName) + { + ITableMapping dbMapping = da.TableMappings.Add(tableName, tableName); + foreach (DataColumn col in ds.Tables[tableName].Columns) + { + dbMapping.ColumnMappings.Add(col.ColumnName, col.ColumnName); + } + } + /// /// /// @@ -1130,6 +1156,7 @@ namespace OpenSim.Data.SQLite createCol(regionsettings, "fixed_sun", typeof (Int32)); createCol(regionsettings, "sun_position", typeof (Double)); createCol(regionsettings, "covenant", typeof(String)); + createCol(regionsettings, "map_tile_ID", typeof(String)); regionsettings.PrimaryKey = new DataColumn[] { regionsettings.Columns["regionUUID"] }; return regionsettings; } @@ -1448,6 +1475,7 @@ namespace OpenSim.Data.SQLite newSettings.FixedSun = Convert.ToBoolean(row["fixed_sun"]); newSettings.SunPosition = Convert.ToDouble(row["sun_position"]); newSettings.Covenant = new UUID((String) row["covenant"]); + newSettings.TerrainImageID = new UUID((String)row["map_tile_ID"]); return newSettings; } @@ -1766,6 +1794,7 @@ namespace OpenSim.Data.SQLite row["fixed_sun"] = settings.FixedSun; row["sun_position"] = settings.SunPosition; row["covenant"] = settings.Covenant.ToString(); + row["map_tile_ID"] = settings.TerrainImageID.ToString(); } /// @@ -1897,7 +1926,7 @@ namespace OpenSim.Data.SQLite /// public void StorePrimInventory(UUID primID, ICollection items) { - m_log.InfoFormat("[REGION DB]: Entered StorePrimInventory with prim ID {0}", primID); + //m_log.InfoFormat("[REGION DB]: Entered StorePrimInventory with prim ID {0}", primID); DataTable dbItems = ds.Tables["primitems"]; @@ -1964,6 +1993,7 @@ namespace OpenSim.Data.SQLite sql += ") values (:"; sql += String.Join(", :", cols); sql += ")"; + //m_log.DebugFormat("[SQLITE]: Created insert command {0}", sql); SqliteCommand cmd = new SqliteCommand(sql); // this provides the binding for all our parameters, so @@ -2259,6 +2289,36 @@ namespace OpenSim.Data.SQLite return DbType.String; } } + + static void PrintDataSet(DataSet ds) + { + // Print out any name and extended properties. + Console.WriteLine("DataSet is named: {0}", ds.DataSetName); + foreach (System.Collections.DictionaryEntry de in ds.ExtendedProperties) + { + Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value); + } + Console.WriteLine(); + foreach (DataTable dt in ds.Tables) + { + Console.WriteLine("=> {0} Table:", dt.TableName); + // Print out the column names. + for (int curCol = 0; curCol < dt.Columns.Count; curCol++) + { + Console.Write(dt.Columns[curCol].ColumnName + "\t"); + } + Console.WriteLine("\n----------------------------------"); + // Print the DataTable. + for (int curRow = 0; curRow < dt.Rows.Count; curRow++) + { + for (int curCol = 0; curCol < dt.Columns.Count; curCol++) + { + Console.Write(dt.Rows[curRow][curCol].ToString() + "\t"); + } + Console.WriteLine(); + } + } + } } } diff --git a/OpenSim/Data/SQLite/SQLiteUserAccountData.cs b/OpenSim/Data/SQLite/SQLiteUserAccountData.cs index 67cf7165b1..893f105604 100644 --- a/OpenSim/Data/SQLite/SQLiteUserAccountData.cs +++ b/OpenSim/Data/SQLite/SQLiteUserAccountData.cs @@ -31,7 +31,7 @@ using System.Collections.Generic; using System.Data; using OpenMetaverse; using OpenSim.Framework; -using Mono.Data.SqliteClient; +using Mono.Data.Sqlite; namespace OpenSim.Data.SQLite { @@ -66,7 +66,7 @@ namespace OpenSim.Data.SQLite if (words.Length == 1) { - cmd.CommandText = String.Format("select * from {0} where (ScopeID='{1}' or ScopeID='00000000-0000-0000-0000-000000000000') and (FirstName like '{2}%' or LastName like '{2}%')", + cmd.CommandText = String.Format("select * from {0} where ScopeID='{1}' or ScopeID='00000000-0000-0000-0000-000000000000') and (FirstName like '{2}%' or LastName like '{2}%')", m_Realm, scopeID.ToString(), words[0]); } else diff --git a/OpenSim/Data/SQLite/SQLiteUtils.cs b/OpenSim/Data/SQLite/SQLiteUtils.cs index 4a835ce52f..07c6b69a3b 100644 --- a/OpenSim/Data/SQLite/SQLiteUtils.cs +++ b/OpenSim/Data/SQLite/SQLiteUtils.cs @@ -27,7 +27,7 @@ using System; using System.Data; -using Mono.Data.SqliteClient; +using Mono.Data.Sqlite; namespace OpenSim.Data.SQLite { diff --git a/OpenSim/Data/SQLite/SQLiteXInventoryData.cs b/OpenSim/Data/SQLite/SQLiteXInventoryData.cs index a66e0c6fe0..6064538990 100644 --- a/OpenSim/Data/SQLite/SQLiteXInventoryData.cs +++ b/OpenSim/Data/SQLite/SQLiteXInventoryData.cs @@ -29,7 +29,7 @@ using System; using System.Data; using System.Reflection; using System.Collections.Generic; -using Mono.Data.SqliteClient; +using Mono.Data.Sqlite; using log4net; using OpenMetaverse; using OpenSim.Framework; @@ -49,7 +49,7 @@ namespace OpenSim.Data.SQLite public SQLiteXInventoryData(string conn, string realm) { m_Folders = new SQLiteGenericTableHandler( - conn, "inventoryfolders", "InventoryStore"); + conn, "inventoryfolders", "XInventoryStore"); m_Items = new SqliteItemHandler( conn, "inventoryitems", String.Empty); } @@ -147,7 +147,7 @@ namespace OpenSim.Data.SQLite } reader.Close(); - CloseCommand(cmd); + //CloseCommand(cmd); return perms; } diff --git a/OpenSim/Data/SQLiteLegacy/Properties/AssemblyInfo.cs b/OpenSim/Data/SQLiteLegacy/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000..609a024b73 --- /dev/null +++ b/OpenSim/Data/SQLiteLegacy/Properties/AssemblyInfo.cs @@ -0,0 +1,65 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System.Reflection; +using System.Runtime.InteropServices; + +// General information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. + +[assembly : AssemblyTitle("OpenSim.Data.SQLiteLegacy")] +[assembly : AssemblyDescription("")] +[assembly : AssemblyConfiguration("")] +[assembly : AssemblyCompany("http://opensimulator.org")] +[assembly : AssemblyProduct("OpenSim.Data.SQLiteLegacy")] +[assembly : AssemblyCopyright("Copyright (c) OpenSimulator.org Developers 2007-2009")] +[assembly : AssemblyTrademark("")] +[assembly : AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. + +[assembly : ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM + +[assembly : Guid("6113d5ce-4547-49f4-9236-0dcc503457b1")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: + +[assembly : AssemblyVersion("0.6.5.*")] +[assembly : AssemblyFileVersion("0.6.5.0")] diff --git a/OpenSim/Data/SQLite/Resources/001_AssetStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/001_AssetStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/001_AssetStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/001_AssetStore.sql diff --git a/OpenSim/Data/SQLite/Resources/001_AuthStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/001_AuthStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/001_AuthStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/001_AuthStore.sql diff --git a/OpenSim/Data/SQLite/Resources/001_Avatar.sql b/OpenSim/Data/SQLiteLegacy/Resources/001_Avatar.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/001_Avatar.sql rename to OpenSim/Data/SQLiteLegacy/Resources/001_Avatar.sql diff --git a/OpenSim/Data/SQLite/Resources/001_FriendsStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/001_FriendsStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/001_FriendsStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/001_FriendsStore.sql diff --git a/OpenSim/Data/SQLite/Resources/001_InventoryStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/001_InventoryStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/001_InventoryStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/001_InventoryStore.sql diff --git a/OpenSim/Data/SQLite/Resources/001_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/001_RegionStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/001_RegionStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/001_RegionStore.sql diff --git a/OpenSim/Data/SQLite/Resources/001_UserAccount.sql b/OpenSim/Data/SQLiteLegacy/Resources/001_UserAccount.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/001_UserAccount.sql rename to OpenSim/Data/SQLiteLegacy/Resources/001_UserAccount.sql diff --git a/OpenSim/Data/SQLite/Resources/001_UserStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/001_UserStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/001_UserStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/001_UserStore.sql diff --git a/OpenSim/Data/SQLite/Resources/002_AssetStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/002_AssetStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/002_AssetStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/002_AssetStore.sql diff --git a/OpenSim/Data/SQLite/Resources/002_AuthStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/002_AuthStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/002_AuthStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/002_AuthStore.sql diff --git a/OpenSim/Data/SQLite/Resources/002_FriendsStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/002_FriendsStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/002_FriendsStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/002_FriendsStore.sql diff --git a/OpenSim/Data/SQLite/Resources/002_InventoryStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/002_InventoryStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/002_InventoryStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/002_InventoryStore.sql diff --git a/OpenSim/Data/SQLite/Resources/002_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/002_RegionStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/002_RegionStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/002_RegionStore.sql diff --git a/OpenSim/Data/SQLite/Resources/002_UserAccount.sql b/OpenSim/Data/SQLiteLegacy/Resources/002_UserAccount.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/002_UserAccount.sql rename to OpenSim/Data/SQLiteLegacy/Resources/002_UserAccount.sql diff --git a/OpenSim/Data/SQLite/Resources/002_UserStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/002_UserStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/002_UserStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/002_UserStore.sql diff --git a/OpenSim/Data/SQLite/Resources/003_AssetStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/003_AssetStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/003_AssetStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/003_AssetStore.sql diff --git a/OpenSim/Data/MySQL/Resources/003_InventoryStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/003_InventoryStore.sql similarity index 100% rename from OpenSim/Data/MySQL/Resources/003_InventoryStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/003_InventoryStore.sql diff --git a/OpenSim/Data/SQLite/Resources/003_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/003_RegionStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/003_RegionStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/003_RegionStore.sql diff --git a/OpenSim/Data/MySQL/Resources/003_UserStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/003_UserStore.sql similarity index 100% rename from OpenSim/Data/MySQL/Resources/003_UserStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/003_UserStore.sql diff --git a/OpenSim/Data/SQLite/Resources/004_AssetStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/004_AssetStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/004_AssetStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/004_AssetStore.sql diff --git a/OpenSim/Data/SQLite/Resources/004_InventoryStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/004_InventoryStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/004_InventoryStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/004_InventoryStore.sql diff --git a/OpenSim/Data/SQLite/Resources/004_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/004_RegionStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/004_RegionStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/004_RegionStore.sql diff --git a/OpenSim/Data/MySQL/Resources/004_UserStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/004_UserStore.sql similarity index 100% rename from OpenSim/Data/MySQL/Resources/004_UserStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/004_UserStore.sql diff --git a/OpenSim/Data/SQLite/Resources/005_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/005_RegionStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/005_RegionStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/005_RegionStore.sql diff --git a/OpenSim/Data/SQLite/Resources/005_UserStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/005_UserStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/005_UserStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/005_UserStore.sql diff --git a/OpenSim/Data/SQLite/Resources/006_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/006_RegionStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/006_RegionStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/006_RegionStore.sql diff --git a/OpenSim/Data/SQLite/Resources/006_UserStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/006_UserStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/006_UserStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/006_UserStore.sql diff --git a/OpenSim/Data/SQLite/Resources/007_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/007_RegionStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/007_RegionStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/007_RegionStore.sql diff --git a/OpenSim/Data/SQLite/Resources/007_UserStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/007_UserStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/007_UserStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/007_UserStore.sql diff --git a/OpenSim/Data/SQLite/Resources/008_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/008_RegionStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/008_RegionStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/008_RegionStore.sql diff --git a/OpenSim/Data/SQLite/Resources/008_UserStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/008_UserStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/008_UserStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/008_UserStore.sql diff --git a/OpenSim/Data/SQLite/Resources/009_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/009_RegionStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/009_RegionStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/009_RegionStore.sql diff --git a/OpenSim/Data/SQLite/Resources/009_UserStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/009_UserStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/009_UserStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/009_UserStore.sql diff --git a/OpenSim/Data/SQLite/Resources/010_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/010_RegionStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/010_RegionStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/010_RegionStore.sql diff --git a/OpenSim/Data/SQLite/Resources/010_UserStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/010_UserStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/010_UserStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/010_UserStore.sql diff --git a/OpenSim/Data/SQLite/Resources/011_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/011_RegionStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/011_RegionStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/011_RegionStore.sql diff --git a/OpenSim/Data/SQLite/Resources/012_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/012_RegionStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/012_RegionStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/012_RegionStore.sql diff --git a/OpenSim/Data/SQLite/Resources/013_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/013_RegionStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/013_RegionStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/013_RegionStore.sql diff --git a/OpenSim/Data/SQLite/Resources/014_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/014_RegionStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/014_RegionStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/014_RegionStore.sql diff --git a/OpenSim/Data/SQLite/Resources/015_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/015_RegionStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/015_RegionStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/015_RegionStore.sql diff --git a/OpenSim/Data/SQLite/Resources/016_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/016_RegionStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/016_RegionStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/016_RegionStore.sql diff --git a/OpenSim/Data/SQLite/Resources/017_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/017_RegionStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/017_RegionStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/017_RegionStore.sql diff --git a/OpenSim/Data/SQLite/Resources/018_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/018_RegionStore.sql similarity index 100% rename from OpenSim/Data/SQLite/Resources/018_RegionStore.sql rename to OpenSim/Data/SQLiteLegacy/Resources/018_RegionStore.sql diff --git a/OpenSim/Data/SQLiteLegacy/Resources/OpenSim.Data.SQLite.addin.xml b/OpenSim/Data/SQLiteLegacy/Resources/OpenSim.Data.SQLite.addin.xml new file mode 100644 index 0000000000..e6764facbd --- /dev/null +++ b/OpenSim/Data/SQLiteLegacy/Resources/OpenSim.Data.SQLite.addin.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/OpenSim/Data/SQLiteLegacy/SQLiteAssetData.cs b/OpenSim/Data/SQLiteLegacy/SQLiteAssetData.cs new file mode 100644 index 0000000000..df509023eb --- /dev/null +++ b/OpenSim/Data/SQLiteLegacy/SQLiteAssetData.cs @@ -0,0 +1,347 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Data; +using System.Reflection; +using System.Collections.Generic; +using log4net; +using Mono.Data.SqliteClient; +using OpenMetaverse; +using OpenSim.Framework; + +namespace OpenSim.Data.SQLiteLegacy +{ + /// + /// An asset storage interface for the SQLite database system + /// + public class SQLiteAssetData : AssetDataBase + { +// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private const string SelectAssetSQL = "select * from assets where UUID=:UUID"; + private const string SelectAssetMetadataSQL = "select Name, Description, Type, Temporary, UUID from assets limit :start, :count"; + private const string DeleteAssetSQL = "delete from assets where UUID=:UUID"; + private const string InsertAssetSQL = "insert into assets(UUID, Name, Description, Type, Local, Temporary, Data) values(:UUID, :Name, :Description, :Type, :Local, :Temporary, :Data)"; + private const string UpdateAssetSQL = "update assets set Name=:Name, Description=:Description, Type=:Type, Local=:Local, Temporary=:Temporary, Data=:Data where UUID=:UUID"; + private const string assetSelect = "select * from assets"; + + private SqliteConnection m_conn; + + override public void Dispose() + { + if (m_conn != null) + { + m_conn.Close(); + m_conn = null; + } + } + + /// + /// + /// Initialises AssetData interface + /// Loads and initialises a new SQLite connection and maintains it. + /// use default URI if connect string is empty. + /// + /// + /// connect string + override public void Initialise(string dbconnect) + { + if (dbconnect == string.Empty) + { + dbconnect = "URI=file:Asset.db,version=3"; + } + m_conn = new SqliteConnection(dbconnect); + m_conn.Open(); + + Assembly assem = GetType().Assembly; + Migration m = new Migration(m_conn, assem, "AssetStore"); + m.Update(); + + return; + } + + /// + /// Fetch Asset + /// + /// UUID of ... ? + /// Asset base + override public AssetBase GetAsset(UUID uuid) + { + lock (this) + { + using (SqliteCommand cmd = new SqliteCommand(SelectAssetSQL, m_conn)) + { + cmd.Parameters.Add(new SqliteParameter(":UUID", uuid.ToString())); + using (IDataReader reader = cmd.ExecuteReader()) + { + if (reader.Read()) + { + AssetBase asset = buildAsset(reader); + reader.Close(); + return asset; + } + else + { + reader.Close(); + return null; + } + } + } + } + } + + /// + /// Create an asset + /// + /// Asset Base + override public void StoreAsset(AssetBase asset) + { + //m_log.Info("[ASSET DB]: Creating Asset " + asset.FullID.ToString()); + if (ExistsAsset(asset.FullID)) + { + //LogAssetLoad(asset); + + lock (this) + { + using (SqliteCommand cmd = new SqliteCommand(UpdateAssetSQL, m_conn)) + { + cmd.Parameters.Add(new SqliteParameter(":UUID", asset.FullID.ToString())); + cmd.Parameters.Add(new SqliteParameter(":Name", asset.Name)); + cmd.Parameters.Add(new SqliteParameter(":Description", asset.Description)); + cmd.Parameters.Add(new SqliteParameter(":Type", asset.Type)); + cmd.Parameters.Add(new SqliteParameter(":Local", asset.Local)); + cmd.Parameters.Add(new SqliteParameter(":Temporary", asset.Temporary)); + cmd.Parameters.Add(new SqliteParameter(":Data", asset.Data)); + + cmd.ExecuteNonQuery(); + } + } + } + else + { + lock (this) + { + using (SqliteCommand cmd = new SqliteCommand(InsertAssetSQL, m_conn)) + { + cmd.Parameters.Add(new SqliteParameter(":UUID", asset.FullID.ToString())); + cmd.Parameters.Add(new SqliteParameter(":Name", asset.Name)); + cmd.Parameters.Add(new SqliteParameter(":Description", asset.Description)); + cmd.Parameters.Add(new SqliteParameter(":Type", asset.Type)); + cmd.Parameters.Add(new SqliteParameter(":Local", asset.Local)); + cmd.Parameters.Add(new SqliteParameter(":Temporary", asset.Temporary)); + cmd.Parameters.Add(new SqliteParameter(":Data", asset.Data)); + + cmd.ExecuteNonQuery(); + } + } + } + } + +// /// +// /// Some... logging functionnality +// /// +// /// +// private static void LogAssetLoad(AssetBase asset) +// { +// string temporary = asset.Temporary ? "Temporary" : "Stored"; +// string local = asset.Local ? "Local" : "Remote"; +// +// int assetLength = (asset.Data != null) ? asset.Data.Length : 0; +// +// m_log.Debug("[ASSET DB]: " + +// string.Format("Loaded {5} {4} Asset: [{0}][{3}] \"{1}\":{2} ({6} bytes)", +// asset.FullID, asset.Name, asset.Description, asset.Type, +// temporary, local, assetLength)); +// } + + /// + /// Check if an asset exist in database + /// + /// The asset UUID + /// True if exist, or false. + override public bool ExistsAsset(UUID uuid) + { + lock (this) { + using (SqliteCommand cmd = new SqliteCommand(SelectAssetSQL, m_conn)) + { + cmd.Parameters.Add(new SqliteParameter(":UUID", uuid.ToString())); + using (IDataReader reader = cmd.ExecuteReader()) + { + if (reader.Read()) + { + reader.Close(); + return true; + } + else + { + reader.Close(); + return false; + } + } + } + } + } + + /// + /// Delete an asset from database + /// + /// + public void DeleteAsset(UUID uuid) + { + using (SqliteCommand cmd = new SqliteCommand(DeleteAssetSQL, m_conn)) + { + cmd.Parameters.Add(new SqliteParameter(":UUID", uuid.ToString())); + + cmd.ExecuteNonQuery(); + } + } + + /// + /// + /// + /// + /// + private static AssetBase buildAsset(IDataReader row) + { + // TODO: this doesn't work yet because something more + // interesting has to be done to actually get these values + // back out. Not enough time to figure it out yet. + AssetBase asset = new AssetBase( + new UUID((String)row["UUID"]), + (String)row["Name"], + Convert.ToSByte(row["Type"]), + UUID.Zero.ToString() + ); + + asset.Description = (String) row["Description"]; + asset.Local = Convert.ToBoolean(row["Local"]); + asset.Temporary = Convert.ToBoolean(row["Temporary"]); + asset.Data = (byte[]) row["Data"]; + return asset; + } + + private static AssetMetadata buildAssetMetadata(IDataReader row) + { + AssetMetadata metadata = new AssetMetadata(); + + metadata.FullID = new UUID((string) row["UUID"]); + metadata.Name = (string) row["Name"]; + metadata.Description = (string) row["Description"]; + metadata.Type = Convert.ToSByte(row["Type"]); + metadata.Temporary = Convert.ToBoolean(row["Temporary"]); // Not sure if this is correct. + + // Current SHA1s are not stored/computed. + metadata.SHA1 = new byte[] {}; + + return metadata; + } + + /// + /// Returns a list of AssetMetadata objects. The list is a subset of + /// the entire data set offset by containing + /// elements. + /// + /// The number of results to discard from the total data set. + /// The number of rows the returned list should contain. + /// A list of AssetMetadata objects. + public override List FetchAssetMetadataSet(int start, int count) + { + List retList = new List(count); + + lock (this) + { + using (SqliteCommand cmd = new SqliteCommand(SelectAssetMetadataSQL, m_conn)) + { + cmd.Parameters.Add(new SqliteParameter(":start", start)); + cmd.Parameters.Add(new SqliteParameter(":count", count)); + + using (IDataReader reader = cmd.ExecuteReader()) + { + while (reader.Read()) + { + AssetMetadata metadata = buildAssetMetadata(reader); + retList.Add(metadata); + } + } + } + } + + return retList; + } + + /*********************************************************************** + * + * Database Binding functions + * + * These will be db specific due to typing, and minor differences + * in databases. + * + **********************************************************************/ + + #region IPlugin interface + + /// + /// + /// + override public string Version + { + get + { + Module module = GetType().Module; + // string dllName = module.Assembly.ManifestModule.Name; + Version dllVersion = module.Assembly.GetName().Version; + + return + string.Format("{0}.{1}.{2}.{3}", dllVersion.Major, dllVersion.Minor, dllVersion.Build, + dllVersion.Revision); + } + } + + /// + /// Initialise the AssetData interface using default URI + /// + override public void Initialise() + { + Initialise("URI=file:Asset.db,version=3"); + } + + /// + /// Name of this DB provider + /// + override public string Name + { + get { return "SQLite Asset storage engine"; } + } + + public override bool Delete(string id) + { + return false; + } + #endregion + } +} diff --git a/OpenSim/Data/SQLiteLegacy/SQLiteAuthenticationData.cs b/OpenSim/Data/SQLiteLegacy/SQLiteAuthenticationData.cs new file mode 100644 index 0000000000..760221d9fe --- /dev/null +++ b/OpenSim/Data/SQLiteLegacy/SQLiteAuthenticationData.cs @@ -0,0 +1,266 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Reflection; +using log4net; +using OpenMetaverse; +using OpenSim.Framework; +using Mono.Data.SqliteClient; + +namespace OpenSim.Data.SQLiteLegacy +{ + public class SQLiteAuthenticationData : SQLiteFramework, IAuthenticationData + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private string m_Realm; + private List m_ColumnNames; + private int m_LastExpire; + private string m_connectionString; + + protected static SqliteConnection m_Connection; + private static bool m_initialized = false; + + public SQLiteAuthenticationData(string connectionString, string realm) + : base(connectionString) + { + m_Realm = realm; + m_connectionString = connectionString; + + if (!m_initialized) + { + m_Connection = new SqliteConnection(connectionString); + m_Connection.Open(); + + using (SqliteConnection dbcon = (SqliteConnection)((ICloneable)m_Connection).Clone()) + { + dbcon.Open(); + Migration m = new Migration(dbcon, GetType().Assembly, "AuthStore"); + m.Update(); + dbcon.Close(); + } + + m_initialized = true; + } + } + + public AuthenticationData Get(UUID principalID) + { + AuthenticationData ret = new AuthenticationData(); + ret.Data = new Dictionary(); + + SqliteCommand cmd = new SqliteCommand("select * from `" + m_Realm + "` where UUID = :PrincipalID"); + cmd.Parameters.Add(new SqliteParameter(":PrincipalID", principalID.ToString())); + + IDataReader result = ExecuteReader(cmd, m_Connection); + + try + { + if (result.Read()) + { + ret.PrincipalID = principalID; + + if (m_ColumnNames == null) + { + m_ColumnNames = new List(); + + DataTable schemaTable = result.GetSchemaTable(); + foreach (DataRow row in schemaTable.Rows) + m_ColumnNames.Add(row["ColumnName"].ToString()); + } + + foreach (string s in m_ColumnNames) + { + if (s == "UUID") + continue; + + ret.Data[s] = result[s].ToString(); + } + + return ret; + } + else + { + return null; + } + } + catch + { + } + finally + { + CloseCommand(cmd); + } + + return null; + } + + public bool Store(AuthenticationData data) + { + if (data.Data.ContainsKey("UUID")) + data.Data.Remove("UUID"); + + string[] fields = new List(data.Data.Keys).ToArray(); + string[] values = new string[data.Data.Count]; + int i = 0; + foreach (object o in data.Data.Values) + values[i++] = o.ToString(); + + SqliteCommand cmd = new SqliteCommand(); + + if (Get(data.PrincipalID) != null) + { + + + string update = "update `" + m_Realm + "` set "; + bool first = true; + foreach (string field in fields) + { + if (!first) + update += ", "; + update += "`" + field + "` = :" + field; + cmd.Parameters.Add(new SqliteParameter(":" + field, data.Data[field])); + + first = false; + } + + update += " where UUID = :UUID"; + cmd.Parameters.Add(new SqliteParameter(":UUID", data.PrincipalID.ToString())); + + cmd.CommandText = update; + try + { + if (ExecuteNonQuery(cmd, m_Connection) < 1) + { + CloseCommand(cmd); + return false; + } + } + catch (Exception e) + { + m_log.Error("[SQLITE]: Exception storing authentication data", e); + CloseCommand(cmd); + return false; + } + } + + else + { + string insert = "insert into `" + m_Realm + "` (`UUID`, `" + + String.Join("`, `", fields) + + "`) values (:UUID, :" + String.Join(", :", fields) + ")"; + + cmd.Parameters.Add(new SqliteParameter(":UUID", data.PrincipalID.ToString())); + foreach (string field in fields) + cmd.Parameters.Add(new SqliteParameter(":" + field, data.Data[field])); + + cmd.CommandText = insert; + + try + { + if (ExecuteNonQuery(cmd, m_Connection) < 1) + { + CloseCommand(cmd); + return false; + } + } + catch (Exception e) + { + Console.WriteLine(e.ToString()); + CloseCommand(cmd); + return false; + } + } + + CloseCommand(cmd); + + return true; + } + + public bool SetDataItem(UUID principalID, string item, string value) + { + SqliteCommand cmd = new SqliteCommand("update `" + m_Realm + + "` set `" + item + "` = " + value + " where UUID = '" + principalID.ToString() + "'"); + + if (ExecuteNonQuery(cmd, m_Connection) > 0) + return true; + + return false; + } + + public bool SetToken(UUID principalID, string token, int lifetime) + { + if (System.Environment.TickCount - m_LastExpire > 30000) + DoExpire(); + + SqliteCommand cmd = new SqliteCommand("insert into tokens (UUID, token, validity) values ('" + principalID.ToString() + + "', '" + token + "', datetime('now', 'localtime', '+" + lifetime.ToString() + " minutes'))"); + + if (ExecuteNonQuery(cmd, m_Connection) > 0) + { + cmd.Dispose(); + return true; + } + + cmd.Dispose(); + return false; + } + + public bool CheckToken(UUID principalID, string token, int lifetime) + { + if (System.Environment.TickCount - m_LastExpire > 30000) + DoExpire(); + + SqliteCommand cmd = new SqliteCommand("update tokens set validity = datetime('now', 'localtime', '+" + lifetime.ToString() + + " minutes') where UUID = '" + principalID.ToString() + "' and token = '" + token + "' and validity > datetime('now', 'localtime')"); + + if (ExecuteNonQuery(cmd, m_Connection) > 0) + { + cmd.Dispose(); + return true; + } + + cmd.Dispose(); + + return false; + } + + private void DoExpire() + { + SqliteCommand cmd = new SqliteCommand("delete from tokens where validity < datetime('now', 'localtime')"); + ExecuteNonQuery(cmd, m_Connection); + + cmd.Dispose(); + + m_LastExpire = System.Environment.TickCount; + } + } +} diff --git a/OpenSim/Data/SQLite/Tests/SQLiteInventoryTest.cs b/OpenSim/Data/SQLiteLegacy/SQLiteAvatarData.cs similarity index 57% rename from OpenSim/Data/SQLite/Tests/SQLiteInventoryTest.cs rename to OpenSim/Data/SQLiteLegacy/SQLiteAvatarData.cs index 98458a30ec..660632ca07 100644 --- a/OpenSim/Data/SQLite/Tests/SQLiteInventoryTest.cs +++ b/OpenSim/Data/SQLiteLegacy/SQLiteAvatarData.cs @@ -25,42 +25,50 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -using System.IO; -using NUnit.Framework; -using OpenSim.Data.Tests; -using OpenSim.Tests.Common; +using System; +using System.Collections.Generic; +using System.Data; +using System.Reflection; +using System.Threading; +using log4net; +using OpenMetaverse; +using OpenSim.Framework; +using Mono.Data.SqliteClient; -namespace OpenSim.Data.SQLite.Tests +namespace OpenSim.Data.SQLiteLegacy { - [TestFixture, DatabaseTest] - public class SQLiteInventoryTest : BasicInventoryTest + /// + /// A SQLite Interface for Avatar Data + /// + public class SQLiteAvatarData : SQLiteGenericTableHandler, + IAvatarData { - public string file; - public string connect; - - [TestFixtureSetUp] - public void Init() - { - // SQLite doesn't work on power or z linux - if (Directory.Exists("/proc/ppc64") || Directory.Exists("/proc/dasd")) - { - Assert.Ignore(); - } + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - SuperInit(); - - file = Path.GetTempFileName() + ".db"; - connect = "URI=file:" + file + ",version=3"; - - db = new SQLiteInventoryStore(); - db.Initialise(connect); + public SQLiteAvatarData(string connectionString, string realm) : + base(connectionString, realm, "Avatar") + { } - [TestFixtureTearDown] - public void Cleanup() + public bool Delete(UUID principalID, string name) { - db.Dispose(); - File.Delete(file); + SqliteCommand cmd = new SqliteCommand(); + + cmd.CommandText = String.Format("delete from {0} where `PrincipalID` = :PrincipalID and `Name` = :Name", m_Realm); + cmd.Parameters.Add(":PrincipalID", principalID.ToString()); + cmd.Parameters.Add(":Name", name); + + try + { + if (ExecuteNonQuery(cmd, m_Connection) > 0) + return true; + + return false; + } + finally + { + CloseCommand(cmd); + } } } } diff --git a/OpenSim/Data/SQLiteLegacy/SQLiteEstateData.cs b/OpenSim/Data/SQLiteLegacy/SQLiteEstateData.cs new file mode 100644 index 0000000000..e135eaa524 --- /dev/null +++ b/OpenSim/Data/SQLiteLegacy/SQLiteEstateData.cs @@ -0,0 +1,387 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; +using System.Data; +using System.Reflection; +using log4net; +using Mono.Data.SqliteClient; +using OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Region.Framework.Interfaces; + +namespace OpenSim.Data.SQLiteLegacy +{ + public class SQLiteEstateStore : IEstateDataStore + { + private static readonly ILog m_log = + LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private SqliteConnection m_connection; + private string m_connectionString; + + private FieldInfo[] m_Fields; + private Dictionary m_FieldMap = + new Dictionary(); + + public void Initialise(string connectionString) + { + m_connectionString = connectionString; + + m_log.Info("[ESTATE DB]: Sqlite - connecting: "+m_connectionString); + + m_connection = new SqliteConnection(m_connectionString); + m_connection.Open(); + + Assembly assem = GetType().Assembly; + Migration m = new Migration(m_connection, assem, "EstateStore"); + m.Update(); + + m_connection.Close(); + m_connection.Open(); + + Type t = typeof(EstateSettings); + m_Fields = t.GetFields(BindingFlags.NonPublic | + BindingFlags.Instance | + BindingFlags.DeclaredOnly); + + foreach (FieldInfo f in m_Fields) + if (f.Name.Substring(0, 2) == "m_") + m_FieldMap[f.Name.Substring(2)] = f; + } + + private string[] FieldList + { + get { return new List(m_FieldMap.Keys).ToArray(); } + } + + public EstateSettings LoadEstateSettings(UUID regionID, bool create) + { + string sql = "select estate_settings."+String.Join(",estate_settings.", FieldList)+" from estate_map left join estate_settings on estate_map.EstateID = estate_settings.EstateID where estate_settings.EstateID is not null and RegionID = :RegionID"; + + SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand(); + + cmd.CommandText = sql; + cmd.Parameters.Add(":RegionID", regionID.ToString()); + + return DoLoad(cmd, regionID, create); + } + + private EstateSettings DoLoad(SqliteCommand cmd, UUID regionID, bool create) + { + EstateSettings es = new EstateSettings(); + es.OnSave += StoreEstateSettings; + + IDataReader r = cmd.ExecuteReader(); + + if (r.Read()) + { + foreach (string name in FieldList) + { + if (m_FieldMap[name].GetValue(es) is bool) + { + int v = Convert.ToInt32(r[name]); + if (v != 0) + m_FieldMap[name].SetValue(es, true); + else + m_FieldMap[name].SetValue(es, false); + } + else if (m_FieldMap[name].GetValue(es) is UUID) + { + UUID uuid = UUID.Zero; + + UUID.TryParse(r[name].ToString(), out uuid); + m_FieldMap[name].SetValue(es, uuid); + } + else + { + m_FieldMap[name].SetValue(es, Convert.ChangeType(r[name], m_FieldMap[name].FieldType)); + } + } + r.Close(); + } + else if (create) + { + r.Close(); + + List names = new List(FieldList); + + names.Remove("EstateID"); + + string sql = "insert into estate_settings ("+String.Join(",", names.ToArray())+") values ( :"+String.Join(", :", names.ToArray())+")"; + + cmd.CommandText = sql; + cmd.Parameters.Clear(); + + foreach (string name in FieldList) + { + if (m_FieldMap[name].GetValue(es) is bool) + { + if ((bool)m_FieldMap[name].GetValue(es)) + cmd.Parameters.Add(":"+name, "1"); + else + cmd.Parameters.Add(":"+name, "0"); + } + else + { + cmd.Parameters.Add(":"+name, m_FieldMap[name].GetValue(es).ToString()); + } + } + + cmd.ExecuteNonQuery(); + + cmd.CommandText = "select LAST_INSERT_ROWID() as id"; + cmd.Parameters.Clear(); + + r = cmd.ExecuteReader(); + + r.Read(); + + es.EstateID = Convert.ToUInt32(r["id"]); + + r.Close(); + + cmd.CommandText = "insert into estate_map values (:RegionID, :EstateID)"; + cmd.Parameters.Add(":RegionID", regionID.ToString()); + cmd.Parameters.Add(":EstateID", es.EstateID.ToString()); + + // This will throw on dupe key + try + { + cmd.ExecuteNonQuery(); + } + catch (Exception) + { + } + + es.Save(); + } + + LoadBanList(es); + + es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers"); + es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users"); + es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups"); + return es; + } + + public void StoreEstateSettings(EstateSettings es) + { + List fields = new List(FieldList); + fields.Remove("EstateID"); + + List terms = new List(); + + foreach (string f in fields) + terms.Add(f+" = :"+f); + + string sql = "update estate_settings set "+String.Join(", ", terms.ToArray())+" where EstateID = :EstateID"; + + SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand(); + + cmd.CommandText = sql; + + foreach (string name in FieldList) + { + if (m_FieldMap[name].GetValue(es) is bool) + { + if ((bool)m_FieldMap[name].GetValue(es)) + cmd.Parameters.Add(":"+name, "1"); + else + cmd.Parameters.Add(":"+name, "0"); + } + else + { + cmd.Parameters.Add(":"+name, m_FieldMap[name].GetValue(es).ToString()); + } + } + + cmd.ExecuteNonQuery(); + + SaveBanList(es); + SaveUUIDList(es.EstateID, "estate_managers", es.EstateManagers); + SaveUUIDList(es.EstateID, "estate_users", es.EstateAccess); + SaveUUIDList(es.EstateID, "estate_groups", es.EstateGroups); + } + + private void LoadBanList(EstateSettings es) + { + es.ClearBans(); + + SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand(); + + cmd.CommandText = "select bannedUUID from estateban where EstateID = :EstateID"; + cmd.Parameters.Add(":EstateID", es.EstateID); + + IDataReader r = cmd.ExecuteReader(); + + while (r.Read()) + { + EstateBan eb = new EstateBan(); + + UUID uuid = new UUID(); + UUID.TryParse(r["bannedUUID"].ToString(), out uuid); + + eb.BannedUserID = uuid; + eb.BannedHostAddress = "0.0.0.0"; + eb.BannedHostIPMask = "0.0.0.0"; + es.AddBan(eb); + } + r.Close(); + } + + private void SaveBanList(EstateSettings es) + { + SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand(); + + cmd.CommandText = "delete from estateban where EstateID = :EstateID"; + cmd.Parameters.Add(":EstateID", es.EstateID.ToString()); + + cmd.ExecuteNonQuery(); + + cmd.Parameters.Clear(); + + cmd.CommandText = "insert into estateban (EstateID, bannedUUID, bannedIp, bannedIpHostMask, bannedNameMask) values ( :EstateID, :bannedUUID, '', '', '' )"; + + foreach (EstateBan b in es.EstateBans) + { + cmd.Parameters.Add(":EstateID", es.EstateID.ToString()); + cmd.Parameters.Add(":bannedUUID", b.BannedUserID.ToString()); + + cmd.ExecuteNonQuery(); + cmd.Parameters.Clear(); + } + } + + void SaveUUIDList(uint EstateID, string table, UUID[] data) + { + SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand(); + + cmd.CommandText = "delete from "+table+" where EstateID = :EstateID"; + cmd.Parameters.Add(":EstateID", EstateID.ToString()); + + cmd.ExecuteNonQuery(); + + cmd.Parameters.Clear(); + + cmd.CommandText = "insert into "+table+" (EstateID, uuid) values ( :EstateID, :uuid )"; + + foreach (UUID uuid in data) + { + cmd.Parameters.Add(":EstateID", EstateID.ToString()); + cmd.Parameters.Add(":uuid", uuid.ToString()); + + cmd.ExecuteNonQuery(); + cmd.Parameters.Clear(); + } + } + + UUID[] LoadUUIDList(uint EstateID, string table) + { + List uuids = new List(); + + SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand(); + + cmd.CommandText = "select uuid from "+table+" where EstateID = :EstateID"; + cmd.Parameters.Add(":EstateID", EstateID); + + IDataReader r = cmd.ExecuteReader(); + + while (r.Read()) + { + // EstateBan eb = new EstateBan(); + + UUID uuid = new UUID(); + UUID.TryParse(r["uuid"].ToString(), out uuid); + + uuids.Add(uuid); + } + r.Close(); + + return uuids.ToArray(); + } + + public EstateSettings LoadEstateSettings(int estateID) + { + string sql = "select estate_settings."+String.Join(",estate_settings.", FieldList)+" from estate_settings where estate_settings.EstateID :EstateID"; + + SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand(); + + cmd.CommandText = sql; + cmd.Parameters.Add(":EstateID", estateID.ToString()); + + return DoLoad(cmd, UUID.Zero, false); + } + + public List GetEstates(string search) + { + List result = new List(); + + string sql = "select EstateID from estate_settings where estate_settings.EstateName :EstateName"; + + SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand(); + + cmd.CommandText = sql; + cmd.Parameters.Add(":EstateName", search); + + IDataReader r = cmd.ExecuteReader(); + + while (r.Read()) + { + result.Add(Convert.ToInt32(r["EstateID"])); + } + r.Close(); + + return result; + } + + public bool LinkRegion(UUID regionID, int estateID) + { + SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand(); + + cmd.CommandText = "insert into estate_map values (:RegionID, :EstateID)"; + cmd.Parameters.Add(":RegionID", regionID.ToString()); + cmd.Parameters.Add(":EstateID", estateID.ToString()); + + if (cmd.ExecuteNonQuery() == 0) + return false; + + return true; + } + + public List GetRegions(int estateID) + { + return new List(); + } + + public bool DeleteEstate(int estateID) + { + return false; + } + } +} diff --git a/OpenSim/Data/SQLiteLegacy/SQLiteFramework.cs b/OpenSim/Data/SQLiteLegacy/SQLiteFramework.cs new file mode 100644 index 0000000000..606478ea7e --- /dev/null +++ b/OpenSim/Data/SQLiteLegacy/SQLiteFramework.cs @@ -0,0 +1,91 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using OpenMetaverse; +using OpenSim.Framework; +using Mono.Data.SqliteClient; + +namespace OpenSim.Data.SQLiteLegacy +{ + /// + /// A database interface class to a user profile storage system + /// + public class SQLiteFramework + { + protected Object m_lockObject = new Object(); + + protected SQLiteFramework(string connectionString) + { + } + + ////////////////////////////////////////////////////////////// + // + // All non queries are funneled through one connection + // to increase performance a little + // + protected int ExecuteNonQuery(SqliteCommand cmd, SqliteConnection connection) + { + lock (connection) + { + SqliteConnection newConnection = + (SqliteConnection)((ICloneable)connection).Clone(); + newConnection.Open(); + + cmd.Connection = newConnection; + //Console.WriteLine("XXX " + cmd.CommandText); + + return cmd.ExecuteNonQuery(); + } + } + + protected IDataReader ExecuteReader(SqliteCommand cmd, SqliteConnection connection) + { + lock (connection) + { + SqliteConnection newConnection = + (SqliteConnection)((ICloneable)connection).Clone(); + newConnection.Open(); + + cmd.Connection = newConnection; + //Console.WriteLine("XXX " + cmd.CommandText); + + return cmd.ExecuteReader(); + } + } + + protected void CloseCommand(SqliteCommand cmd) + { + cmd.Connection.Close(); + cmd.Connection.Dispose(); + cmd.Dispose(); + } + } +} diff --git a/OpenSim/Data/SQLite/Tests/SQLiteRegionTest.cs b/OpenSim/Data/SQLiteLegacy/SQLiteFriendsData.cs similarity index 55% rename from OpenSim/Data/SQLite/Tests/SQLiteRegionTest.cs rename to OpenSim/Data/SQLiteLegacy/SQLiteFriendsData.cs index abb97cfa4f..d529d4d8ab 100644 --- a/OpenSim/Data/SQLite/Tests/SQLiteRegionTest.cs +++ b/OpenSim/Data/SQLiteLegacy/SQLiteFriendsData.cs @@ -25,40 +25,46 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -using System.IO; -using NUnit.Framework; -using OpenSim.Data.Tests; -using OpenSim.Tests.Common; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using OpenMetaverse; +using OpenSim.Framework; +using Mono.Data.SqliteClient; -namespace OpenSim.Data.SQLite.Tests +namespace OpenSim.Data.SQLiteLegacy { - [TestFixture, DatabaseTest] - public class SQLiteRegionTest : BasicRegionTest + public class SQLiteFriendsData : SQLiteGenericTableHandler, IFriendsData { - public string file = "regiontest.db"; - public string connect; - - [TestFixtureSetUp] - public void Init() + public SQLiteFriendsData(string connectionString, string realm) + : base(connectionString, realm, "FriendsStore") { - // SQLite doesn't work on power or z linux - if (Directory.Exists("/proc/ppc64") || Directory.Exists("/proc/dasd")) - { - Assert.Ignore(); - } - - SuperInit(); - file = Path.GetTempFileName() + ".db"; - connect = "URI=file:" + file + ",version=3"; - db = new SQLiteRegionData(); - db.Initialise(connect); } - [TestFixtureTearDown] - public void Cleanup() + public FriendsData[] GetFriends(UUID userID) { - db.Dispose(); - File.Delete(file); + SqliteCommand cmd = new SqliteCommand(); + + cmd.CommandText = String.Format("select a.*,case when b.Flags is null then -1 else b.Flags end as TheirFlags from {0} as a left join {0} as b on a.PrincipalID = b.Friend and a.Friend = b.PrincipalID where a.PrincipalID = :PrincipalID", m_Realm); + cmd.Parameters.Add(":PrincipalID", userID.ToString()); + + return DoQuery(cmd); + } + + public bool Delete(UUID principalID, string friend) + { + SqliteCommand cmd = new SqliteCommand(); + + cmd.CommandText = String.Format("delete from {0} where PrincipalID = :PrincipalID and Friend = :Friend", m_Realm); + cmd.Parameters.Add(":PrincipalID", principalID.ToString()); + cmd.Parameters.Add(":Friend", friend); + + ExecuteNonQuery(cmd, cmd.Connection); + + return true; + } + } } diff --git a/OpenSim/Data/SQLiteLegacy/SQLiteGenericTableHandler.cs b/OpenSim/Data/SQLiteLegacy/SQLiteGenericTableHandler.cs new file mode 100644 index 0000000000..1c1fe8cc0f --- /dev/null +++ b/OpenSim/Data/SQLiteLegacy/SQLiteGenericTableHandler.cs @@ -0,0 +1,268 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; +using System.Data; +using System.Reflection; +using log4net; +using Mono.Data.SqliteClient; +using OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Region.Framework.Interfaces; + +namespace OpenSim.Data.SQLiteLegacy +{ + public class SQLiteGenericTableHandler : SQLiteFramework where T: class, new() + { +// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + protected Dictionary m_Fields = + new Dictionary(); + + protected List m_ColumnNames = null; + protected string m_Realm; + protected FieldInfo m_DataField = null; + + protected static SqliteConnection m_Connection; + private static bool m_initialized; + + public SQLiteGenericTableHandler(string connectionString, + string realm, string storeName) : base(connectionString) + { + m_Realm = realm; + + if (!m_initialized) + { + m_Connection = new SqliteConnection(connectionString); + m_Connection.Open(); + + if (storeName != String.Empty) + { + Assembly assem = GetType().Assembly; + SqliteConnection newConnection = + (SqliteConnection)((ICloneable)m_Connection).Clone(); + newConnection.Open(); + + Migration m = new Migration(newConnection, assem, storeName); + m.Update(); + newConnection.Close(); + newConnection.Dispose(); + } + + m_initialized = true; + } + + Type t = typeof(T); + FieldInfo[] fields = t.GetFields(BindingFlags.Public | + BindingFlags.Instance | + BindingFlags.DeclaredOnly); + + if (fields.Length == 0) + return; + + foreach (FieldInfo f in fields) + { + if (f.Name != "Data") + m_Fields[f.Name] = f; + else + m_DataField = f; + } + } + + private void CheckColumnNames(IDataReader reader) + { + if (m_ColumnNames != null) + return; + + m_ColumnNames = new List(); + + DataTable schemaTable = reader.GetSchemaTable(); + foreach (DataRow row in schemaTable.Rows) + { + if (row["ColumnName"] != null && + (!m_Fields.ContainsKey(row["ColumnName"].ToString()))) + m_ColumnNames.Add(row["ColumnName"].ToString()); + } + } + + public T[] Get(string field, string key) + { + return Get(new string[] { field }, new string[] { key }); + } + + public T[] Get(string[] fields, string[] keys) + { + if (fields.Length != keys.Length) + return new T[0]; + + List terms = new List(); + + SqliteCommand cmd = new SqliteCommand(); + + for (int i = 0 ; i < fields.Length ; i++) + { + cmd.Parameters.Add(new SqliteParameter(":" + fields[i], keys[i])); + terms.Add("`" + fields[i] + "` = :" + fields[i]); + } + + string where = String.Join(" and ", terms.ToArray()); + + string query = String.Format("select * from {0} where {1}", + m_Realm, where); + + cmd.CommandText = query; + + return DoQuery(cmd); + } + + protected T[] DoQuery(SqliteCommand cmd) + { + IDataReader reader = ExecuteReader(cmd, m_Connection); + if (reader == null) + return new T[0]; + + CheckColumnNames(reader); + + List result = new List(); + + while (reader.Read()) + { + T row = new T(); + + foreach (string name in m_Fields.Keys) + { + if (m_Fields[name].GetValue(row) is bool) + { + int v = Convert.ToInt32(reader[name]); + m_Fields[name].SetValue(row, v != 0 ? true : false); + } + else if (m_Fields[name].GetValue(row) is UUID) + { + UUID uuid = UUID.Zero; + + UUID.TryParse(reader[name].ToString(), out uuid); + m_Fields[name].SetValue(row, uuid); + } + else if (m_Fields[name].GetValue(row) is int) + { + int v = Convert.ToInt32(reader[name]); + m_Fields[name].SetValue(row, v); + } + else + { + m_Fields[name].SetValue(row, reader[name]); + } + } + + if (m_DataField != null) + { + Dictionary data = + new Dictionary(); + + foreach (string col in m_ColumnNames) + { + data[col] = reader[col].ToString(); + if (data[col] == null) + data[col] = String.Empty; + } + + m_DataField.SetValue(row, data); + } + + result.Add(row); + } + + CloseCommand(cmd); + + return result.ToArray(); + } + + public T[] Get(string where) + { + SqliteCommand cmd = new SqliteCommand(); + + string query = String.Format("select * from {0} where {1}", + m_Realm, where); + + cmd.CommandText = query; + + return DoQuery(cmd); + } + + public bool Store(T row) + { + SqliteCommand cmd = new SqliteCommand(); + + string query = ""; + List names = new List(); + List values = new List(); + + foreach (FieldInfo fi in m_Fields.Values) + { + names.Add(fi.Name); + values.Add(":" + fi.Name); + cmd.Parameters.Add(new SqliteParameter(":" + fi.Name, fi.GetValue(row).ToString())); + } + + if (m_DataField != null) + { + Dictionary data = + (Dictionary)m_DataField.GetValue(row); + + foreach (KeyValuePair kvp in data) + { + names.Add(kvp.Key); + values.Add(":" + kvp.Key); + cmd.Parameters.Add(new SqliteParameter(":" + kvp.Key, kvp.Value)); + } + } + + query = String.Format("replace into {0} (`", m_Realm) + String.Join("`,`", names.ToArray()) + "`) values (" + String.Join(",", values.ToArray()) + ")"; + + cmd.CommandText = query; + + if (ExecuteNonQuery(cmd, m_Connection) > 0) + return true; + + return false; + } + + public bool Delete(string field, string val) + { + SqliteCommand cmd = new SqliteCommand(); + + cmd.CommandText = String.Format("delete from {0} where `{1}` = :{1}", m_Realm, field); + cmd.Parameters.Add(new SqliteParameter(field, val)); + + if (ExecuteNonQuery(cmd, m_Connection) > 0) + return true; + + return false; + } + } +} diff --git a/OpenSim/Data/SQLiteLegacy/SQLiteInventoryStore.cs b/OpenSim/Data/SQLiteLegacy/SQLiteInventoryStore.cs new file mode 100644 index 0000000000..726703b79d --- /dev/null +++ b/OpenSim/Data/SQLiteLegacy/SQLiteInventoryStore.cs @@ -0,0 +1,898 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; +using System.Data; +using System.Reflection; +using log4net; +using Mono.Data.SqliteClient; +using OpenMetaverse; +using OpenSim.Framework; + +namespace OpenSim.Data.SQLiteLegacy +{ + /// + /// An Inventory Interface to the SQLite database + /// + public class SQLiteInventoryStore : SQLiteUtil, IInventoryDataPlugin + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private const string invItemsSelect = "select * from inventoryitems"; + private const string invFoldersSelect = "select * from inventoryfolders"; + + private static SqliteConnection conn; + private static DataSet ds; + private static SqliteDataAdapter invItemsDa; + private static SqliteDataAdapter invFoldersDa; + + private static bool m_Initialized = false; + + public void Initialise() + { + m_log.Info("[SQLiteInventoryData]: " + Name + " cannot be default-initialized!"); + throw new PluginNotInitialisedException(Name); + } + + /// + /// + /// Initialises Inventory interface + /// Loads and initialises a new SQLite connection and maintains it. + /// use default URI if connect string string is empty. + /// + /// + /// connect string + public void Initialise(string dbconnect) + { + if (!m_Initialized) + { + m_Initialized = true; + + if (dbconnect == string.Empty) + { + dbconnect = "URI=file:inventoryStore.db,version=3"; + } + m_log.Info("[INVENTORY DB]: Sqlite - connecting: " + dbconnect); + conn = new SqliteConnection(dbconnect); + + conn.Open(); + + Assembly assem = GetType().Assembly; + Migration m = new Migration(conn, assem, "InventoryStore"); + m.Update(); + + SqliteCommand itemsSelectCmd = new SqliteCommand(invItemsSelect, conn); + invItemsDa = new SqliteDataAdapter(itemsSelectCmd); + // SqliteCommandBuilder primCb = new SqliteCommandBuilder(primDa); + + SqliteCommand foldersSelectCmd = new SqliteCommand(invFoldersSelect, conn); + invFoldersDa = new SqliteDataAdapter(foldersSelectCmd); + + ds = new DataSet(); + + ds.Tables.Add(createInventoryFoldersTable()); + invFoldersDa.Fill(ds.Tables["inventoryfolders"]); + setupFoldersCommands(invFoldersDa, conn); + m_log.Info("[INVENTORY DB]: Populated Inventory Folders Definitions"); + + ds.Tables.Add(createInventoryItemsTable()); + invItemsDa.Fill(ds.Tables["inventoryitems"]); + setupItemsCommands(invItemsDa, conn); + m_log.Info("[INVENTORY DB]: Populated Inventory Items Definitions"); + + ds.AcceptChanges(); + } + } + + /// + /// Closes the inventory interface + /// + public void Dispose() + { + if (conn != null) + { + conn.Close(); + conn = null; + } + if (invItemsDa != null) + { + invItemsDa.Dispose(); + invItemsDa = null; + } + if (invFoldersDa != null) + { + invFoldersDa.Dispose(); + invFoldersDa = null; + } + if (ds != null) + { + ds.Dispose(); + ds = null; + } + } + + /// + /// + /// + /// + /// + public InventoryItemBase buildItem(DataRow row) + { + InventoryItemBase item = new InventoryItemBase(); + item.ID = new UUID((string) row["UUID"]); + item.AssetID = new UUID((string) row["assetID"]); + item.AssetType = Convert.ToInt32(row["assetType"]); + item.InvType = Convert.ToInt32(row["invType"]); + item.Folder = new UUID((string) row["parentFolderID"]); + item.Owner = new UUID((string) row["avatarID"]); + item.CreatorId = (string)row["creatorsID"]; + item.Name = (string) row["inventoryName"]; + item.Description = (string) row["inventoryDescription"]; + + item.NextPermissions = Convert.ToUInt32(row["inventoryNextPermissions"]); + item.CurrentPermissions = Convert.ToUInt32(row["inventoryCurrentPermissions"]); + item.BasePermissions = Convert.ToUInt32(row["inventoryBasePermissions"]); + item.EveryOnePermissions = Convert.ToUInt32(row["inventoryEveryOnePermissions"]); + item.GroupPermissions = Convert.ToUInt32(row["inventoryGroupPermissions"]); + + // new fields + if (!Convert.IsDBNull(row["salePrice"])) + item.SalePrice = Convert.ToInt32(row["salePrice"]); + + if (!Convert.IsDBNull(row["saleType"])) + item.SaleType = Convert.ToByte(row["saleType"]); + + if (!Convert.IsDBNull(row["creationDate"])) + item.CreationDate = Convert.ToInt32(row["creationDate"]); + + if (!Convert.IsDBNull(row["groupID"])) + item.GroupID = new UUID((string)row["groupID"]); + + if (!Convert.IsDBNull(row["groupOwned"])) + item.GroupOwned = Convert.ToBoolean(row["groupOwned"]); + + if (!Convert.IsDBNull(row["Flags"])) + item.Flags = Convert.ToUInt32(row["Flags"]); + + return item; + } + + /// + /// Fill a database row with item data + /// + /// + /// + private static void fillItemRow(DataRow row, InventoryItemBase item) + { + row["UUID"] = item.ID.ToString(); + row["assetID"] = item.AssetID.ToString(); + row["assetType"] = item.AssetType; + row["invType"] = item.InvType; + row["parentFolderID"] = item.Folder.ToString(); + row["avatarID"] = item.Owner.ToString(); + row["creatorsID"] = item.CreatorId.ToString(); + row["inventoryName"] = item.Name; + row["inventoryDescription"] = item.Description; + + row["inventoryNextPermissions"] = item.NextPermissions; + row["inventoryCurrentPermissions"] = item.CurrentPermissions; + row["inventoryBasePermissions"] = item.BasePermissions; + row["inventoryEveryOnePermissions"] = item.EveryOnePermissions; + row["inventoryGroupPermissions"] = item.GroupPermissions; + + // new fields + row["salePrice"] = item.SalePrice; + row["saleType"] = item.SaleType; + row["creationDate"] = item.CreationDate; + row["groupID"] = item.GroupID.ToString(); + row["groupOwned"] = item.GroupOwned; + row["flags"] = item.Flags; + } + + /// + /// Add inventory folder + /// + /// Folder base + /// true=create folder. false=update existing folder + /// nasty + private void addFolder(InventoryFolderBase folder, bool add) + { + lock (ds) + { + DataTable inventoryFolderTable = ds.Tables["inventoryfolders"]; + + DataRow inventoryRow = inventoryFolderTable.Rows.Find(folder.ID.ToString()); + if (inventoryRow == null) + { + if (! add) + m_log.ErrorFormat("Interface Misuse: Attempting to Update non-existant inventory folder: {0}", folder.ID); + + inventoryRow = inventoryFolderTable.NewRow(); + fillFolderRow(inventoryRow, folder); + inventoryFolderTable.Rows.Add(inventoryRow); + } + else + { + if (add) + m_log.ErrorFormat("Interface Misuse: Attempting to Add inventory folder that already exists: {0}", folder.ID); + + fillFolderRow(inventoryRow, folder); + } + + invFoldersDa.Update(ds, "inventoryfolders"); + } + } + + /// + /// Move an inventory folder + /// + /// folder base + private void moveFolder(InventoryFolderBase folder) + { + lock (ds) + { + DataTable inventoryFolderTable = ds.Tables["inventoryfolders"]; + + DataRow inventoryRow = inventoryFolderTable.Rows.Find(folder.ID.ToString()); + if (inventoryRow == null) + { + inventoryRow = inventoryFolderTable.NewRow(); + fillFolderRow(inventoryRow, folder); + inventoryFolderTable.Rows.Add(inventoryRow); + } + else + { + moveFolderRow(inventoryRow, folder); + } + + invFoldersDa.Update(ds, "inventoryfolders"); + } + } + + /// + /// add an item in inventory + /// + /// the item + /// true=add item ; false=update existing item + private void addItem(InventoryItemBase item, bool add) + { + lock (ds) + { + DataTable inventoryItemTable = ds.Tables["inventoryitems"]; + + DataRow inventoryRow = inventoryItemTable.Rows.Find(item.ID.ToString()); + if (inventoryRow == null) + { + if (!add) + m_log.ErrorFormat("[INVENTORY DB]: Interface Misuse: Attempting to Update non-existant inventory item: {0}", item.ID); + + inventoryRow = inventoryItemTable.NewRow(); + fillItemRow(inventoryRow, item); + inventoryItemTable.Rows.Add(inventoryRow); + } + else + { + if (add) + m_log.ErrorFormat("[INVENTORY DB]: Interface Misuse: Attempting to Add inventory item that already exists: {0}", item.ID); + + fillItemRow(inventoryRow, item); + } + + invItemsDa.Update(ds, "inventoryitems"); + + DataTable inventoryFolderTable = ds.Tables["inventoryfolders"]; + + inventoryRow = inventoryFolderTable.Rows.Find(item.Folder.ToString()); + if (inventoryRow != null) //MySQL doesn't throw an exception here, so sqlite shouldn't either. + inventoryRow["version"] = (int)inventoryRow["version"] + 1; + + invFoldersDa.Update(ds, "inventoryfolders"); + } + } + + /// + /// TODO : DataSet commit + /// + public void Shutdown() + { + // TODO: DataSet commit + } + + /// + /// The name of this DB provider + /// + /// Name of DB provider + public string Name + { + get { return "SQLite Inventory Data Interface"; } + } + + /// + /// Returns the version of this DB provider + /// + /// A string containing the DB provider version + public string Version + { + get + { + Module module = GetType().Module; + // string dllName = module.Assembly.ManifestModule.Name; + Version dllVersion = module.Assembly.GetName().Version; + + + return + string.Format("{0}.{1}.{2}.{3}", dllVersion.Major, dllVersion.Minor, dllVersion.Build, + dllVersion.Revision); + } + } + + /// + /// Returns a list of inventory items contained within the specified folder + /// + /// The UUID of the target folder + /// A List of InventoryItemBase items + public List getInventoryInFolder(UUID folderID) + { + lock (ds) + { + List retval = new List(); + DataTable inventoryItemTable = ds.Tables["inventoryitems"]; + string selectExp = "parentFolderID = '" + folderID + "'"; + DataRow[] rows = inventoryItemTable.Select(selectExp); + foreach (DataRow row in rows) + { + retval.Add(buildItem(row)); + } + + return retval; + } + } + + /// + /// Returns a list of the root folders within a users inventory + /// + /// The user whos inventory is to be searched + /// A list of folder objects + public List getUserRootFolders(UUID user) + { + return new List(); + } + + // see InventoryItemBase.getUserRootFolder + public InventoryFolderBase getUserRootFolder(UUID user) + { + lock (ds) + { + List folders = new List(); + DataTable inventoryFolderTable = ds.Tables["inventoryfolders"]; + string selectExp = "agentID = '" + user + "' AND parentID = '" + UUID.Zero + "'"; + DataRow[] rows = inventoryFolderTable.Select(selectExp); + foreach (DataRow row in rows) + { + folders.Add(buildFolder(row)); + } + + // There should only ever be one root folder for a user. However, if there's more + // than one we'll simply use the first one rather than failing. It would be even + // nicer to print some message to this effect, but this feels like it's too low a + // to put such a message out, and it's too minor right now to spare the time to + // suitably refactor. + if (folders.Count > 0) + { + return folders[0]; + } + + return null; + } + } + + /// + /// Append a list of all the child folders of a parent folder + /// + /// list where folders will be appended + /// ID of parent + protected void getInventoryFolders(ref List folders, UUID parentID) + { + lock (ds) + { + DataTable inventoryFolderTable = ds.Tables["inventoryfolders"]; + string selectExp = "parentID = '" + parentID + "'"; + DataRow[] rows = inventoryFolderTable.Select(selectExp); + foreach (DataRow row in rows) + { + folders.Add(buildFolder(row)); + } + + } + } + + /// + /// Returns a list of inventory folders contained in the folder 'parentID' + /// + /// The folder to get subfolders for + /// A list of inventory folders + public List getInventoryFolders(UUID parentID) + { + List folders = new List(); + getInventoryFolders(ref folders, parentID); + return folders; + } + + /// + /// See IInventoryDataPlugin + /// + /// + /// + public List getFolderHierarchy(UUID parentID) + { + /* Note: There are subtle changes between this implementation of getFolderHierarchy and the previous one + * - We will only need to hit the database twice instead of n times. + * - We assume the database is well-formed - no stranded/dangling folders, all folders in heirarchy owned + * by the same person, each user only has 1 inventory heirarchy + * - The returned list is not ordered, instead of breadth-first ordered + There are basically 2 usage cases for getFolderHeirarchy: + 1) Getting the user's entire inventory heirarchy when they log in + 2) Finding a subfolder heirarchy to delete when emptying the trash. + This implementation will pull all inventory folders from the database, and then prune away any folder that + is not part of the requested sub-heirarchy. The theory is that it is cheaper to make 1 request from the + database than to make n requests. This pays off only if requested heirarchy is large. + By making this choice, we are making the worst case better at the cost of making the best case worse + - Francis + */ + + List folders = new List(); + DataRow[] folderRows = null, parentRow; + InventoryFolderBase parentFolder = null; + lock (ds) + { + /* Fetch the parent folder from the database to determine the agent ID. + * Then fetch all inventory folders for that agent from the agent ID. + */ + DataTable inventoryFolderTable = ds.Tables["inventoryfolders"]; + string selectExp = "UUID = '" + parentID + "'"; + parentRow = inventoryFolderTable.Select(selectExp); // Assume at most 1 result + if (parentRow.GetLength(0) >= 1) // No result means parent folder does not exist + { + parentFolder = buildFolder(parentRow[0]); + UUID agentID = parentFolder.Owner; + selectExp = "agentID = '" + agentID + "'"; + folderRows = inventoryFolderTable.Select(selectExp); + } + + if (folderRows != null && folderRows.GetLength(0) >= 1) // No result means parent folder does not exist + { // or has no children + /* if we're querying the root folder, just return an unordered list of all folders in the user's + * inventory + */ + if (parentFolder.ParentID == UUID.Zero) + { + foreach (DataRow row in folderRows) + { + InventoryFolderBase curFolder = buildFolder(row); + if (curFolder.ID != parentID) // Return all folders except the parent folder of heirarchy + folders.Add(buildFolder(row)); + } + } // If requesting root folder + /* else we are querying a non-root folder. We currently have a list of all of the user's folders, + * we must construct a list of all folders in the heirarchy below parentID. + * Our first step will be to construct a hash table of all folders, indexed by parent ID. + * Once we have constructed the hash table, we will do a breadth-first traversal on the tree using the + * hash table to find child folders. + */ + else + { // Querying a non-root folder + + // Build a hash table of all user's inventory folders, indexed by each folder's parent ID + Dictionary> hashtable = + new Dictionary>(folderRows.GetLength(0)); + + foreach (DataRow row in folderRows) + { + InventoryFolderBase curFolder = buildFolder(row); + if (curFolder.ParentID != UUID.Zero) // Discard root of tree - not needed + { + if (hashtable.ContainsKey(curFolder.ParentID)) + { + // Current folder already has a sibling - append to sibling list + hashtable[curFolder.ParentID].Add(curFolder); + } + else + { + List siblingList = new List(); + siblingList.Add(curFolder); + // Current folder has no known (yet) siblings + hashtable.Add(curFolder.ParentID, siblingList); + } + } + } // For all inventory folders + + // Note: Could release the ds lock here - we don't access folderRows or the database anymore. + // This is somewhat of a moot point as the callers of this function usually lock db anyways. + + if (hashtable.ContainsKey(parentID)) // if requested folder does have children + folders.AddRange(hashtable[parentID]); + + // BreadthFirstSearch build inventory tree **Note: folders.Count is *not* static + for (int i = 0; i < folders.Count; i++) + if (hashtable.ContainsKey(folders[i].ID)) + folders.AddRange(hashtable[folders[i].ID]); + + } // if requesting a subfolder heirarchy + } // if folder parentID exists and has children + } // lock ds + return folders; + } + + /// + /// Returns an inventory item by its UUID + /// + /// The UUID of the item to be returned + /// A class containing item information + public InventoryItemBase getInventoryItem(UUID item) + { + lock (ds) + { + DataRow row = ds.Tables["inventoryitems"].Rows.Find(item.ToString()); + if (row != null) + { + return buildItem(row); + } + else + { + return null; + } + } + } + + /// + /// Returns a specified inventory folder by its UUID + /// + /// The UUID of the folder to be returned + /// A class containing folder information + public InventoryFolderBase getInventoryFolder(UUID folder) + { + // TODO: Deep voodoo here. If you enable this code then + // multi region breaks. No idea why, but I figured it was + // better to leave multi region at this point. It does mean + // that you don't get to see system textures why creating + // clothes and the like. :( + lock (ds) + { + DataRow row = ds.Tables["inventoryfolders"].Rows.Find(folder.ToString()); + if (row != null) + { + return buildFolder(row); + } + else + { + return null; + } + } + } + + /// + /// Creates a new inventory item based on item + /// + /// The item to be created + public void addInventoryItem(InventoryItemBase item) + { + addItem(item, true); + } + + /// + /// Updates an inventory item with item (updates based on ID) + /// + /// The updated item + public void updateInventoryItem(InventoryItemBase item) + { + addItem(item, false); + } + + /// + /// Delete an inventory item + /// + /// The item UUID + public void deleteInventoryItem(UUID itemID) + { + lock (ds) + { + DataTable inventoryItemTable = ds.Tables["inventoryitems"]; + + DataRow inventoryRow = inventoryItemTable.Rows.Find(itemID.ToString()); + if (inventoryRow != null) + { + inventoryRow.Delete(); + } + + invItemsDa.Update(ds, "inventoryitems"); + } + } + + public InventoryItemBase queryInventoryItem(UUID itemID) + { + return getInventoryItem(itemID); + } + + public InventoryFolderBase queryInventoryFolder(UUID folderID) + { + return getInventoryFolder(folderID); + } + + /// + /// Delete all items in the specified folder + /// + /// id of the folder, whose item content should be deleted + /// this is horribly inefficient, but I don't want to ruin the overall structure of this implementation + private void deleteItemsInFolder(UUID folderId) + { + List items = getInventoryInFolder(folderId); + + foreach (InventoryItemBase i in items) + deleteInventoryItem(i.ID); + } + + /// + /// Adds a new folder specified by folder + /// + /// The inventory folder + public void addInventoryFolder(InventoryFolderBase folder) + { + addFolder(folder, true); + } + + /// + /// Updates a folder based on its ID with folder + /// + /// The inventory folder + public void updateInventoryFolder(InventoryFolderBase folder) + { + addFolder(folder, false); + } + + /// + /// Moves a folder based on its ID with folder + /// + /// The inventory folder + public void moveInventoryFolder(InventoryFolderBase folder) + { + moveFolder(folder); + } + + /// + /// Delete a folder + /// + /// + /// This will clean-up any child folders and child items as well + /// + /// the folder UUID + public void deleteInventoryFolder(UUID folderID) + { + lock (ds) + { + List subFolders = getFolderHierarchy(folderID); + + DataTable inventoryFolderTable = ds.Tables["inventoryfolders"]; + DataRow inventoryRow; + + //Delete all sub-folders + foreach (InventoryFolderBase f in subFolders) + { + inventoryRow = inventoryFolderTable.Rows.Find(f.ID.ToString()); + if (inventoryRow != null) + { + deleteItemsInFolder(f.ID); + inventoryRow.Delete(); + } + } + + //Delete the actual row + inventoryRow = inventoryFolderTable.Rows.Find(folderID.ToString()); + if (inventoryRow != null) + { + deleteItemsInFolder(folderID); + inventoryRow.Delete(); + } + + invFoldersDa.Update(ds, "inventoryfolders"); + } + } + + /*********************************************************************** + * + * Data Table definitions + * + **********************************************************************/ + + /// + /// Create the "inventoryitems" table + /// + private static DataTable createInventoryItemsTable() + { + DataTable inv = new DataTable("inventoryitems"); + + createCol(inv, "UUID", typeof (String)); //inventoryID + createCol(inv, "assetID", typeof (String)); + createCol(inv, "assetType", typeof (Int32)); + createCol(inv, "invType", typeof (Int32)); + createCol(inv, "parentFolderID", typeof (String)); + createCol(inv, "avatarID", typeof (String)); + createCol(inv, "creatorsID", typeof (String)); + + createCol(inv, "inventoryName", typeof (String)); + createCol(inv, "inventoryDescription", typeof (String)); + // permissions + createCol(inv, "inventoryNextPermissions", typeof (Int32)); + createCol(inv, "inventoryCurrentPermissions", typeof (Int32)); + createCol(inv, "inventoryBasePermissions", typeof (Int32)); + createCol(inv, "inventoryEveryOnePermissions", typeof (Int32)); + createCol(inv, "inventoryGroupPermissions", typeof (Int32)); + + // sale info + createCol(inv, "salePrice", typeof(Int32)); + createCol(inv, "saleType", typeof(Byte)); + + // creation date + createCol(inv, "creationDate", typeof(Int32)); + + // group info + createCol(inv, "groupID", typeof(String)); + createCol(inv, "groupOwned", typeof(Boolean)); + + // Flags + createCol(inv, "flags", typeof(UInt32)); + + inv.PrimaryKey = new DataColumn[] { inv.Columns["UUID"] }; + return inv; + } + + /// + /// Creates the "inventoryfolders" table + /// + /// + private static DataTable createInventoryFoldersTable() + { + DataTable fol = new DataTable("inventoryfolders"); + + createCol(fol, "UUID", typeof (String)); //folderID + createCol(fol, "name", typeof (String)); + createCol(fol, "agentID", typeof (String)); + createCol(fol, "parentID", typeof (String)); + createCol(fol, "type", typeof (Int32)); + createCol(fol, "version", typeof (Int32)); + + fol.PrimaryKey = new DataColumn[] {fol.Columns["UUID"]}; + return fol; + } + + /// + /// + /// + /// + /// + private void setupItemsCommands(SqliteDataAdapter da, SqliteConnection conn) + { + lock (ds) + { + da.InsertCommand = createInsertCommand("inventoryitems", ds.Tables["inventoryitems"]); + da.InsertCommand.Connection = conn; + + da.UpdateCommand = createUpdateCommand("inventoryitems", "UUID=:UUID", ds.Tables["inventoryitems"]); + da.UpdateCommand.Connection = conn; + + SqliteCommand delete = new SqliteCommand("delete from inventoryitems where UUID = :UUID"); + delete.Parameters.Add(createSqliteParameter("UUID", typeof(String))); + delete.Connection = conn; + da.DeleteCommand = delete; + } + } + + /// + /// + /// + /// + /// + private void setupFoldersCommands(SqliteDataAdapter da, SqliteConnection conn) + { + lock (ds) + { + da.InsertCommand = createInsertCommand("inventoryfolders", ds.Tables["inventoryfolders"]); + da.InsertCommand.Connection = conn; + + da.UpdateCommand = createUpdateCommand("inventoryfolders", "UUID=:UUID", ds.Tables["inventoryfolders"]); + da.UpdateCommand.Connection = conn; + + SqliteCommand delete = new SqliteCommand("delete from inventoryfolders where UUID = :UUID"); + delete.Parameters.Add(createSqliteParameter("UUID", typeof(String))); + delete.Connection = conn; + da.DeleteCommand = delete; + } + } + + /// + /// + /// + /// + /// + private static InventoryFolderBase buildFolder(DataRow row) + { + InventoryFolderBase folder = new InventoryFolderBase(); + folder.ID = new UUID((string) row["UUID"]); + folder.Name = (string) row["name"]; + folder.Owner = new UUID((string) row["agentID"]); + folder.ParentID = new UUID((string) row["parentID"]); + folder.Type = Convert.ToInt16(row["type"]); + folder.Version = Convert.ToUInt16(row["version"]); + return folder; + } + + /// + /// + /// + /// + /// + private static void fillFolderRow(DataRow row, InventoryFolderBase folder) + { + row["UUID"] = folder.ID.ToString(); + row["name"] = folder.Name; + row["agentID"] = folder.Owner.ToString(); + row["parentID"] = folder.ParentID.ToString(); + row["type"] = folder.Type; + row["version"] = folder.Version; + } + + /// + /// + /// + /// + /// + private static void moveFolderRow(DataRow row, InventoryFolderBase folder) + { + row["UUID"] = folder.ID.ToString(); + row["parentID"] = folder.ParentID.ToString(); + } + + public List fetchActiveGestures (UUID avatarID) + { + lock (ds) + { + List items = new List(); + + DataTable inventoryItemTable = ds.Tables["inventoryitems"]; + string selectExp + = "avatarID = '" + avatarID + "' AND assetType = " + (int)AssetType.Gesture + " AND flags = 1"; + //m_log.DebugFormat("[SQL]: sql = " + selectExp); + DataRow[] rows = inventoryItemTable.Select(selectExp); + foreach (DataRow row in rows) + { + items.Add(buildItem(row)); + } + return items; + } + } + } +} diff --git a/OpenSim/Data/SQLiteLegacy/SQLiteRegionData.cs b/OpenSim/Data/SQLiteLegacy/SQLiteRegionData.cs new file mode 100644 index 0000000000..eb78037bb1 --- /dev/null +++ b/OpenSim/Data/SQLiteLegacy/SQLiteRegionData.cs @@ -0,0 +1,2264 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; +using System.Data; +using System.Drawing; +using System.IO; +using System.Reflection; +using log4net; +using Mono.Data.SqliteClient; +using OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Region.Framework.Interfaces; +using OpenSim.Region.Framework.Scenes; + +namespace OpenSim.Data.SQLiteLegacy +{ + /// + /// A RegionData Interface to the SQLite database + /// + public class SQLiteRegionData : IRegionDataStore + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private const string primSelect = "select * from prims"; + private const string shapeSelect = "select * from primshapes"; + private const string itemsSelect = "select * from primitems"; + private const string terrainSelect = "select * from terrain limit 1"; + private const string landSelect = "select * from land"; + private const string landAccessListSelect = "select distinct * from landaccesslist"; + private const string regionbanListSelect = "select * from regionban"; + private const string regionSettingsSelect = "select * from regionsettings"; + + private DataSet ds; + private SqliteDataAdapter primDa; + private SqliteDataAdapter shapeDa; + private SqliteDataAdapter itemsDa; + private SqliteDataAdapter terrainDa; + private SqliteDataAdapter landDa; + private SqliteDataAdapter landAccessListDa; + private SqliteDataAdapter regionSettingsDa; + + private SqliteConnection m_conn; + + private String m_connectionString; + + // Temporary attribute while this is experimental + + /*********************************************************************** + * + * Public Interface Functions + * + **********************************************************************/ + + /// + /// See IRegionDataStore + /// + /// Initialises RegionData Interface + /// Loads and initialises a new SQLite connection and maintains it. + /// + /// + /// the connection string + public void Initialise(string connectionString) + { + m_connectionString = connectionString; + + ds = new DataSet(); + + m_log.Info("[REGION DB]: Sqlite - connecting: " + connectionString); + m_conn = new SqliteConnection(m_connectionString); + m_conn.Open(); + + + + SqliteCommand primSelectCmd = new SqliteCommand(primSelect, m_conn); + primDa = new SqliteDataAdapter(primSelectCmd); + // SqliteCommandBuilder primCb = new SqliteCommandBuilder(primDa); + + SqliteCommand shapeSelectCmd = new SqliteCommand(shapeSelect, m_conn); + shapeDa = new SqliteDataAdapter(shapeSelectCmd); + // SqliteCommandBuilder shapeCb = new SqliteCommandBuilder(shapeDa); + + SqliteCommand itemsSelectCmd = new SqliteCommand(itemsSelect, m_conn); + itemsDa = new SqliteDataAdapter(itemsSelectCmd); + + SqliteCommand terrainSelectCmd = new SqliteCommand(terrainSelect, m_conn); + terrainDa = new SqliteDataAdapter(terrainSelectCmd); + + SqliteCommand landSelectCmd = new SqliteCommand(landSelect, m_conn); + landDa = new SqliteDataAdapter(landSelectCmd); + + SqliteCommand landAccessListSelectCmd = new SqliteCommand(landAccessListSelect, m_conn); + landAccessListDa = new SqliteDataAdapter(landAccessListSelectCmd); + + SqliteCommand regionSettingsSelectCmd = new SqliteCommand(regionSettingsSelect, m_conn); + regionSettingsDa = new SqliteDataAdapter(regionSettingsSelectCmd); + // This actually does the roll forward assembly stuff + Assembly assem = GetType().Assembly; + Migration m = new Migration(m_conn, assem, "RegionStore"); + m.Update(); + + lock (ds) + { + ds.Tables.Add(createPrimTable()); + setupPrimCommands(primDa, m_conn); + primDa.Fill(ds.Tables["prims"]); + + ds.Tables.Add(createShapeTable()); + setupShapeCommands(shapeDa, m_conn); + + ds.Tables.Add(createItemsTable()); + setupItemsCommands(itemsDa, m_conn); + itemsDa.Fill(ds.Tables["primitems"]); + + ds.Tables.Add(createTerrainTable()); + setupTerrainCommands(terrainDa, m_conn); + + ds.Tables.Add(createLandTable()); + setupLandCommands(landDa, m_conn); + + ds.Tables.Add(createLandAccessListTable()); + setupLandAccessCommands(landAccessListDa, m_conn); + + ds.Tables.Add(createRegionSettingsTable()); + + setupRegionSettingsCommands(regionSettingsDa, m_conn); + + // WORKAROUND: This is a work around for sqlite on + // windows, which gets really unhappy with blob columns + // that have no sample data in them. At some point we + // need to actually find a proper way to handle this. + try + { + shapeDa.Fill(ds.Tables["primshapes"]); + } + catch (Exception) + { + m_log.Info("[REGION DB]: Caught fill error on primshapes table"); + } + + try + { + terrainDa.Fill(ds.Tables["terrain"]); + } + catch (Exception) + { + m_log.Info("[REGION DB]: Caught fill error on terrain table"); + } + + try + { + landDa.Fill(ds.Tables["land"]); + } + catch (Exception) + { + m_log.Info("[REGION DB]: Caught fill error on land table"); + } + + try + { + landAccessListDa.Fill(ds.Tables["landaccesslist"]); + } + catch (Exception) + { + m_log.Info("[REGION DB]: Caught fill error on landaccesslist table"); + } + + try + { + regionSettingsDa.Fill(ds.Tables["regionsettings"]); + } + catch (Exception) + { + m_log.Info("[REGION DB]: Caught fill error on regionsettings table"); + } + return; + } + } + + public void Dispose() + { + if (m_conn != null) + { + m_conn.Close(); + m_conn = null; + } + if (ds != null) + { + ds.Dispose(); + ds = null; + } + if (primDa != null) + { + primDa.Dispose(); + primDa = null; + } + if (shapeDa != null) + { + shapeDa.Dispose(); + shapeDa = null; + } + if (itemsDa != null) + { + itemsDa.Dispose(); + itemsDa = null; + } + if (terrainDa != null) + { + terrainDa.Dispose(); + terrainDa = null; + } + if (landDa != null) + { + landDa.Dispose(); + landDa = null; + } + if (landAccessListDa != null) + { + landAccessListDa.Dispose(); + landAccessListDa = null; + } + if (regionSettingsDa != null) + { + regionSettingsDa.Dispose(); + regionSettingsDa = null; + } + } + + public void StoreRegionSettings(RegionSettings rs) + { + lock (ds) + { + DataTable regionsettings = ds.Tables["regionsettings"]; + + DataRow settingsRow = regionsettings.Rows.Find(rs.RegionUUID.ToString()); + if (settingsRow == null) + { + settingsRow = regionsettings.NewRow(); + fillRegionSettingsRow(settingsRow, rs); + regionsettings.Rows.Add(settingsRow); + } + else + { + fillRegionSettingsRow(settingsRow, rs); + } + + Commit(); + } + } + public RegionLightShareData LoadRegionWindlightSettings(UUID regionUUID) + { + //This connector doesn't support the windlight module yet + //Return default LL windlight settings + return new RegionLightShareData(); + } + public void StoreRegionWindlightSettings(RegionLightShareData wl) + { + //This connector doesn't support the windlight module yet + } + public RegionSettings LoadRegionSettings(UUID regionUUID) + { + lock (ds) + { + DataTable regionsettings = ds.Tables["regionsettings"]; + + string searchExp = "regionUUID = '" + regionUUID.ToString() + "'"; + DataRow[] rawsettings = regionsettings.Select(searchExp); + if (rawsettings.Length == 0) + { + RegionSettings rs = new RegionSettings(); + rs.RegionUUID = regionUUID; + rs.OnSave += StoreRegionSettings; + + StoreRegionSettings(rs); + + return rs; + } + DataRow row = rawsettings[0]; + + RegionSettings newSettings = buildRegionSettings(row); + newSettings.OnSave += StoreRegionSettings; + + return newSettings; + } + } + + /// + /// Adds an object into region storage + /// + /// the object + /// the region UUID + public void StoreObject(SceneObjectGroup obj, UUID regionUUID) + { + uint flags = obj.RootPart.GetEffectiveObjectFlags(); + + // Eligibility check + // + if ((flags & (uint)PrimFlags.Temporary) != 0) + return; + if ((flags & (uint)PrimFlags.TemporaryOnRez) != 0) + return; + + lock (ds) + { + foreach (SceneObjectPart prim in obj.Children.Values) + { +// m_log.Info("[REGION DB]: Adding obj: " + obj.UUID + " to region: " + regionUUID); + addPrim(prim, obj.UUID, regionUUID); + } + } + + Commit(); + // m_log.Info("[Dump of prims]: " + ds.GetXml()); + } + + /// + /// Removes an object from region storage + /// + /// the object + /// the region UUID + public void RemoveObject(UUID obj, UUID regionUUID) + { + // m_log.InfoFormat("[REGION DB]: Removing obj: {0} from region: {1}", obj.Guid, regionUUID); + + DataTable prims = ds.Tables["prims"]; + DataTable shapes = ds.Tables["primshapes"]; + + string selectExp = "SceneGroupID = '" + obj + "' and RegionUUID = '" + regionUUID + "'"; + lock (ds) + { + DataRow[] primRows = prims.Select(selectExp); + foreach (DataRow row in primRows) + { + // Remove shape rows + UUID uuid = new UUID((string) row["UUID"]); + DataRow shapeRow = shapes.Rows.Find(uuid.ToString()); + if (shapeRow != null) + { + shapeRow.Delete(); + } + + RemoveItems(uuid); + + // Remove prim row + row.Delete(); + } + } + + Commit(); + } + + /// + /// Remove all persisted items of the given prim. + /// The caller must acquire the necessrary synchronization locks and commit or rollback changes. + /// + /// The item UUID + private void RemoveItems(UUID uuid) + { + DataTable items = ds.Tables["primitems"]; + + String sql = String.Format("primID = '{0}'", uuid); + DataRow[] itemRows = items.Select(sql); + + foreach (DataRow itemRow in itemRows) + { + itemRow.Delete(); + } + } + + /// + /// Load persisted objects from region storage. + /// + /// The region UUID + /// List of loaded groups + public List LoadObjects(UUID regionUUID) + { + Dictionary createdObjects = new Dictionary(); + + List retvals = new List(); + + DataTable prims = ds.Tables["prims"]; + DataTable shapes = ds.Tables["primshapes"]; + + string byRegion = "RegionUUID = '" + regionUUID + "'"; + + lock (ds) + { + DataRow[] primsForRegion = prims.Select(byRegion); + m_log.Info("[REGION DB]: Loaded " + primsForRegion.Length + " prims for region: " + regionUUID); + + // First, create all groups + foreach (DataRow primRow in primsForRegion) + { + try + { + SceneObjectPart prim = null; + + string uuid = (string) primRow["UUID"]; + string objID = (string) primRow["SceneGroupID"]; + + if (uuid == objID) //is new SceneObjectGroup ? + { + prim = buildPrim(primRow); + DataRow shapeRow = shapes.Rows.Find(prim.UUID.ToString()); + if (shapeRow != null) + { + prim.Shape = buildShape(shapeRow); + } + else + { + m_log.Info( + "[REGION DB]: No shape found for prim in storage, so setting default box shape"); + prim.Shape = PrimitiveBaseShape.Default; + } + + SceneObjectGroup group = new SceneObjectGroup(prim); + createdObjects.Add(group.UUID, group); + retvals.Add(group); + LoadItems(prim); + } + } + catch (Exception e) + { + m_log.Error("[REGION DB]: Failed create prim object in new group, exception and data follows"); + m_log.Info("[REGION DB]: " + e.ToString()); + foreach (DataColumn col in prims.Columns) + { + m_log.Info("[REGION DB]: Col: " + col.ColumnName + " => " + primRow[col]); + } + } + } + + // Now fill the groups with part data + foreach (DataRow primRow in primsForRegion) + { + try + { + SceneObjectPart prim = null; + + string uuid = (string) primRow["UUID"]; + string objID = (string) primRow["SceneGroupID"]; + if (uuid != objID) //is new SceneObjectGroup ? + { + prim = buildPrim(primRow); + DataRow shapeRow = shapes.Rows.Find(prim.UUID.ToString()); + if (shapeRow != null) + { + prim.Shape = buildShape(shapeRow); + } + else + { + m_log.Warn( + "[REGION DB]: No shape found for prim in storage, so setting default box shape"); + prim.Shape = PrimitiveBaseShape.Default; + } + + createdObjects[new UUID(objID)].AddPart(prim); + LoadItems(prim); + } + } + catch (Exception e) + { + m_log.Error("[REGION DB]: Failed create prim object in group, exception and data follows"); + m_log.Info("[REGION DB]: " + e.ToString()); + foreach (DataColumn col in prims.Columns) + { + m_log.Info("[REGION DB]: Col: " + col.ColumnName + " => " + primRow[col]); + } + } + } + } + return retvals; + } + + /// + /// Load in a prim's persisted inventory. + /// + /// the prim + private void LoadItems(SceneObjectPart prim) + { + //m_log.DebugFormat("[DATASTORE]: Loading inventory for {0}, {1}", prim.Name, prim.UUID); + + DataTable dbItems = ds.Tables["primitems"]; + String sql = String.Format("primID = '{0}'", prim.UUID.ToString()); + DataRow[] dbItemRows = dbItems.Select(sql); + IList inventory = new List(); + + foreach (DataRow row in dbItemRows) + { + TaskInventoryItem item = buildItem(row); + inventory.Add(item); + + //m_log.DebugFormat("[DATASTORE]: Restored item {0}, {1}", item.Name, item.ItemID); + } + + prim.Inventory.RestoreInventoryItems(inventory); + } + + /// + /// Store a terrain revision in region storage + /// + /// terrain heightfield + /// region UUID + public void StoreTerrain(double[,] ter, UUID regionID) + { + lock (ds) + { + int revision = Util.UnixTimeSinceEpoch(); + + // This is added to get rid of the infinitely growing + // terrain databases which negatively impact on SQLite + // over time. Before reenabling this feature there + // needs to be a limitter put on the number of + // revisions in the database, as this old + // implementation is a DOS attack waiting to happen. + + using ( + SqliteCommand cmd = + new SqliteCommand("delete from terrain where RegionUUID=:RegionUUID and Revision <= :Revision", + m_conn)) + { + cmd.Parameters.Add(new SqliteParameter(":RegionUUID", regionID.ToString())); + cmd.Parameters.Add(new SqliteParameter(":Revision", revision)); + cmd.ExecuteNonQuery(); + } + + // the following is an work around for .NET. The perf + // issues associated with it aren't as bad as you think. + m_log.Info("[REGION DB]: Storing terrain revision r" + revision.ToString()); + String sql = "insert into terrain(RegionUUID, Revision, Heightfield)" + + " values(:RegionUUID, :Revision, :Heightfield)"; + + using (SqliteCommand cmd = new SqliteCommand(sql, m_conn)) + { + cmd.Parameters.Add(new SqliteParameter(":RegionUUID", regionID.ToString())); + cmd.Parameters.Add(new SqliteParameter(":Revision", revision)); + cmd.Parameters.Add(new SqliteParameter(":Heightfield", serializeTerrain(ter))); + cmd.ExecuteNonQuery(); + } + } + } + + /// + /// Load the latest terrain revision from region storage + /// + /// the region UUID + /// Heightfield data + public double[,] LoadTerrain(UUID regionID) + { + lock (ds) + { + double[,] terret = new double[(int)Constants.RegionSize, (int)Constants.RegionSize]; + terret.Initialize(); + + String sql = "select RegionUUID, Revision, Heightfield from terrain" + + " where RegionUUID=:RegionUUID order by Revision desc"; + + using (SqliteCommand cmd = new SqliteCommand(sql, m_conn)) + { + cmd.Parameters.Add(new SqliteParameter(":RegionUUID", regionID.ToString())); + + using (IDataReader row = cmd.ExecuteReader()) + { + int rev = 0; + if (row.Read()) + { + // TODO: put this into a function + using (MemoryStream str = new MemoryStream((byte[])row["Heightfield"])) + { + using (BinaryReader br = new BinaryReader(str)) + { + for (int x = 0; x < (int)Constants.RegionSize; x++) + { + for (int y = 0; y < (int)Constants.RegionSize; y++) + { + terret[x, y] = br.ReadDouble(); + } + } + } + } + rev = (int) row["Revision"]; + } + else + { + m_log.Info("[REGION DB]: No terrain found for region"); + return null; + } + + m_log.Info("[REGION DB]: Loaded terrain revision r" + rev.ToString()); + } + } + return terret; + } + } + + /// + /// + /// + /// + public void RemoveLandObject(UUID globalID) + { + lock (ds) + { + // Can't use blanket SQL statements when using SqlAdapters unless you re-read the data into the adapter + // after you're done. + // replaced below code with the SqliteAdapter version. + //using (SqliteCommand cmd = new SqliteCommand("delete from land where UUID=:UUID", m_conn)) + //{ + // cmd.Parameters.Add(new SqliteParameter(":UUID", globalID.ToString())); + // cmd.ExecuteNonQuery(); + //} + + //using (SqliteCommand cmd = new SqliteCommand("delete from landaccesslist where LandUUID=:UUID", m_conn)) + //{ + // cmd.Parameters.Add(new SqliteParameter(":UUID", globalID.ToString())); + // cmd.ExecuteNonQuery(); + //} + + DataTable land = ds.Tables["land"]; + DataTable landaccesslist = ds.Tables["landaccesslist"]; + DataRow landRow = land.Rows.Find(globalID.ToString()); + if (landRow != null) + { + land.Rows.Remove(landRow); + } + List rowsToDelete = new List(); + foreach (DataRow rowToCheck in landaccesslist.Rows) + { + if (rowToCheck["LandUUID"].ToString() == globalID.ToString()) + rowsToDelete.Add(rowToCheck); + } + for (int iter = 0; iter < rowsToDelete.Count; iter++) + { + landaccesslist.Rows.Remove(rowsToDelete[iter]); + } + + + } + Commit(); + } + + /// + /// + /// + /// + public void StoreLandObject(ILandObject parcel) + { + lock (ds) + { + DataTable land = ds.Tables["land"]; + DataTable landaccesslist = ds.Tables["landaccesslist"]; + + DataRow landRow = land.Rows.Find(parcel.LandData.GlobalID.ToString()); + if (landRow == null) + { + landRow = land.NewRow(); + fillLandRow(landRow, parcel.LandData, parcel.RegionUUID); + land.Rows.Add(landRow); + } + else + { + fillLandRow(landRow, parcel.LandData, parcel.RegionUUID); + } + + // I know this caused someone issues before, but OpenSim is unusable if we leave this stuff around + //using (SqliteCommand cmd = new SqliteCommand("delete from landaccesslist where LandUUID=:LandUUID", m_conn)) + //{ + // cmd.Parameters.Add(new SqliteParameter(":LandUUID", parcel.LandData.GlobalID.ToString())); + // cmd.ExecuteNonQuery(); + +// } + + // This is the slower.. but more appropriate thing to do + + // We can't modify the table with direct queries before calling Commit() and re-filling them. + List rowsToDelete = new List(); + foreach (DataRow rowToCheck in landaccesslist.Rows) + { + if (rowToCheck["LandUUID"].ToString() == parcel.LandData.GlobalID.ToString()) + rowsToDelete.Add(rowToCheck); + } + for (int iter = 0; iter < rowsToDelete.Count; iter++) + { + landaccesslist.Rows.Remove(rowsToDelete[iter]); + } + rowsToDelete.Clear(); + foreach (ParcelManager.ParcelAccessEntry entry in parcel.LandData.ParcelAccessList) + { + DataRow newAccessRow = landaccesslist.NewRow(); + fillLandAccessRow(newAccessRow, entry, parcel.LandData.GlobalID); + landaccesslist.Rows.Add(newAccessRow); + } + } + + Commit(); + } + + /// + /// + /// + /// + /// + public List LoadLandObjects(UUID regionUUID) + { + List landDataForRegion = new List(); + lock (ds) + { + DataTable land = ds.Tables["land"]; + DataTable landaccesslist = ds.Tables["landaccesslist"]; + string searchExp = "RegionUUID = '" + regionUUID + "'"; + DataRow[] rawDataForRegion = land.Select(searchExp); + foreach (DataRow rawDataLand in rawDataForRegion) + { + LandData newLand = buildLandData(rawDataLand); + string accessListSearchExp = "LandUUID = '" + newLand.GlobalID + "'"; + DataRow[] rawDataForLandAccessList = landaccesslist.Select(accessListSearchExp); + foreach (DataRow rawDataLandAccess in rawDataForLandAccessList) + { + newLand.ParcelAccessList.Add(buildLandAccessData(rawDataLandAccess)); + } + + landDataForRegion.Add(newLand); + } + } + return landDataForRegion; + } + + /// + /// + /// + public void Commit() + { + lock (ds) + { + primDa.Update(ds, "prims"); + shapeDa.Update(ds, "primshapes"); + + itemsDa.Update(ds, "primitems"); + + terrainDa.Update(ds, "terrain"); + landDa.Update(ds, "land"); + landAccessListDa.Update(ds, "landaccesslist"); + try + { + regionSettingsDa.Update(ds, "regionsettings"); + } + catch (SqliteExecutionException SqlEx) + { + if (SqlEx.Message.Contains("logic error")) + { + throw new Exception( + "There was a SQL error or connection string configuration error when saving the region settings. This could be a bug, it could also happen if ConnectionString is defined in the [DatabaseService] section of StandaloneCommon.ini in the config_include folder. This could also happen if the config_include folder doesn't exist or if the OpenSim.ini [Architecture] section isn't set. If this is your first time running OpenSimulator, please restart the simulator and bug a developer to fix this!", + SqlEx); + } + else + { + throw SqlEx; + } + } + ds.AcceptChanges(); + } + } + + /// + /// See + /// + public void Shutdown() + { + Commit(); + } + + /*********************************************************************** + * + * Database Definition Functions + * + * This should be db agnostic as we define them in ADO.NET terms + * + **********************************************************************/ + + /// + /// + /// + /// + /// + /// + private static void createCol(DataTable dt, string name, Type type) + { + DataColumn col = new DataColumn(name, type); + dt.Columns.Add(col); + } + + /// + /// Creates the "terrain" table + /// + /// terrain table DataTable + private static DataTable createTerrainTable() + { + DataTable terrain = new DataTable("terrain"); + + createCol(terrain, "RegionUUID", typeof (String)); + createCol(terrain, "Revision", typeof (Int32)); + createCol(terrain, "Heightfield", typeof (Byte[])); + + return terrain; + } + + /// + /// Creates the "prims" table + /// + /// prim table DataTable + private static DataTable createPrimTable() + { + DataTable prims = new DataTable("prims"); + + createCol(prims, "UUID", typeof (String)); + createCol(prims, "RegionUUID", typeof (String)); + createCol(prims, "CreationDate", typeof (Int32)); + createCol(prims, "Name", typeof (String)); + createCol(prims, "SceneGroupID", typeof (String)); + // various text fields + createCol(prims, "Text", typeof (String)); + createCol(prims, "ColorR", typeof (Int32)); + createCol(prims, "ColorG", typeof (Int32)); + createCol(prims, "ColorB", typeof (Int32)); + createCol(prims, "ColorA", typeof (Int32)); + createCol(prims, "Description", typeof (String)); + createCol(prims, "SitName", typeof (String)); + createCol(prims, "TouchName", typeof (String)); + // permissions + createCol(prims, "ObjectFlags", typeof (Int32)); + createCol(prims, "CreatorID", typeof (String)); + createCol(prims, "OwnerID", typeof (String)); + createCol(prims, "GroupID", typeof (String)); + createCol(prims, "LastOwnerID", typeof (String)); + createCol(prims, "OwnerMask", typeof (Int32)); + createCol(prims, "NextOwnerMask", typeof (Int32)); + createCol(prims, "GroupMask", typeof (Int32)); + createCol(prims, "EveryoneMask", typeof (Int32)); + createCol(prims, "BaseMask", typeof (Int32)); + // vectors + createCol(prims, "PositionX", typeof (Double)); + createCol(prims, "PositionY", typeof (Double)); + createCol(prims, "PositionZ", typeof (Double)); + createCol(prims, "GroupPositionX", typeof (Double)); + createCol(prims, "GroupPositionY", typeof (Double)); + createCol(prims, "GroupPositionZ", typeof (Double)); + createCol(prims, "VelocityX", typeof (Double)); + createCol(prims, "VelocityY", typeof (Double)); + createCol(prims, "VelocityZ", typeof (Double)); + createCol(prims, "AngularVelocityX", typeof (Double)); + createCol(prims, "AngularVelocityY", typeof (Double)); + createCol(prims, "AngularVelocityZ", typeof (Double)); + createCol(prims, "AccelerationX", typeof (Double)); + createCol(prims, "AccelerationY", typeof (Double)); + createCol(prims, "AccelerationZ", typeof (Double)); + // quaternions + createCol(prims, "RotationX", typeof (Double)); + createCol(prims, "RotationY", typeof (Double)); + createCol(prims, "RotationZ", typeof (Double)); + createCol(prims, "RotationW", typeof (Double)); + + // sit target + createCol(prims, "SitTargetOffsetX", typeof (Double)); + createCol(prims, "SitTargetOffsetY", typeof (Double)); + createCol(prims, "SitTargetOffsetZ", typeof (Double)); + + createCol(prims, "SitTargetOrientW", typeof (Double)); + createCol(prims, "SitTargetOrientX", typeof (Double)); + createCol(prims, "SitTargetOrientY", typeof (Double)); + createCol(prims, "SitTargetOrientZ", typeof (Double)); + + createCol(prims, "PayPrice", typeof(Int32)); + createCol(prims, "PayButton1", typeof(Int32)); + createCol(prims, "PayButton2", typeof(Int32)); + createCol(prims, "PayButton3", typeof(Int32)); + createCol(prims, "PayButton4", typeof(Int32)); + + createCol(prims, "LoopedSound", typeof(String)); + createCol(prims, "LoopedSoundGain", typeof(Double)); + createCol(prims, "TextureAnimation", typeof(String)); + createCol(prims, "ParticleSystem", typeof(String)); + + createCol(prims, "OmegaX", typeof(Double)); + createCol(prims, "OmegaY", typeof(Double)); + createCol(prims, "OmegaZ", typeof(Double)); + + createCol(prims, "CameraEyeOffsetX", typeof(Double)); + createCol(prims, "CameraEyeOffsetY", typeof(Double)); + createCol(prims, "CameraEyeOffsetZ", typeof(Double)); + + createCol(prims, "CameraAtOffsetX", typeof(Double)); + createCol(prims, "CameraAtOffsetY", typeof(Double)); + createCol(prims, "CameraAtOffsetZ", typeof(Double)); + + createCol(prims, "ForceMouselook", typeof(Int16)); + + createCol(prims, "ScriptAccessPin", typeof(Int32)); + + createCol(prims, "AllowedDrop", typeof(Int16)); + createCol(prims, "DieAtEdge", typeof(Int16)); + + createCol(prims, "SalePrice", typeof(Int32)); + createCol(prims, "SaleType", typeof(Int16)); + + // click action + createCol(prims, "ClickAction", typeof (Byte)); + + createCol(prims, "Material", typeof(Byte)); + + createCol(prims, "CollisionSound", typeof(String)); + createCol(prims, "CollisionSoundVolume", typeof(Double)); + + createCol(prims, "VolumeDetect", typeof(Int16)); + + // Add in contraints + prims.PrimaryKey = new DataColumn[] {prims.Columns["UUID"]}; + + return prims; + } + + /// + /// Creates "primshapes" table + /// + /// shape table DataTable + private static DataTable createShapeTable() + { + DataTable shapes = new DataTable("primshapes"); + createCol(shapes, "UUID", typeof (String)); + // shape is an enum + createCol(shapes, "Shape", typeof (Int32)); + // vectors + createCol(shapes, "ScaleX", typeof (Double)); + createCol(shapes, "ScaleY", typeof (Double)); + createCol(shapes, "ScaleZ", typeof (Double)); + // paths + createCol(shapes, "PCode", typeof (Int32)); + createCol(shapes, "PathBegin", typeof (Int32)); + createCol(shapes, "PathEnd", typeof (Int32)); + createCol(shapes, "PathScaleX", typeof (Int32)); + createCol(shapes, "PathScaleY", typeof (Int32)); + createCol(shapes, "PathShearX", typeof (Int32)); + createCol(shapes, "PathShearY", typeof (Int32)); + createCol(shapes, "PathSkew", typeof (Int32)); + createCol(shapes, "PathCurve", typeof (Int32)); + createCol(shapes, "PathRadiusOffset", typeof (Int32)); + createCol(shapes, "PathRevolutions", typeof (Int32)); + createCol(shapes, "PathTaperX", typeof (Int32)); + createCol(shapes, "PathTaperY", typeof (Int32)); + createCol(shapes, "PathTwist", typeof (Int32)); + createCol(shapes, "PathTwistBegin", typeof (Int32)); + // profile + createCol(shapes, "ProfileBegin", typeof (Int32)); + createCol(shapes, "ProfileEnd", typeof (Int32)); + createCol(shapes, "ProfileCurve", typeof (Int32)); + createCol(shapes, "ProfileHollow", typeof (Int32)); + createCol(shapes, "State", typeof(Int32)); + // text TODO: this isn't right, but I'm not sure the right + // way to specify this as a blob atm + createCol(shapes, "Texture", typeof (Byte[])); + createCol(shapes, "ExtraParams", typeof (Byte[])); + + shapes.PrimaryKey = new DataColumn[] {shapes.Columns["UUID"]}; + + return shapes; + } + + /// + /// creates "primitems" table + /// + /// item table DataTable + private static DataTable createItemsTable() + { + DataTable items = new DataTable("primitems"); + + createCol(items, "itemID", typeof (String)); + createCol(items, "primID", typeof (String)); + createCol(items, "assetID", typeof (String)); + createCol(items, "parentFolderID", typeof (String)); + + createCol(items, "invType", typeof (Int32)); + createCol(items, "assetType", typeof (Int32)); + + createCol(items, "name", typeof (String)); + createCol(items, "description", typeof (String)); + + createCol(items, "creationDate", typeof (Int64)); + createCol(items, "creatorID", typeof (String)); + createCol(items, "ownerID", typeof (String)); + createCol(items, "lastOwnerID", typeof (String)); + createCol(items, "groupID", typeof (String)); + + createCol(items, "nextPermissions", typeof (UInt32)); + createCol(items, "currentPermissions", typeof (UInt32)); + createCol(items, "basePermissions", typeof (UInt32)); + createCol(items, "everyonePermissions", typeof (UInt32)); + createCol(items, "groupPermissions", typeof (UInt32)); + createCol(items, "flags", typeof (UInt32)); + + items.PrimaryKey = new DataColumn[] { items.Columns["itemID"] }; + + return items; + } + + /// + /// Creates "land" table + /// + /// land table DataTable + private static DataTable createLandTable() + { + DataTable land = new DataTable("land"); + createCol(land, "UUID", typeof (String)); + createCol(land, "RegionUUID", typeof (String)); + createCol(land, "LocalLandID", typeof (UInt32)); + + // Bitmap is a byte[512] + createCol(land, "Bitmap", typeof (Byte[])); + + createCol(land, "Name", typeof (String)); + createCol(land, "Desc", typeof (String)); + createCol(land, "OwnerUUID", typeof (String)); + createCol(land, "IsGroupOwned", typeof (Boolean)); + createCol(land, "Area", typeof (Int32)); + createCol(land, "AuctionID", typeof (Int32)); //Unemplemented + createCol(land, "Category", typeof (Int32)); //Enum OpenMetaverse.Parcel.ParcelCategory + createCol(land, "ClaimDate", typeof (Int32)); + createCol(land, "ClaimPrice", typeof (Int32)); + createCol(land, "GroupUUID", typeof (string)); + createCol(land, "SalePrice", typeof (Int32)); + createCol(land, "LandStatus", typeof (Int32)); //Enum. OpenMetaverse.Parcel.ParcelStatus + createCol(land, "LandFlags", typeof (UInt32)); + createCol(land, "LandingType", typeof (Byte)); + createCol(land, "MediaAutoScale", typeof (Byte)); + createCol(land, "MediaTextureUUID", typeof (String)); + createCol(land, "MediaURL", typeof (String)); + createCol(land, "MusicURL", typeof (String)); + createCol(land, "PassHours", typeof (Double)); + createCol(land, "PassPrice", typeof (UInt32)); + createCol(land, "SnapshotUUID", typeof (String)); + createCol(land, "UserLocationX", typeof (Double)); + createCol(land, "UserLocationY", typeof (Double)); + createCol(land, "UserLocationZ", typeof (Double)); + createCol(land, "UserLookAtX", typeof (Double)); + createCol(land, "UserLookAtY", typeof (Double)); + createCol(land, "UserLookAtZ", typeof (Double)); + createCol(land, "AuthbuyerID", typeof(String)); + createCol(land, "OtherCleanTime", typeof(Int32)); + createCol(land, "Dwell", typeof(Int32)); + + land.PrimaryKey = new DataColumn[] {land.Columns["UUID"]}; + + return land; + } + + /// + /// create "landaccesslist" table + /// + /// Landacceslist DataTable + private static DataTable createLandAccessListTable() + { + DataTable landaccess = new DataTable("landaccesslist"); + createCol(landaccess, "LandUUID", typeof (String)); + createCol(landaccess, "AccessUUID", typeof (String)); + createCol(landaccess, "Flags", typeof (UInt32)); + + return landaccess; + } + + private static DataTable createRegionSettingsTable() + { + DataTable regionsettings = new DataTable("regionsettings"); + createCol(regionsettings, "regionUUID", typeof(String)); + createCol(regionsettings, "block_terraform", typeof (Int32)); + createCol(regionsettings, "block_fly", typeof (Int32)); + createCol(regionsettings, "allow_damage", typeof (Int32)); + createCol(regionsettings, "restrict_pushing", typeof (Int32)); + createCol(regionsettings, "allow_land_resell", typeof (Int32)); + createCol(regionsettings, "allow_land_join_divide", typeof (Int32)); + createCol(regionsettings, "block_show_in_search", typeof (Int32)); + createCol(regionsettings, "agent_limit", typeof (Int32)); + createCol(regionsettings, "object_bonus", typeof (Double)); + createCol(regionsettings, "maturity", typeof (Int32)); + createCol(regionsettings, "disable_scripts", typeof (Int32)); + createCol(regionsettings, "disable_collisions", typeof (Int32)); + createCol(regionsettings, "disable_physics", typeof (Int32)); + createCol(regionsettings, "terrain_texture_1", typeof(String)); + createCol(regionsettings, "terrain_texture_2", typeof(String)); + createCol(regionsettings, "terrain_texture_3", typeof(String)); + createCol(regionsettings, "terrain_texture_4", typeof(String)); + createCol(regionsettings, "elevation_1_nw", typeof (Double)); + createCol(regionsettings, "elevation_2_nw", typeof (Double)); + createCol(regionsettings, "elevation_1_ne", typeof (Double)); + createCol(regionsettings, "elevation_2_ne", typeof (Double)); + createCol(regionsettings, "elevation_1_se", typeof (Double)); + createCol(regionsettings, "elevation_2_se", typeof (Double)); + createCol(regionsettings, "elevation_1_sw", typeof (Double)); + createCol(regionsettings, "elevation_2_sw", typeof (Double)); + createCol(regionsettings, "water_height", typeof (Double)); + createCol(regionsettings, "terrain_raise_limit", typeof (Double)); + createCol(regionsettings, "terrain_lower_limit", typeof (Double)); + createCol(regionsettings, "use_estate_sun", typeof (Int32)); + createCol(regionsettings, "sandbox", typeof (Int32)); + createCol(regionsettings, "sunvectorx",typeof (Double)); + createCol(regionsettings, "sunvectory",typeof (Double)); + createCol(regionsettings, "sunvectorz",typeof (Double)); + createCol(regionsettings, "fixed_sun", typeof (Int32)); + createCol(regionsettings, "sun_position", typeof (Double)); + createCol(regionsettings, "covenant", typeof(String)); + regionsettings.PrimaryKey = new DataColumn[] { regionsettings.Columns["regionUUID"] }; + return regionsettings; + } + + /*********************************************************************** + * + * Convert between ADO.NET <=> OpenSim Objects + * + * These should be database independant + * + **********************************************************************/ + + /// + /// + /// + /// + /// + private SceneObjectPart buildPrim(DataRow row) + { + // Code commented. Uncomment to test the unit test inline. + + // The unit test mentions this commented code for the purposes + // of debugging a unit test failure + + // SceneObjectGroup sog = new SceneObjectGroup(); + // SceneObjectPart sop = new SceneObjectPart(); + // sop.LocalId = 1; + // sop.Name = "object1"; + // sop.Description = "object1"; + // sop.Text = ""; + // sop.SitName = ""; + // sop.TouchName = ""; + // sop.UUID = UUID.Random(); + // sop.Shape = PrimitiveBaseShape.Default; + // sog.SetRootPart(sop); + // Add breakpoint in above line. Check sop fields. + + // TODO: this doesn't work yet because something more + // interesting has to be done to actually get these values + // back out. Not enough time to figure it out yet. + + SceneObjectPart prim = new SceneObjectPart(); + prim.UUID = new UUID((String) row["UUID"]); + // explicit conversion of integers is required, which sort + // of sucks. No idea if there is a shortcut here or not. + prim.CreationDate = Convert.ToInt32(row["CreationDate"]); + prim.Name = row["Name"] == DBNull.Value ? string.Empty : (string)row["Name"]; + // various text fields + prim.Text = (String) row["Text"]; + prim.Color = Color.FromArgb(Convert.ToInt32(row["ColorA"]), + Convert.ToInt32(row["ColorR"]), + Convert.ToInt32(row["ColorG"]), + Convert.ToInt32(row["ColorB"])); + prim.Description = (String) row["Description"]; + prim.SitName = (String) row["SitName"]; + prim.TouchName = (String) row["TouchName"]; + // permissions + prim.ObjectFlags = Convert.ToUInt32(row["ObjectFlags"]); + prim.CreatorID = new UUID((String) row["CreatorID"]); + prim.OwnerID = new UUID((String) row["OwnerID"]); + prim.GroupID = new UUID((String) row["GroupID"]); + prim.LastOwnerID = new UUID((String) row["LastOwnerID"]); + prim.OwnerMask = Convert.ToUInt32(row["OwnerMask"]); + prim.NextOwnerMask = Convert.ToUInt32(row["NextOwnerMask"]); + prim.GroupMask = Convert.ToUInt32(row["GroupMask"]); + prim.EveryoneMask = Convert.ToUInt32(row["EveryoneMask"]); + prim.BaseMask = Convert.ToUInt32(row["BaseMask"]); + // vectors + prim.OffsetPosition = new Vector3( + Convert.ToSingle(row["PositionX"]), + Convert.ToSingle(row["PositionY"]), + Convert.ToSingle(row["PositionZ"]) + ); + prim.GroupPosition = new Vector3( + Convert.ToSingle(row["GroupPositionX"]), + Convert.ToSingle(row["GroupPositionY"]), + Convert.ToSingle(row["GroupPositionZ"]) + ); + prim.Velocity = new Vector3( + Convert.ToSingle(row["VelocityX"]), + Convert.ToSingle(row["VelocityY"]), + Convert.ToSingle(row["VelocityZ"]) + ); + prim.AngularVelocity = new Vector3( + Convert.ToSingle(row["AngularVelocityX"]), + Convert.ToSingle(row["AngularVelocityY"]), + Convert.ToSingle(row["AngularVelocityZ"]) + ); + prim.Acceleration = new Vector3( + Convert.ToSingle(row["AccelerationX"]), + Convert.ToSingle(row["AccelerationY"]), + Convert.ToSingle(row["AccelerationZ"]) + ); + // quaternions + prim.RotationOffset = new Quaternion( + Convert.ToSingle(row["RotationX"]), + Convert.ToSingle(row["RotationY"]), + Convert.ToSingle(row["RotationZ"]), + Convert.ToSingle(row["RotationW"]) + ); + + prim.SitTargetPositionLL = new Vector3( + Convert.ToSingle(row["SitTargetOffsetX"]), + Convert.ToSingle(row["SitTargetOffsetY"]), + Convert.ToSingle(row["SitTargetOffsetZ"])); + prim.SitTargetOrientationLL = new Quaternion( + Convert.ToSingle( + row["SitTargetOrientX"]), + Convert.ToSingle( + row["SitTargetOrientY"]), + Convert.ToSingle( + row["SitTargetOrientZ"]), + Convert.ToSingle( + row["SitTargetOrientW"])); + + prim.ClickAction = Convert.ToByte(row["ClickAction"]); + prim.PayPrice[0] = Convert.ToInt32(row["PayPrice"]); + prim.PayPrice[1] = Convert.ToInt32(row["PayButton1"]); + prim.PayPrice[2] = Convert.ToInt32(row["PayButton2"]); + prim.PayPrice[3] = Convert.ToInt32(row["PayButton3"]); + prim.PayPrice[4] = Convert.ToInt32(row["PayButton4"]); + + prim.Sound = new UUID(row["LoopedSound"].ToString()); + prim.SoundGain = Convert.ToSingle(row["LoopedSoundGain"]); + prim.SoundFlags = 1; // If it's persisted at all, it's looped + + if (!row.IsNull("TextureAnimation")) + prim.TextureAnimation = Convert.FromBase64String(row["TextureAnimation"].ToString()); + if (!row.IsNull("ParticleSystem")) + prim.ParticleSystem = Convert.FromBase64String(row["ParticleSystem"].ToString()); + + prim.AngularVelocity = new Vector3( + Convert.ToSingle(row["OmegaX"]), + Convert.ToSingle(row["OmegaY"]), + Convert.ToSingle(row["OmegaZ"]) + ); + + prim.SetCameraEyeOffset(new Vector3( + Convert.ToSingle(row["CameraEyeOffsetX"]), + Convert.ToSingle(row["CameraEyeOffsetY"]), + Convert.ToSingle(row["CameraEyeOffsetZ"]) + )); + + prim.SetCameraAtOffset(new Vector3( + Convert.ToSingle(row["CameraAtOffsetX"]), + Convert.ToSingle(row["CameraAtOffsetY"]), + Convert.ToSingle(row["CameraAtOffsetZ"]) + )); + + if (Convert.ToInt16(row["ForceMouselook"]) != 0) + prim.SetForceMouselook(true); + + prim.ScriptAccessPin = Convert.ToInt32(row["ScriptAccessPin"]); + + if (Convert.ToInt16(row["AllowedDrop"]) != 0) + prim.AllowedDrop = true; + + if (Convert.ToInt16(row["DieAtEdge"]) != 0) + prim.DIE_AT_EDGE = true; + + prim.SalePrice = Convert.ToInt32(row["SalePrice"]); + prim.ObjectSaleType = Convert.ToByte(row["SaleType"]); + + prim.Material = Convert.ToByte(row["Material"]); + + prim.CollisionSound = new UUID(row["CollisionSound"].ToString()); + prim.CollisionSoundVolume = Convert.ToSingle(row["CollisionSoundVolume"]); + + if (Convert.ToInt16(row["VolumeDetect"]) != 0) + prim.VolumeDetectActive = true; + + return prim; + } + + /// + /// Build a prim inventory item from the persisted data. + /// + /// + /// + private static TaskInventoryItem buildItem(DataRow row) + { + TaskInventoryItem taskItem = new TaskInventoryItem(); + + taskItem.ItemID = new UUID((String)row["itemID"]); + taskItem.ParentPartID = new UUID((String)row["primID"]); + taskItem.AssetID = new UUID((String)row["assetID"]); + taskItem.ParentID = new UUID((String)row["parentFolderID"]); + + taskItem.InvType = Convert.ToInt32(row["invType"]); + taskItem.Type = Convert.ToInt32(row["assetType"]); + + taskItem.Name = (String)row["name"]; + taskItem.Description = (String)row["description"]; + taskItem.CreationDate = Convert.ToUInt32(row["creationDate"]); + taskItem.CreatorID = new UUID((String)row["creatorID"]); + taskItem.OwnerID = new UUID((String)row["ownerID"]); + taskItem.LastOwnerID = new UUID((String)row["lastOwnerID"]); + taskItem.GroupID = new UUID((String)row["groupID"]); + + taskItem.NextPermissions = Convert.ToUInt32(row["nextPermissions"]); + taskItem.CurrentPermissions = Convert.ToUInt32(row["currentPermissions"]); + taskItem.BasePermissions = Convert.ToUInt32(row["basePermissions"]); + taskItem.EveryonePermissions = Convert.ToUInt32(row["everyonePermissions"]); + taskItem.GroupPermissions = Convert.ToUInt32(row["groupPermissions"]); + taskItem.Flags = Convert.ToUInt32(row["flags"]); + + return taskItem; + } + + /// + /// Build a Land Data from the persisted data. + /// + /// + /// + private LandData buildLandData(DataRow row) + { + LandData newData = new LandData(); + + newData.GlobalID = new UUID((String) row["UUID"]); + newData.LocalID = Convert.ToInt32(row["LocalLandID"]); + + // Bitmap is a byte[512] + newData.Bitmap = (Byte[]) row["Bitmap"]; + + newData.Name = (String) row["Name"]; + newData.Description = (String) row["Desc"]; + newData.OwnerID = (UUID)(String) row["OwnerUUID"]; + newData.IsGroupOwned = (Boolean) row["IsGroupOwned"]; + newData.Area = Convert.ToInt32(row["Area"]); + newData.AuctionID = Convert.ToUInt32(row["AuctionID"]); //Unemplemented + newData.Category = (ParcelCategory) Convert.ToInt32(row["Category"]); + //Enum OpenMetaverse.Parcel.ParcelCategory + newData.ClaimDate = Convert.ToInt32(row["ClaimDate"]); + newData.ClaimPrice = Convert.ToInt32(row["ClaimPrice"]); + newData.GroupID = new UUID((String) row["GroupUUID"]); + newData.SalePrice = Convert.ToInt32(row["SalePrice"]); + newData.Status = (ParcelStatus) Convert.ToInt32(row["LandStatus"]); + //Enum. OpenMetaverse.Parcel.ParcelStatus + newData.Flags = Convert.ToUInt32(row["LandFlags"]); + newData.LandingType = (Byte) row["LandingType"]; + newData.MediaAutoScale = (Byte) row["MediaAutoScale"]; + newData.MediaID = new UUID((String) row["MediaTextureUUID"]); + newData.MediaURL = (String) row["MediaURL"]; + newData.MusicURL = (String) row["MusicURL"]; + newData.PassHours = Convert.ToSingle(row["PassHours"]); + newData.PassPrice = Convert.ToInt32(row["PassPrice"]); + newData.SnapshotID = (UUID)(String) row["SnapshotUUID"]; + try + { + + newData.UserLocation = + new Vector3(Convert.ToSingle(row["UserLocationX"]), Convert.ToSingle(row["UserLocationY"]), + Convert.ToSingle(row["UserLocationZ"])); + newData.UserLookAt = + new Vector3(Convert.ToSingle(row["UserLookAtX"]), Convert.ToSingle(row["UserLookAtY"]), + Convert.ToSingle(row["UserLookAtZ"])); + + } + catch (InvalidCastException) + { + m_log.ErrorFormat("[PARCEL]: unable to get parcel telehub settings for {1}", newData.Name); + newData.UserLocation = Vector3.Zero; + newData.UserLookAt = Vector3.Zero; + } + newData.ParcelAccessList = new List(); + UUID authBuyerID = UUID.Zero; + + UUID.TryParse((string)row["AuthbuyerID"], out authBuyerID); + + newData.OtherCleanTime = Convert.ToInt32(row["OtherCleanTime"]); + newData.Dwell = Convert.ToInt32(row["Dwell"]); + + return newData; + } + + private RegionSettings buildRegionSettings(DataRow row) + { + RegionSettings newSettings = new RegionSettings(); + + newSettings.RegionUUID = new UUID((string) row["regionUUID"]); + newSettings.BlockTerraform = Convert.ToBoolean(row["block_terraform"]); + newSettings.AllowDamage = Convert.ToBoolean(row["allow_damage"]); + newSettings.BlockFly = Convert.ToBoolean(row["block_fly"]); + newSettings.RestrictPushing = Convert.ToBoolean(row["restrict_pushing"]); + newSettings.AllowLandResell = Convert.ToBoolean(row["allow_land_resell"]); + newSettings.AllowLandJoinDivide = Convert.ToBoolean(row["allow_land_join_divide"]); + newSettings.BlockShowInSearch = Convert.ToBoolean(row["block_show_in_search"]); + newSettings.AgentLimit = Convert.ToInt32(row["agent_limit"]); + newSettings.ObjectBonus = Convert.ToDouble(row["object_bonus"]); + newSettings.Maturity = Convert.ToInt32(row["maturity"]); + newSettings.DisableScripts = Convert.ToBoolean(row["disable_scripts"]); + newSettings.DisableCollisions = Convert.ToBoolean(row["disable_collisions"]); + newSettings.DisablePhysics = Convert.ToBoolean(row["disable_physics"]); + newSettings.TerrainTexture1 = new UUID((String) row["terrain_texture_1"]); + newSettings.TerrainTexture2 = new UUID((String) row["terrain_texture_2"]); + newSettings.TerrainTexture3 = new UUID((String) row["terrain_texture_3"]); + newSettings.TerrainTexture4 = new UUID((String) row["terrain_texture_4"]); + newSettings.Elevation1NW = Convert.ToDouble(row["elevation_1_nw"]); + newSettings.Elevation2NW = Convert.ToDouble(row["elevation_2_nw"]); + newSettings.Elevation1NE = Convert.ToDouble(row["elevation_1_ne"]); + newSettings.Elevation2NE = Convert.ToDouble(row["elevation_2_ne"]); + newSettings.Elevation1SE = Convert.ToDouble(row["elevation_1_se"]); + newSettings.Elevation2SE = Convert.ToDouble(row["elevation_2_se"]); + newSettings.Elevation1SW = Convert.ToDouble(row["elevation_1_sw"]); + newSettings.Elevation2SW = Convert.ToDouble(row["elevation_2_sw"]); + newSettings.WaterHeight = Convert.ToDouble(row["water_height"]); + newSettings.TerrainRaiseLimit = Convert.ToDouble(row["terrain_raise_limit"]); + newSettings.TerrainLowerLimit = Convert.ToDouble(row["terrain_lower_limit"]); + newSettings.UseEstateSun = Convert.ToBoolean(row["use_estate_sun"]); + newSettings.Sandbox = Convert.ToBoolean(row["sandbox"]); + newSettings.SunVector = new Vector3 ( + Convert.ToSingle(row["sunvectorx"]), + Convert.ToSingle(row["sunvectory"]), + Convert.ToSingle(row["sunvectorz"]) + ); + newSettings.FixedSun = Convert.ToBoolean(row["fixed_sun"]); + newSettings.SunPosition = Convert.ToDouble(row["sun_position"]); + newSettings.Covenant = new UUID((String) row["covenant"]); + + return newSettings; + } + + /// + /// Build a land access entry from the persisted data. + /// + /// + /// + private static ParcelManager.ParcelAccessEntry buildLandAccessData(DataRow row) + { + ParcelManager.ParcelAccessEntry entry = new ParcelManager.ParcelAccessEntry(); + entry.AgentID = new UUID((string) row["AccessUUID"]); + entry.Flags = (AccessList) row["Flags"]; + entry.Time = new DateTime(); + return entry; + } + + /// + /// + /// + /// + /// + private static Array serializeTerrain(double[,] val) + { + MemoryStream str = new MemoryStream(((int)Constants.RegionSize * (int)Constants.RegionSize) *sizeof (double)); + BinaryWriter bw = new BinaryWriter(str); + + // TODO: COMPATIBILITY - Add byte-order conversions + for (int x = 0; x < (int)Constants.RegionSize; x++) + for (int y = 0; y < (int)Constants.RegionSize; y++) + bw.Write(val[x, y]); + + return str.ToArray(); + } + +// private void fillTerrainRow(DataRow row, UUID regionUUID, int rev, double[,] val) +// { +// row["RegionUUID"] = regionUUID; +// row["Revision"] = rev; + + // MemoryStream str = new MemoryStream(((int)Constants.RegionSize * (int)Constants.RegionSize)*sizeof (double)); +// BinaryWriter bw = new BinaryWriter(str); + +// // TODO: COMPATIBILITY - Add byte-order conversions + // for (int x = 0; x < (int)Constants.RegionSize; x++) + // for (int y = 0; y < (int)Constants.RegionSize; y++) +// bw.Write(val[x, y]); + +// row["Heightfield"] = str.ToArray(); +// } + + /// + /// + /// + /// + /// + /// + /// + private static void fillPrimRow(DataRow row, SceneObjectPart prim, UUID sceneGroupID, UUID regionUUID) + { + row["UUID"] = prim.UUID.ToString(); + row["RegionUUID"] = regionUUID.ToString(); + row["CreationDate"] = prim.CreationDate; + row["Name"] = prim.Name; + row["SceneGroupID"] = sceneGroupID.ToString(); + // the UUID of the root part for this SceneObjectGroup + // various text fields + row["Text"] = prim.Text; + row["Description"] = prim.Description; + row["SitName"] = prim.SitName; + row["TouchName"] = prim.TouchName; + // permissions + row["ObjectFlags"] = prim.ObjectFlags; + row["CreatorID"] = prim.CreatorID.ToString(); + row["OwnerID"] = prim.OwnerID.ToString(); + row["GroupID"] = prim.GroupID.ToString(); + row["LastOwnerID"] = prim.LastOwnerID.ToString(); + row["OwnerMask"] = prim.OwnerMask; + row["NextOwnerMask"] = prim.NextOwnerMask; + row["GroupMask"] = prim.GroupMask; + row["EveryoneMask"] = prim.EveryoneMask; + row["BaseMask"] = prim.BaseMask; + // vectors + row["PositionX"] = prim.OffsetPosition.X; + row["PositionY"] = prim.OffsetPosition.Y; + row["PositionZ"] = prim.OffsetPosition.Z; + row["GroupPositionX"] = prim.GroupPosition.X; + row["GroupPositionY"] = prim.GroupPosition.Y; + row["GroupPositionZ"] = prim.GroupPosition.Z; + row["VelocityX"] = prim.Velocity.X; + row["VelocityY"] = prim.Velocity.Y; + row["VelocityZ"] = prim.Velocity.Z; + row["AngularVelocityX"] = prim.AngularVelocity.X; + row["AngularVelocityY"] = prim.AngularVelocity.Y; + row["AngularVelocityZ"] = prim.AngularVelocity.Z; + row["AccelerationX"] = prim.Acceleration.X; + row["AccelerationY"] = prim.Acceleration.Y; + row["AccelerationZ"] = prim.Acceleration.Z; + // quaternions + row["RotationX"] = prim.RotationOffset.X; + row["RotationY"] = prim.RotationOffset.Y; + row["RotationZ"] = prim.RotationOffset.Z; + row["RotationW"] = prim.RotationOffset.W; + + // Sit target + Vector3 sitTargetPos = prim.SitTargetPositionLL; + row["SitTargetOffsetX"] = sitTargetPos.X; + row["SitTargetOffsetY"] = sitTargetPos.Y; + row["SitTargetOffsetZ"] = sitTargetPos.Z; + + Quaternion sitTargetOrient = prim.SitTargetOrientationLL; + row["SitTargetOrientW"] = sitTargetOrient.W; + row["SitTargetOrientX"] = sitTargetOrient.X; + row["SitTargetOrientY"] = sitTargetOrient.Y; + row["SitTargetOrientZ"] = sitTargetOrient.Z; + row["ColorR"] = Convert.ToInt32(prim.Color.R); + row["ColorG"] = Convert.ToInt32(prim.Color.G); + row["ColorB"] = Convert.ToInt32(prim.Color.B); + row["ColorA"] = Convert.ToInt32(prim.Color.A); + row["PayPrice"] = prim.PayPrice[0]; + row["PayButton1"] = prim.PayPrice[1]; + row["PayButton2"] = prim.PayPrice[2]; + row["PayButton3"] = prim.PayPrice[3]; + row["PayButton4"] = prim.PayPrice[4]; + + + row["TextureAnimation"] = Convert.ToBase64String(prim.TextureAnimation); + row["ParticleSystem"] = Convert.ToBase64String(prim.ParticleSystem); + + row["OmegaX"] = prim.AngularVelocity.X; + row["OmegaY"] = prim.AngularVelocity.Y; + row["OmegaZ"] = prim.AngularVelocity.Z; + + row["CameraEyeOffsetX"] = prim.GetCameraEyeOffset().X; + row["CameraEyeOffsetY"] = prim.GetCameraEyeOffset().Y; + row["CameraEyeOffsetZ"] = prim.GetCameraEyeOffset().Z; + + row["CameraAtOffsetX"] = prim.GetCameraAtOffset().X; + row["CameraAtOffsetY"] = prim.GetCameraAtOffset().Y; + row["CameraAtOffsetZ"] = prim.GetCameraAtOffset().Z; + + + if ((prim.SoundFlags & 1) != 0) // Looped + { + row["LoopedSound"] = prim.Sound.ToString(); + row["LoopedSoundGain"] = prim.SoundGain; + } + else + { + row["LoopedSound"] = UUID.Zero.ToString(); + row["LoopedSoundGain"] = 0.0f; + } + + if (prim.GetForceMouselook()) + row["ForceMouselook"] = 1; + else + row["ForceMouselook"] = 0; + + row["ScriptAccessPin"] = prim.ScriptAccessPin; + + if (prim.AllowedDrop) + row["AllowedDrop"] = 1; + else + row["AllowedDrop"] = 0; + + if (prim.DIE_AT_EDGE) + row["DieAtEdge"] = 1; + else + row["DieAtEdge"] = 0; + + row["SalePrice"] = prim.SalePrice; + row["SaleType"] = Convert.ToInt16(prim.ObjectSaleType); + + // click action + row["ClickAction"] = prim.ClickAction; + + row["SalePrice"] = prim.SalePrice; + row["Material"] = prim.Material; + + row["CollisionSound"] = prim.CollisionSound.ToString(); + row["CollisionSoundVolume"] = prim.CollisionSoundVolume; + if (prim.VolumeDetectActive) + row["VolumeDetect"] = 1; + else + row["VolumeDetect"] = 0; + + } + + /// + /// + /// + /// + /// + private static void fillItemRow(DataRow row, TaskInventoryItem taskItem) + { + row["itemID"] = taskItem.ItemID.ToString(); + row["primID"] = taskItem.ParentPartID.ToString(); + row["assetID"] = taskItem.AssetID.ToString(); + row["parentFolderID"] = taskItem.ParentID.ToString(); + + row["invType"] = taskItem.InvType; + row["assetType"] = taskItem.Type; + + row["name"] = taskItem.Name; + row["description"] = taskItem.Description; + row["creationDate"] = taskItem.CreationDate; + row["creatorID"] = taskItem.CreatorID.ToString(); + row["ownerID"] = taskItem.OwnerID.ToString(); + row["lastOwnerID"] = taskItem.LastOwnerID.ToString(); + row["groupID"] = taskItem.GroupID.ToString(); + row["nextPermissions"] = taskItem.NextPermissions; + row["currentPermissions"] = taskItem.CurrentPermissions; + row["basePermissions"] = taskItem.BasePermissions; + row["everyonePermissions"] = taskItem.EveryonePermissions; + row["groupPermissions"] = taskItem.GroupPermissions; + row["flags"] = taskItem.Flags; + } + + /// + /// + /// + /// + /// + /// + private static void fillLandRow(DataRow row, LandData land, UUID regionUUID) + { + row["UUID"] = land.GlobalID.ToString(); + row["RegionUUID"] = regionUUID.ToString(); + row["LocalLandID"] = land.LocalID; + + // Bitmap is a byte[512] + row["Bitmap"] = land.Bitmap; + + row["Name"] = land.Name; + row["Desc"] = land.Description; + row["OwnerUUID"] = land.OwnerID.ToString(); + row["IsGroupOwned"] = land.IsGroupOwned; + row["Area"] = land.Area; + row["AuctionID"] = land.AuctionID; //Unemplemented + row["Category"] = land.Category; //Enum OpenMetaverse.Parcel.ParcelCategory + row["ClaimDate"] = land.ClaimDate; + row["ClaimPrice"] = land.ClaimPrice; + row["GroupUUID"] = land.GroupID.ToString(); + row["SalePrice"] = land.SalePrice; + row["LandStatus"] = land.Status; //Enum. OpenMetaverse.Parcel.ParcelStatus + row["LandFlags"] = land.Flags; + row["LandingType"] = land.LandingType; + row["MediaAutoScale"] = land.MediaAutoScale; + row["MediaTextureUUID"] = land.MediaID.ToString(); + row["MediaURL"] = land.MediaURL; + row["MusicURL"] = land.MusicURL; + row["PassHours"] = land.PassHours; + row["PassPrice"] = land.PassPrice; + row["SnapshotUUID"] = land.SnapshotID.ToString(); + row["UserLocationX"] = land.UserLocation.X; + row["UserLocationY"] = land.UserLocation.Y; + row["UserLocationZ"] = land.UserLocation.Z; + row["UserLookAtX"] = land.UserLookAt.X; + row["UserLookAtY"] = land.UserLookAt.Y; + row["UserLookAtZ"] = land.UserLookAt.Z; + row["AuthbuyerID"] = land.AuthBuyerID.ToString(); + row["OtherCleanTime"] = land.OtherCleanTime; + row["Dwell"] = land.Dwell; + } + + /// + /// + /// + /// + /// + /// + private static void fillLandAccessRow(DataRow row, ParcelManager.ParcelAccessEntry entry, UUID parcelID) + { + row["LandUUID"] = parcelID.ToString(); + row["AccessUUID"] = entry.AgentID.ToString(); + row["Flags"] = entry.Flags; + } + + private static void fillRegionSettingsRow(DataRow row, RegionSettings settings) + { + row["regionUUID"] = settings.RegionUUID.ToString(); + row["block_terraform"] = settings.BlockTerraform; + row["block_fly"] = settings.BlockFly; + row["allow_damage"] = settings.AllowDamage; + row["restrict_pushing"] = settings.RestrictPushing; + row["allow_land_resell"] = settings.AllowLandResell; + row["allow_land_join_divide"] = settings.AllowLandJoinDivide; + row["block_show_in_search"] = settings.BlockShowInSearch; + row["agent_limit"] = settings.AgentLimit; + row["object_bonus"] = settings.ObjectBonus; + row["maturity"] = settings.Maturity; + row["disable_scripts"] = settings.DisableScripts; + row["disable_collisions"] = settings.DisableCollisions; + row["disable_physics"] = settings.DisablePhysics; + row["terrain_texture_1"] = settings.TerrainTexture1.ToString(); + row["terrain_texture_2"] = settings.TerrainTexture2.ToString(); + row["terrain_texture_3"] = settings.TerrainTexture3.ToString(); + row["terrain_texture_4"] = settings.TerrainTexture4.ToString(); + row["elevation_1_nw"] = settings.Elevation1NW; + row["elevation_2_nw"] = settings.Elevation2NW; + row["elevation_1_ne"] = settings.Elevation1NE; + row["elevation_2_ne"] = settings.Elevation2NE; + row["elevation_1_se"] = settings.Elevation1SE; + row["elevation_2_se"] = settings.Elevation2SE; + row["elevation_1_sw"] = settings.Elevation1SW; + row["elevation_2_sw"] = settings.Elevation2SW; + row["water_height"] = settings.WaterHeight; + row["terrain_raise_limit"] = settings.TerrainRaiseLimit; + row["terrain_lower_limit"] = settings.TerrainLowerLimit; + row["use_estate_sun"] = settings.UseEstateSun; + row["Sandbox"] = settings.Sandbox; // database uses upper case S for sandbox + row["sunvectorx"] = settings.SunVector.X; + row["sunvectory"] = settings.SunVector.Y; + row["sunvectorz"] = settings.SunVector.Z; + row["fixed_sun"] = settings.FixedSun; + row["sun_position"] = settings.SunPosition; + row["covenant"] = settings.Covenant.ToString(); + } + + /// + /// + /// + /// + /// + private PrimitiveBaseShape buildShape(DataRow row) + { + PrimitiveBaseShape s = new PrimitiveBaseShape(); + s.Scale = new Vector3( + Convert.ToSingle(row["ScaleX"]), + Convert.ToSingle(row["ScaleY"]), + Convert.ToSingle(row["ScaleZ"]) + ); + // paths + s.PCode = Convert.ToByte(row["PCode"]); + s.PathBegin = Convert.ToUInt16(row["PathBegin"]); + s.PathEnd = Convert.ToUInt16(row["PathEnd"]); + s.PathScaleX = Convert.ToByte(row["PathScaleX"]); + s.PathScaleY = Convert.ToByte(row["PathScaleY"]); + s.PathShearX = Convert.ToByte(row["PathShearX"]); + s.PathShearY = Convert.ToByte(row["PathShearY"]); + s.PathSkew = Convert.ToSByte(row["PathSkew"]); + s.PathCurve = Convert.ToByte(row["PathCurve"]); + s.PathRadiusOffset = Convert.ToSByte(row["PathRadiusOffset"]); + s.PathRevolutions = Convert.ToByte(row["PathRevolutions"]); + s.PathTaperX = Convert.ToSByte(row["PathTaperX"]); + s.PathTaperY = Convert.ToSByte(row["PathTaperY"]); + s.PathTwist = Convert.ToSByte(row["PathTwist"]); + s.PathTwistBegin = Convert.ToSByte(row["PathTwistBegin"]); + // profile + s.ProfileBegin = Convert.ToUInt16(row["ProfileBegin"]); + s.ProfileEnd = Convert.ToUInt16(row["ProfileEnd"]); + s.ProfileCurve = Convert.ToByte(row["ProfileCurve"]); + s.ProfileHollow = Convert.ToUInt16(row["ProfileHollow"]); + s.State = Convert.ToByte(row["State"]); + + byte[] textureEntry = (byte[])row["Texture"]; + s.TextureEntry = textureEntry; + + s.ExtraParams = (byte[]) row["ExtraParams"]; + return s; + } + + /// + /// + /// + /// + /// + private static void fillShapeRow(DataRow row, SceneObjectPart prim) + { + PrimitiveBaseShape s = prim.Shape; + row["UUID"] = prim.UUID.ToString(); + // shape is an enum + row["Shape"] = 0; + // vectors + row["ScaleX"] = s.Scale.X; + row["ScaleY"] = s.Scale.Y; + row["ScaleZ"] = s.Scale.Z; + // paths + row["PCode"] = s.PCode; + row["PathBegin"] = s.PathBegin; + row["PathEnd"] = s.PathEnd; + row["PathScaleX"] = s.PathScaleX; + row["PathScaleY"] = s.PathScaleY; + row["PathShearX"] = s.PathShearX; + row["PathShearY"] = s.PathShearY; + row["PathSkew"] = s.PathSkew; + row["PathCurve"] = s.PathCurve; + row["PathRadiusOffset"] = s.PathRadiusOffset; + row["PathRevolutions"] = s.PathRevolutions; + row["PathTaperX"] = s.PathTaperX; + row["PathTaperY"] = s.PathTaperY; + row["PathTwist"] = s.PathTwist; + row["PathTwistBegin"] = s.PathTwistBegin; + // profile + row["ProfileBegin"] = s.ProfileBegin; + row["ProfileEnd"] = s.ProfileEnd; + row["ProfileCurve"] = s.ProfileCurve; + row["ProfileHollow"] = s.ProfileHollow; + row["State"] = s.State; + + row["Texture"] = s.TextureEntry; + row["ExtraParams"] = s.ExtraParams; + } + + /// + /// + /// + /// + /// + /// + private void addPrim(SceneObjectPart prim, UUID sceneGroupID, UUID regionUUID) + { + + DataTable prims = ds.Tables["prims"]; + DataTable shapes = ds.Tables["primshapes"]; + + DataRow primRow = prims.Rows.Find(prim.UUID.ToString()); + if (primRow == null) + { + primRow = prims.NewRow(); + fillPrimRow(primRow, prim, sceneGroupID, regionUUID); + prims.Rows.Add(primRow); + } + else + { + fillPrimRow(primRow, prim, sceneGroupID, regionUUID); + } + + DataRow shapeRow = shapes.Rows.Find(prim.UUID.ToString()); + if (shapeRow == null) + { + shapeRow = shapes.NewRow(); + fillShapeRow(shapeRow, prim); + shapes.Rows.Add(shapeRow); + } + else + { + fillShapeRow(shapeRow, prim); + } + } + + /// + /// see IRegionDatastore + /// + /// + /// + public void StorePrimInventory(UUID primID, ICollection items) + { + m_log.InfoFormat("[REGION DB]: Entered StorePrimInventory with prim ID {0}", primID); + + DataTable dbItems = ds.Tables["primitems"]; + + // For now, we're just going to crudely remove all the previous inventory items + // no matter whether they have changed or not, and replace them with the current set. + lock (ds) + { + RemoveItems(primID); + + // repalce with current inventory details + foreach (TaskInventoryItem newItem in items) + { +// m_log.InfoFormat( +// "[DATASTORE]: ", +// "Adding item {0}, {1} to prim ID {2}", +// newItem.Name, newItem.ItemID, newItem.ParentPartID); + + DataRow newItemRow = dbItems.NewRow(); + fillItemRow(newItemRow, newItem); + dbItems.Rows.Add(newItemRow); + } + } + + Commit(); + } + + /*********************************************************************** + * + * SQL Statement Creation Functions + * + * These functions create SQL statements for update, insert, and create. + * They can probably be factored later to have a db independant + * portion and a db specific portion + * + **********************************************************************/ + + /// + /// Create an insert command + /// + /// table name + /// data table + /// the created command + /// + /// This is subtle enough to deserve some commentary. + /// Instead of doing *lots* and *lots of hardcoded strings + /// for database definitions we'll use the fact that + /// realistically all insert statements look like "insert + /// into A(b, c) values(:b, :c) on the parameterized query + /// front. If we just have a list of b, c, etc... we can + /// generate these strings instead of typing them out. + /// + private static SqliteCommand createInsertCommand(string table, DataTable dt) + { + string[] cols = new string[dt.Columns.Count]; + for (int i = 0; i < dt.Columns.Count; i++) + { + DataColumn col = dt.Columns[i]; + cols[i] = col.ColumnName; + } + + string sql = "insert into " + table + "("; + sql += String.Join(", ", cols); + // important, the first ':' needs to be here, the rest get added in the join + sql += ") values (:"; + sql += String.Join(", :", cols); + sql += ")"; + SqliteCommand cmd = new SqliteCommand(sql); + + // this provides the binding for all our parameters, so + // much less code than it used to be + foreach (DataColumn col in dt.Columns) + { + cmd.Parameters.Add(createSqliteParameter(col.ColumnName, col.DataType)); + } + return cmd; + } + + + /// + /// create an update command + /// + /// table name + /// + /// + /// the created command + private static SqliteCommand createUpdateCommand(string table, string pk, DataTable dt) + { + string sql = "update " + table + " set "; + string subsql = String.Empty; + foreach (DataColumn col in dt.Columns) + { + if (subsql.Length > 0) + { + // a map function would rock so much here + subsql += ", "; + } + subsql += col.ColumnName + "= :" + col.ColumnName; + } + sql += subsql; + sql += " where " + pk; + SqliteCommand cmd = new SqliteCommand(sql); + + // this provides the binding for all our parameters, so + // much less code than it used to be + + foreach (DataColumn col in dt.Columns) + { + cmd.Parameters.Add(createSqliteParameter(col.ColumnName, col.DataType)); + } + return cmd; + } + + /// + /// create an update command + /// + /// table name + /// + /// + /// the created command + private static SqliteCommand createUpdateCommand(string table, string pk1, string pk2, DataTable dt) + { + string sql = "update " + table + " set "; + string subsql = String.Empty; + foreach (DataColumn col in dt.Columns) + { + if (subsql.Length > 0) + { + // a map function would rock so much here + subsql += ", "; + } + subsql += col.ColumnName + "= :" + col.ColumnName; + } + sql += subsql; + sql += " where " + pk1 + " and " + pk2; + SqliteCommand cmd = new SqliteCommand(sql); + + // this provides the binding for all our parameters, so + // much less code than it used to be + + foreach (DataColumn col in dt.Columns) + { + cmd.Parameters.Add(createSqliteParameter(col.ColumnName, col.DataType)); + } + return cmd; + } + + /// + /// + /// + /// Data Table + /// + // private static string defineTable(DataTable dt) + // { + // string sql = "create table " + dt.TableName + "("; + // string subsql = String.Empty; + // foreach (DataColumn col in dt.Columns) + // { + // if (subsql.Length > 0) + // { + // // a map function would rock so much here + // subsql += ",\n"; + // } + // subsql += col.ColumnName + " " + sqliteType(col.DataType); + // if (dt.PrimaryKey.Length > 0 && col == dt.PrimaryKey[0]) + // { + // subsql += " primary key"; + // } + // } + // sql += subsql; + // sql += ")"; + // return sql; + // } + + /*********************************************************************** + * + * Database Binding functions + * + * These will be db specific due to typing, and minor differences + * in databases. + * + **********************************************************************/ + + /// + /// This is a convenience function that collapses 5 repetitive + /// lines for defining SqliteParameters to 2 parameters: + /// column name and database type. + /// + /// It assumes certain conventions like :param as the param + /// name to replace in parametrized queries, and that source + /// version is always current version, both of which are fine + /// for us. + /// + ///a built sqlite parameter + private static SqliteParameter createSqliteParameter(string name, Type type) + { + SqliteParameter param = new SqliteParameter(); + param.ParameterName = ":" + name; + param.DbType = dbtypeFromType(type); + param.SourceColumn = name; + param.SourceVersion = DataRowVersion.Current; + return param; + } + + /// + /// + /// + /// + /// + private void setupPrimCommands(SqliteDataAdapter da, SqliteConnection conn) + { + da.InsertCommand = createInsertCommand("prims", ds.Tables["prims"]); + da.InsertCommand.Connection = conn; + + da.UpdateCommand = createUpdateCommand("prims", "UUID=:UUID", ds.Tables["prims"]); + da.UpdateCommand.Connection = conn; + + SqliteCommand delete = new SqliteCommand("delete from prims where UUID = :UUID"); + delete.Parameters.Add(createSqliteParameter("UUID", typeof (String))); + delete.Connection = conn; + da.DeleteCommand = delete; + } + + /// + /// + /// + /// + /// + private void setupItemsCommands(SqliteDataAdapter da, SqliteConnection conn) + { + da.InsertCommand = createInsertCommand("primitems", ds.Tables["primitems"]); + da.InsertCommand.Connection = conn; + + da.UpdateCommand = createUpdateCommand("primitems", "itemID = :itemID", ds.Tables["primitems"]); + da.UpdateCommand.Connection = conn; + + SqliteCommand delete = new SqliteCommand("delete from primitems where itemID = :itemID"); + delete.Parameters.Add(createSqliteParameter("itemID", typeof (String))); + delete.Connection = conn; + da.DeleteCommand = delete; + } + + /// + /// + /// + /// + /// + private void setupTerrainCommands(SqliteDataAdapter da, SqliteConnection conn) + { + da.InsertCommand = createInsertCommand("terrain", ds.Tables["terrain"]); + da.InsertCommand.Connection = conn; + } + + /// + /// + /// + /// + /// + private void setupLandCommands(SqliteDataAdapter da, SqliteConnection conn) + { + da.InsertCommand = createInsertCommand("land", ds.Tables["land"]); + da.InsertCommand.Connection = conn; + + da.UpdateCommand = createUpdateCommand("land", "UUID=:UUID", ds.Tables["land"]); + da.UpdateCommand.Connection = conn; + + SqliteCommand delete = new SqliteCommand("delete from land where UUID=:UUID"); + delete.Parameters.Add(createSqliteParameter("UUID", typeof(String))); + da.DeleteCommand = delete; + da.DeleteCommand.Connection = conn; + } + + /// + /// + /// + /// + /// + private void setupLandAccessCommands(SqliteDataAdapter da, SqliteConnection conn) + { + da.InsertCommand = createInsertCommand("landaccesslist", ds.Tables["landaccesslist"]); + da.InsertCommand.Connection = conn; + + da.UpdateCommand = createUpdateCommand("landaccesslist", "LandUUID=:landUUID", "AccessUUID=:AccessUUID", ds.Tables["landaccesslist"]); + da.UpdateCommand.Connection = conn; + + SqliteCommand delete = new SqliteCommand("delete from landaccesslist where LandUUID= :LandUUID and AccessUUID= :AccessUUID"); + delete.Parameters.Add(createSqliteParameter("LandUUID", typeof(String))); + delete.Parameters.Add(createSqliteParameter("AccessUUID", typeof(String))); + da.DeleteCommand = delete; + da.DeleteCommand.Connection = conn; + + } + + private void setupRegionSettingsCommands(SqliteDataAdapter da, SqliteConnection conn) + { + da.InsertCommand = createInsertCommand("regionsettings", ds.Tables["regionsettings"]); + da.InsertCommand.Connection = conn; + da.UpdateCommand = createUpdateCommand("regionsettings", "regionUUID=:regionUUID", ds.Tables["regionsettings"]); + da.UpdateCommand.Connection = conn; + } + + /// + /// + /// + /// + /// + private void setupShapeCommands(SqliteDataAdapter da, SqliteConnection conn) + { + da.InsertCommand = createInsertCommand("primshapes", ds.Tables["primshapes"]); + da.InsertCommand.Connection = conn; + + da.UpdateCommand = createUpdateCommand("primshapes", "UUID=:UUID", ds.Tables["primshapes"]); + da.UpdateCommand.Connection = conn; + + SqliteCommand delete = new SqliteCommand("delete from primshapes where UUID = :UUID"); + delete.Parameters.Add(createSqliteParameter("UUID", typeof (String))); + delete.Connection = conn; + da.DeleteCommand = delete; + } + + /*********************************************************************** + * + * Type conversion functions + * + **********************************************************************/ + + /// + /// Type conversion function + /// + /// + /// + private static DbType dbtypeFromType(Type type) + { + if (type == typeof (String)) + { + return DbType.String; + } + else if (type == typeof (Int32)) + { + return DbType.Int32; + } + else if (type == typeof (Double)) + { + return DbType.Double; + } + else if (type == typeof (Byte)) + { + return DbType.Byte; + } + else if (type == typeof (Double)) + { + return DbType.Double; + } + else if (type == typeof (Byte[])) + { + return DbType.Binary; + } + else + { + return DbType.String; + } + } + + } +} diff --git a/OpenSim/Data/MySQL/Tests/MySQLAssetTest.cs b/OpenSim/Data/SQLiteLegacy/SQLiteUserAccountData.cs similarity index 50% rename from OpenSim/Data/MySQL/Tests/MySQLAssetTest.cs rename to OpenSim/Data/SQLiteLegacy/SQLiteUserAccountData.cs index a46fdf863f..27553c61eb 100644 --- a/OpenSim/Data/MySQL/Tests/MySQLAssetTest.cs +++ b/OpenSim/Data/SQLiteLegacy/SQLiteUserAccountData.cs @@ -26,67 +26,56 @@ */ using System; -using NUnit.Framework; -using OpenSim.Data.Tests; -using log4net; -using System.Reflection; -using OpenSim.Tests.Common; -using MySql.Data.MySqlClient; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using OpenMetaverse; +using OpenSim.Framework; +using Mono.Data.SqliteClient; -namespace OpenSim.Data.MySQL.Tests +namespace OpenSim.Data.SQLiteLegacy { - [TestFixture, DatabaseTest] - public class MySQLAssetTest : BasicAssetTest + public class SQLiteUserAccountData : SQLiteGenericTableHandler, IUserAccountData { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - public string file; - private string m_connectionString; - public string connect = "Server=localhost;Port=3306;Database=opensim-nunit;User ID=opensim-nunit;Password=opensim-nunit;Pooling=false;"; - - [TestFixtureSetUp] - public void Init() + public SQLiteUserAccountData(string connectionString, string realm) + : base(connectionString, realm, "UserAccount") { - SuperInit(); - // If we manage to connect to the database with the user - // and password above it is our test database, and run - // these tests. If anything goes wrong, ignore these - // tests. - try - { - db = new MySQLAssetData(); - db.Initialise(connect); - } - catch (Exception e) - { - m_log.Error(e.ToString()); - Assert.Ignore(); - } } - [TestFixtureTearDown] - public void Cleanup() + public UserAccountData[] GetUsers(UUID scopeID, string query) { - if (db != null) - { - db.Dispose(); - } - ExecuteSql("drop table migrations"); - ExecuteSql("drop table assets"); - } + string[] words = query.Split(new char[] {' '}); - /// - /// Execute a MySqlCommand - /// - /// sql string to execute - private void ExecuteSql(string sql) - { - using (MySqlConnection dbcon = new MySqlConnection(connect)) + for (int i = 0 ; i < words.Length ; i++) { - dbcon.Open(); - - MySqlCommand cmd = new MySqlCommand(sql, dbcon); - cmd.ExecuteNonQuery(); + if (words[i].Length < 3) + { + if (i != words.Length - 1) + Array.Copy(words, i + 1, words, i, words.Length - i - 1); + Array.Resize(ref words, words.Length - 1); + } } + + if (words.Length == 0) + return new UserAccountData[0]; + + if (words.Length > 2) + return new UserAccountData[0]; + + SqliteCommand cmd = new SqliteCommand(); + + if (words.Length == 1) + { + cmd.CommandText = String.Format("select * from {0} where (ScopeID='{1}' or ScopeID='00000000-0000-0000-0000-000000000000') and (FirstName like '{2}%' or LastName like '{2}%')", + m_Realm, scopeID.ToString(), words[0]); + } + else + { + cmd.CommandText = String.Format("select * from {0} where (ScopeID='{1}' or ScopeID='00000000-0000-0000-0000-000000000000') and (FirstName like '{2}%' or LastName like '{3}%')", + m_Realm, scopeID.ToString(), words[0], words[1]); + } + + return DoQuery(cmd); } } } diff --git a/OpenSim/Data/SQLiteLegacy/SQLiteUtils.cs b/OpenSim/Data/SQLiteLegacy/SQLiteUtils.cs new file mode 100644 index 0000000000..095a26251f --- /dev/null +++ b/OpenSim/Data/SQLiteLegacy/SQLiteUtils.cs @@ -0,0 +1,307 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Data; +using Mono.Data.SqliteClient; + +namespace OpenSim.Data.SQLiteLegacy +{ + /// + /// A base class for methods needed by all SQLite database classes + /// + public class SQLiteUtil + { + /*********************************************************************** + * + * Database Definition Helper Functions + * + * This should be db agnostic as we define them in ADO.NET terms + * + **********************************************************************/ + + /// + /// + /// + /// + /// + /// + public static void createCol(DataTable dt, string name, Type type) + { + DataColumn col = new DataColumn(name, type); + dt.Columns.Add(col); + } + + /*********************************************************************** + * + * SQL Statement Creation Functions + * + * These functions create SQL statements for update, insert, and create. + * They can probably be factored later to have a db independant + * portion and a db specific portion + * + **********************************************************************/ + + /// + /// Create an insert command + /// + /// table name + /// data table + /// the created command + /// + /// This is subtle enough to deserve some commentary. + /// Instead of doing *lots* and *lots of hardcoded strings + /// for database definitions we'll use the fact that + /// realistically all insert statements look like "insert + /// into A(b, c) values(:b, :c) on the parameterized query + /// front. If we just have a list of b, c, etc... we can + /// generate these strings instead of typing them out. + /// + public static SqliteCommand createInsertCommand(string table, DataTable dt) + { + + string[] cols = new string[dt.Columns.Count]; + for (int i = 0; i < dt.Columns.Count; i++) + { + DataColumn col = dt.Columns[i]; + cols[i] = col.ColumnName; + } + + string sql = "insert into " + table + "("; + sql += String.Join(", ", cols); + // important, the first ':' needs to be here, the rest get added in the join + sql += ") values (:"; + sql += String.Join(", :", cols); + sql += ")"; + SqliteCommand cmd = new SqliteCommand(sql); + + // this provides the binding for all our parameters, so + // much less code than it used to be + foreach (DataColumn col in dt.Columns) + { + cmd.Parameters.Add(createSqliteParameter(col.ColumnName, col.DataType)); + } + return cmd; + } + + /// + /// create an update command + /// + /// table name + /// + /// + /// the created command + public static SqliteCommand createUpdateCommand(string table, string pk, DataTable dt) + { + string sql = "update " + table + " set "; + string subsql = String.Empty; + foreach (DataColumn col in dt.Columns) + { + if (subsql.Length > 0) + { + // a map function would rock so much here + subsql += ", "; + } + subsql += col.ColumnName + "= :" + col.ColumnName; + } + sql += subsql; + sql += " where " + pk; + SqliteCommand cmd = new SqliteCommand(sql); + + // this provides the binding for all our parameters, so + // much less code than it used to be + + foreach (DataColumn col in dt.Columns) + { + cmd.Parameters.Add(createSqliteParameter(col.ColumnName, col.DataType)); + } + return cmd; + } + + /// + /// + /// + /// Data Table + /// + public static string defineTable(DataTable dt) + { + string sql = "create table " + dt.TableName + "("; + string subsql = String.Empty; + foreach (DataColumn col in dt.Columns) + { + if (subsql.Length > 0) + { + // a map function would rock so much here + subsql += ",\n"; + } + subsql += col.ColumnName + " " + sqliteType(col.DataType); + if (dt.PrimaryKey.Length > 0) + { + if (col == dt.PrimaryKey[0]) + { + subsql += " primary key"; + } + } + } + sql += subsql; + sql += ")"; + return sql; + } + + /*********************************************************************** + * + * Database Binding functions + * + * These will be db specific due to typing, and minor differences + * in databases. + * + **********************************************************************/ + + /// + /// + /// This is a convenience function that collapses 5 repetitive + /// lines for defining SqliteParameters to 2 parameters: + /// column name and database type. + /// + /// + /// + /// It assumes certain conventions like :param as the param + /// name to replace in parametrized queries, and that source + /// version is always current version, both of which are fine + /// for us. + /// + /// + /// + /// + ///a built sqlite parameter + public static SqliteParameter createSqliteParameter(string name, Type type) + { + SqliteParameter param = new SqliteParameter(); + param.ParameterName = ":" + name; + param.DbType = dbtypeFromType(type); + param.SourceColumn = name; + param.SourceVersion = DataRowVersion.Current; + return param; + } + + /*********************************************************************** + * + * Type conversion functions + * + **********************************************************************/ + + /// + /// Type conversion function + /// + /// a type + /// a DbType + public static DbType dbtypeFromType(Type type) + { + if (type == typeof (String)) + { + return DbType.String; + } + else if (type == typeof (Int32)) + { + return DbType.Int32; + } + else if (type == typeof (UInt32)) + { + return DbType.UInt32; + } + else if (type == typeof (Int64)) + { + return DbType.Int64; + } + else if (type == typeof (UInt64)) + { + return DbType.UInt64; + } + else if (type == typeof (Double)) + { + return DbType.Double; + } + else if (type == typeof (Boolean)) + { + return DbType.Boolean; + } + else if (type == typeof (Byte[])) + { + return DbType.Binary; + } + else + { + return DbType.String; + } + } + + /// + /// + /// a Type + /// a string + /// this is something we'll need to implement for each db slightly differently. + public static string sqliteType(Type type) + { + if (type == typeof (String)) + { + return "varchar(255)"; + } + else if (type == typeof (Int32)) + { + return "integer"; + } + else if (type == typeof (UInt32)) + { + return "integer"; + } + else if (type == typeof (Int64)) + { + return "varchar(255)"; + } + else if (type == typeof (UInt64)) + { + return "varchar(255)"; + } + else if (type == typeof (Double)) + { + return "float"; + } + else if (type == typeof (Boolean)) + { + return "integer"; + } + else if (type == typeof (Byte[])) + { + return "blob"; + } + else + { + return "string"; + } + } + } +} diff --git a/OpenSim/Data/SQLiteLegacy/SQLiteXInventoryData.cs b/OpenSim/Data/SQLiteLegacy/SQLiteXInventoryData.cs new file mode 100644 index 0000000000..5422cbf6ad --- /dev/null +++ b/OpenSim/Data/SQLiteLegacy/SQLiteXInventoryData.cs @@ -0,0 +1,155 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Data; +using System.Reflection; +using System.Collections.Generic; +using Mono.Data.SqliteClient; +using log4net; +using OpenMetaverse; +using OpenSim.Framework; + +namespace OpenSim.Data.SQLiteLegacy +{ + /// + /// A MySQL Interface for the Asset Server + /// + public class SQLiteXInventoryData : IXInventoryData + { +// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private SQLiteGenericTableHandler m_Folders; + private SqliteItemHandler m_Items; + + public SQLiteXInventoryData(string conn, string realm) + { + m_Folders = new SQLiteGenericTableHandler( + conn, "inventoryfolders", "InventoryStore"); + m_Items = new SqliteItemHandler( + conn, "inventoryitems", String.Empty); + } + + public XInventoryFolder[] GetFolders(string[] fields, string[] vals) + { + return m_Folders.Get(fields, vals); + } + + public XInventoryItem[] GetItems(string[] fields, string[] vals) + { + return m_Items.Get(fields, vals); + } + + public bool StoreFolder(XInventoryFolder folder) + { + return m_Folders.Store(folder); + } + + public bool StoreItem(XInventoryItem item) + { + return m_Items.Store(item); + } + + public bool DeleteFolders(string field, string val) + { + return m_Folders.Delete(field, val); + } + + public bool DeleteItems(string field, string val) + { + return m_Items.Delete(field, val); + } + + public bool MoveItem(string id, string newParent) + { + return m_Items.MoveItem(id, newParent); + } + + public XInventoryItem[] GetActiveGestures(UUID principalID) + { + return m_Items.GetActiveGestures(principalID); + } + + public int GetAssetPermissions(UUID principalID, UUID assetID) + { + return m_Items.GetAssetPermissions(principalID, assetID); + } + } + + public class SqliteItemHandler : SQLiteGenericTableHandler + { + public SqliteItemHandler(string c, string t, string m) : + base(c, t, m) + { + } + + public bool MoveItem(string id, string newParent) + { + SqliteCommand cmd = new SqliteCommand(); + + cmd.CommandText = String.Format("update {0} set parentFolderID = :ParentFolderID where inventoryID = :InventoryID", m_Realm); + cmd.Parameters.Add(new SqliteParameter(":ParentFolderID", newParent)); + cmd.Parameters.Add(new SqliteParameter(":InventoryID", id)); + + return ExecuteNonQuery(cmd, m_Connection) == 0 ? false : true; + } + + public XInventoryItem[] GetActiveGestures(UUID principalID) + { + SqliteCommand cmd = new SqliteCommand(); + cmd.CommandText = String.Format("select * from inventoryitems where avatarId = :uuid and assetType = :type and flags = 1", m_Realm); + + cmd.Parameters.Add(new SqliteParameter(":uuid", principalID.ToString())); + cmd.Parameters.Add(new SqliteParameter(":type", (int)AssetType.Gesture)); + + return DoQuery(cmd); + } + + public int GetAssetPermissions(UUID principalID, UUID assetID) + { + SqliteCommand cmd = new SqliteCommand(); + + cmd.CommandText = String.Format("select inventoryCurrentPermissions from inventoryitems where avatarID = :PrincipalID and assetID = :AssetID", m_Realm); + cmd.Parameters.Add(new SqliteParameter(":PrincipalID", principalID.ToString())); + cmd.Parameters.Add(new SqliteParameter(":AssetID", assetID.ToString())); + + IDataReader reader = ExecuteReader(cmd, m_Connection); + + int perms = 0; + + while (reader.Read()) + { + perms |= Convert.ToInt32(reader["inventoryCurrentPermissions"]); + } + + reader.Close(); + CloseCommand(cmd); + + return perms; + } + } +} diff --git a/OpenSim/Data/Tests/AssetTests.cs b/OpenSim/Data/Tests/AssetTests.cs new file mode 100644 index 0000000000..800b9bfba2 --- /dev/null +++ b/OpenSim/Data/Tests/AssetTests.cs @@ -0,0 +1,221 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; +using log4net.Config; +using NUnit.Framework; +using NUnit.Framework.Constraints; +using OpenMetaverse; +using OpenSim.Framework; +using System.Data.Common; +using log4net; + +#if !NUNIT25 +using NUnit.Framework.SyntaxHelpers; +#endif + +// DBMS-specific: +using MySql.Data.MySqlClient; +using OpenSim.Data.MySQL; + +using System.Data.SqlClient; +using OpenSim.Data.MSSQL; + +using Mono.Data.Sqlite; +using OpenSim.Data.SQLite; + +namespace OpenSim.Data.Tests +{ + +#if NUNIT25 + + [TestFixture(typeof(MySqlConnection), typeof(MySQLAssetData), Description="Basic Asset store tests (MySQL)")] + [TestFixture(typeof(SqlConnection), typeof(MSSQLAssetData), Description = "Basic Asset store tests (MS SQL Server)")] + [TestFixture(typeof(SqliteConnection), typeof(SQLiteAssetData), Description = "Basic Asset store tests (SQLite)")] + +#else + + [TestFixture(Description = "Asset store tests (SQLite)")] + public class SQLiteAssetTests : AssetTests + { + } + + [TestFixture(Description = "Asset store tests (MySQL)")] + public class MySqlAssetTests : AssetTests + { + } + + [TestFixture(Description = "Asset store tests (MS SQL Server)")] + public class MSSQLAssetTests : AssetTests + { + } + +#endif + + + public class AssetTests : BasicDataServiceTest + where TConn : DbConnection, new() + where TAssetData : AssetDataBase, new() + { + TAssetData m_db; + + public UUID uuid1 = UUID.Random(); + public UUID uuid2 = UUID.Random(); + public UUID uuid3 = UUID.Random(); + + public string critter1 = UUID.Random().ToString(); + public string critter2 = UUID.Random().ToString(); + public string critter3 = UUID.Random().ToString(); + + public byte[] data1 = new byte[100]; + + PropertyScrambler scrambler = new PropertyScrambler() + .DontScramble(x => x.ID) + .DontScramble(x => x.Type) + .DontScramble(x => x.FullID) + .DontScramble(x => x.Metadata.ID) + .DontScramble(x => x.Metadata.CreatorID) + .DontScramble(x => x.Metadata.ContentType) + .DontScramble(x => x.Metadata.FullID) + .DontScramble(x => x.Data); + + protected override void InitService(object service) + { + ClearDB(); + m_db = (TAssetData)service; + m_db.Initialise(m_connStr); + } + + private void ClearDB() + { + DropTables("assets"); + ResetMigrations("AssetStore"); + } + + + [Test] + public void T001_LoadEmpty() + { + Assert.That(m_db.ExistsAsset(uuid1), Is.False); + Assert.That(m_db.ExistsAsset(uuid2), Is.False); + Assert.That(m_db.ExistsAsset(uuid3), Is.False); + } + + [Test] + public void T010_StoreReadVerifyAssets() + { + AssetBase a1 = new AssetBase(uuid1, "asset one", (sbyte)AssetType.Texture, critter1.ToString()); + AssetBase a2 = new AssetBase(uuid2, "asset two", (sbyte)AssetType.Texture, critter2.ToString()); + AssetBase a3 = new AssetBase(uuid3, "asset three", (sbyte)AssetType.Texture, critter3.ToString()); + a1.Data = data1; + a2.Data = data1; + a3.Data = data1; + + scrambler.Scramble(a1); + scrambler.Scramble(a2); + scrambler.Scramble(a3); + + m_db.StoreAsset(a1); + m_db.StoreAsset(a2); + m_db.StoreAsset(a3); + + AssetBase a1a = m_db.GetAsset(uuid1); + Assert.That(a1a, Constraints.PropertyCompareConstraint(a1)); + + AssetBase a2a = m_db.GetAsset(uuid2); + Assert.That(a2a, Constraints.PropertyCompareConstraint(a2)); + + AssetBase a3a = m_db.GetAsset(uuid3); + Assert.That(a3a, Constraints.PropertyCompareConstraint(a3)); + + scrambler.Scramble(a1a); + scrambler.Scramble(a2a); + scrambler.Scramble(a3a); + + m_db.StoreAsset(a1a); + m_db.StoreAsset(a2a); + m_db.StoreAsset(a3a); + + AssetBase a1b = m_db.GetAsset(uuid1); + Assert.That(a1b, Constraints.PropertyCompareConstraint(a1a)); + + AssetBase a2b = m_db.GetAsset(uuid2); + Assert.That(a2b, Constraints.PropertyCompareConstraint(a2a)); + + AssetBase a3b = m_db.GetAsset(uuid3); + Assert.That(a3b, Constraints.PropertyCompareConstraint(a3a)); + + Assert.That(m_db.ExistsAsset(uuid1), Is.True); + Assert.That(m_db.ExistsAsset(uuid2), Is.True); + Assert.That(m_db.ExistsAsset(uuid3), Is.True); + + List metadatas = m_db.FetchAssetMetadataSet(0, 1000); + + Assert.That(metadatas.Count >= 3, "FetchAssetMetadataSet() should have returned at least 3 assets!"); + + // It is possible that the Asset table is filled with data, in which case we don't try to find "our" + // assets there: + if (metadatas.Count < 1000) + { + AssetMetadata metadata = metadatas.Find(x => x.FullID == uuid1); + Assert.That(metadata.Name, Is.EqualTo(a1b.Name)); + Assert.That(metadata.Description, Is.EqualTo(a1b.Description)); + Assert.That(metadata.Type, Is.EqualTo(a1b.Type)); + Assert.That(metadata.Temporary, Is.EqualTo(a1b.Temporary)); + Assert.That(metadata.FullID, Is.EqualTo(a1b.FullID)); + } + } + + [Test] + public void T020_CheckForWeirdCreatorID() + { + // It is expected that eventually the CreatorID might be an arbitrary string (an URI) + // rather than a valid UUID (?). This test is to make sure that the database layer does not + // attempt to convert CreatorID to GUID, but just passes it both ways as a string. + AssetBase a1 = new AssetBase(uuid1, "asset one", (sbyte)AssetType.Texture, critter1); + AssetBase a2 = new AssetBase(uuid2, "asset two", (sbyte)AssetType.Texture, "This is not a GUID!"); + AssetBase a3 = new AssetBase(uuid3, "asset three", (sbyte)AssetType.Texture, ""); + a1.Data = data1; + a2.Data = data1; + a3.Data = data1; + + m_db.StoreAsset(a1); + m_db.StoreAsset(a2); + m_db.StoreAsset(a3); + + AssetBase a1a = m_db.GetAsset(uuid1); + Assert.That(a1a, Constraints.PropertyCompareConstraint(a1)); + + AssetBase a2a = m_db.GetAsset(uuid2); + Assert.That(a2a, Constraints.PropertyCompareConstraint(a2)); + + AssetBase a3a = m_db.GetAsset(uuid3); + Assert.That(a3a, Constraints.PropertyCompareConstraint(a3)); + } + } +} diff --git a/OpenSim/Data/Tests/BasicAssetTest.cs b/OpenSim/Data/Tests/BasicAssetTest.cs deleted file mode 100644 index e80cff96b8..0000000000 --- a/OpenSim/Data/Tests/BasicAssetTest.cs +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using log4net.Config; -using NUnit.Framework; -using NUnit.Framework.SyntaxHelpers; -using OpenMetaverse; -using OpenSim.Framework; -using log4net; - -namespace OpenSim.Data.Tests -{ - public class BasicAssetTest - { - public IAssetDataPlugin db; - public UUID uuid1; - public UUID uuid2; - public UUID uuid3; - public byte[] asset1; - - public void SuperInit() - { - OpenSim.Tests.Common.TestLogging.LogToConsole(); - - uuid1 = UUID.Random(); - uuid2 = UUID.Random(); - uuid3 = UUID.Random(); - asset1 = new byte[100]; - asset1.Initialize(); - } - - [Test] - public void T001_LoadEmpty() - { - Assert.That(db.ExistsAsset(uuid1), Is.False); - Assert.That(db.ExistsAsset(uuid2), Is.False); - Assert.That(db.ExistsAsset(uuid3), Is.False); - } - - [Test] - public void T010_StoreSimpleAsset() - { - AssetBase a1 = new AssetBase(uuid1, "asset one", (sbyte)AssetType.Texture, UUID.Zero.ToString()); - AssetBase a2 = new AssetBase(uuid2, "asset two", (sbyte)AssetType.Texture, UUID.Zero.ToString()); - AssetBase a3 = new AssetBase(uuid3, "asset three", (sbyte)AssetType.Texture, UUID.Zero.ToString()); - a1.Data = asset1; - a2.Data = asset1; - a3.Data = asset1; - - PropertyScrambler scrambler = new PropertyScrambler() - .DontScramble(x => x.Data) - .DontScramble(x => x.ID) - .DontScramble(x => x.FullID) - .DontScramble(x => x.Metadata.ID) - .DontScramble(x => x.Metadata.CreatorID) - .DontScramble(x => x.Metadata.ContentType) - .DontScramble(x => x.Metadata.FullID); - - scrambler.Scramble(a1); - scrambler.Scramble(a2); - scrambler.Scramble(a3); - - - db.StoreAsset(a1); - db.StoreAsset(a2); - db.StoreAsset(a3); - - AssetBase a1a = db.GetAsset(uuid1); - Assert.That(a1a, Constraints.PropertyCompareConstraint(a1)); - - AssetBase a2a = db.GetAsset(uuid2); - Assert.That(a2a, Constraints.PropertyCompareConstraint(a2)); - - AssetBase a3a = db.GetAsset(uuid3); - Assert.That(a3a, Constraints.PropertyCompareConstraint(a3)); - - scrambler.Scramble(a1a); - scrambler.Scramble(a2a); - scrambler.Scramble(a3a); - - db.StoreAsset(a1a); - db.StoreAsset(a2a); - db.StoreAsset(a3a); - - AssetBase a1b = db.GetAsset(uuid1); - Assert.That(a1b, Constraints.PropertyCompareConstraint(a1a)); - - AssetBase a2b = db.GetAsset(uuid2); - Assert.That(a2b, Constraints.PropertyCompareConstraint(a2a)); - - AssetBase a3b = db.GetAsset(uuid3); - Assert.That(a3b, Constraints.PropertyCompareConstraint(a3a)); - - Assert.That(db.ExistsAsset(uuid1), Is.True); - Assert.That(db.ExistsAsset(uuid2), Is.True); - Assert.That(db.ExistsAsset(uuid3), Is.True); - - List metadatas = db.FetchAssetMetadataSet(0, 1000); - - AssetMetadata metadata = metadatas.Find(x => x.FullID == uuid1); - Assert.That(metadata.Name, Is.EqualTo(a1b.Name)); - Assert.That(metadata.Description, Is.EqualTo(a1b.Description)); - Assert.That(metadata.Type, Is.EqualTo(a1b.Type)); - Assert.That(metadata.Temporary, Is.EqualTo(a1b.Temporary)); - Assert.That(metadata.FullID, Is.EqualTo(a1b.FullID)); - } - } -} diff --git a/OpenSim/Data/Tests/BasicDataServiceTest.cs b/OpenSim/Data/Tests/BasicDataServiceTest.cs new file mode 100644 index 0000000000..c261126722 --- /dev/null +++ b/OpenSim/Data/Tests/BasicDataServiceTest.cs @@ -0,0 +1,234 @@ +using System; +using System.IO; +using System.Collections.Generic; +using log4net.Config; +using NUnit.Framework; +using NUnit.Framework.Constraints; +using OpenMetaverse; +using OpenSim.Framework; +using log4net; +using System.Data; +using System.Data.Common; +using System.Reflection; + +namespace OpenSim.Data.Tests +{ + /// This is a base class for testing any Data service for any DBMS. + /// Requires NUnit 2.5 or better (to support the generics). + /// + /// + /// + public class BasicDataServiceTest + where TConn : DbConnection, new() + where TService : class, new() + { + protected string m_connStr; + private TService m_service; + private string m_file; + + // TODO: Is this in the right place here? + // Later: apparently it's not, but does it matter here? +// protected static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + protected ILog m_log; // doesn't matter here that it's not static, init to correct type in instance .ctor + + public BasicDataServiceTest() + : this("") + { + } + + public BasicDataServiceTest(string conn) + { + m_connStr = !String.IsNullOrEmpty(conn) ? conn : DefaultTestConns.Get(typeof(TConn)); + + m_log = LogManager.GetLogger(this.GetType()); + OpenSim.Tests.Common.TestLogging.LogToConsole(); // TODO: Is that right? + } + + /// + /// To be overridden in derived classes. Do whatever init with the m_service, like setting the conn string to it. + /// You'd probably want to to cast the 'service' to a more specific type and store it in a member var. + /// This framework takes care of disposing it, if it's disposable. + /// + /// The service being tested + protected virtual void InitService(object service) + { + } + + [TestFixtureSetUp] + public void Init() + { + // Sorry, some SQLite-specific stuff goes here (not a big deal, as its just some file ops) + if (typeof(TConn).Name.StartsWith("Sqlite")) + { + // SQLite doesn't work on power or z linux + if (Directory.Exists("/proc/ppc64") || Directory.Exists("/proc/dasd")) + Assert.Ignore(); + + // for SQLite, if no explicit conn string is specified, use a temp file + if (String.IsNullOrEmpty(m_connStr)) + { + m_file = Path.GetTempFileName() + ".db"; + m_connStr = "URI=file:" + m_file + ",version=3"; + } + } + + if (String.IsNullOrEmpty(m_connStr)) + { + string msg = String.Format("Connection string for {0} is not defined, ignoring tests", typeof(TConn).Name); + m_log.Warn(msg); + Assert.Ignore(msg); + } + + // Try the connection, ignore tests if Open() fails + using (TConn conn = new TConn()) + { + conn.ConnectionString = m_connStr; + try + { + conn.Open(); + conn.Close(); + } + catch + { + string msg = String.Format("{0} is unable to connect to the database, ignoring tests", typeof(TConn).Name); + m_log.Warn(msg); + Assert.Ignore(msg); + } + } + + // If we manage to connect to the database with the user + // and password above it is our test database, and run + // these tests. If anything goes wrong, ignore these + // tests. + try + { + m_service = new TService(); + InitService(m_service); + } + catch (Exception e) + { + m_log.Error(e.ToString()); + Assert.Ignore(); + } + } + + [TestFixtureTearDown] + public void Cleanup() + { + if (m_service != null) + { + if( m_service is IDisposable) + ((IDisposable)m_service).Dispose(); + m_service = null; + } + + if( !String.IsNullOrEmpty(m_file) && File.Exists(m_file) ) + File.Delete(m_file); + } + + protected virtual DbConnection Connect() + { + DbConnection cnn = new TConn(); + cnn.ConnectionString = m_connStr; + cnn.Open(); + return cnn; + } + + protected virtual void ExecuteSql(string sql) + { + using (DbConnection dbcon = Connect()) + { + using (DbCommand cmd = dbcon.CreateCommand()) + { + cmd.CommandText = sql; + cmd.ExecuteNonQuery(); + } + } + } + + protected delegate bool ProcessRow(IDataReader reader); + + protected virtual int ExecQuery(string sql, bool bSingleRow, ProcessRow action) + { + int nRecs = 0; + using (DbConnection dbcon = Connect()) + { + using (DbCommand cmd = dbcon.CreateCommand()) + { + cmd.CommandText = sql; + CommandBehavior cb = bSingleRow ? CommandBehavior.SingleRow : CommandBehavior.Default; + using (DbDataReader rdr = cmd.ExecuteReader(cb)) + { + while (rdr.Read()) + { + nRecs++; + if (!action(rdr)) + break; + } + } + } + } + return nRecs; + } + + /// Drop tables (listed as parameters). There is no "DROP IF EXISTS" syntax common for all + /// databases, so we just DROP and ignore an exception. + /// + /// + protected virtual void DropTables(params string[] tables) + { + foreach (string tbl in tables) + { + try + { + ExecuteSql("DROP TABLE " + tbl + ";"); + }catch + { + } + } + } + + /// Clear tables listed as parameters (without dropping them). + /// + /// + protected virtual void ResetMigrations(params string[] stores) + { + string lst = ""; + foreach (string store in stores) + { + string s = "'" + store + "'"; + if (lst == "") + lst = s; + else + lst += ", " + s; + } + + string sCond = stores.Length > 1 ? ("in (" + lst + ")") : ("=" + lst); + try + { + ExecuteSql("DELETE FROM migrations where name " + sCond); + } + catch + { + } + } + + /// Clear tables listed as parameters (without dropping them). + /// + /// + protected virtual void ClearTables(params string[] tables) + { + foreach (string tbl in tables) + { + try + { + ExecuteSql("DELETE FROM " + tbl + ";"); + } + catch + { + } + } + } + } +} diff --git a/OpenSim/Data/Tests/DataTestUtil.cs b/OpenSim/Data/Tests/DataTestUtil.cs index d211ab3b40..5393529592 100644 --- a/OpenSim/Data/Tests/DataTestUtil.cs +++ b/OpenSim/Data/Tests/DataTestUtil.cs @@ -39,7 +39,8 @@ namespace OpenSim.Data.Tests public class DataTestUtil { public const uint UNSIGNED_INTEGER_MIN = uint.MinValue; - public const uint UNSIGNED_INTEGER_MAX = uint.MaxValue; + //public const uint UNSIGNED_INTEGER_MAX = uint.MaxValue; + public const uint UNSIGNED_INTEGER_MAX = INTEGER_MAX; public const int INTEGER_MIN = int.MinValue + 1; // Postgresql requires +1 to .NET int.MinValue public const int INTEGER_MAX = int.MaxValue; diff --git a/OpenSim/Data/Tests/DefaultTestConns.cs b/OpenSim/Data/Tests/DefaultTestConns.cs new file mode 100644 index 0000000000..7b52af575a --- /dev/null +++ b/OpenSim/Data/Tests/DefaultTestConns.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Reflection; +using System.IO; +using Nini.Config; + +namespace OpenSim.Data.Tests +{ + /// This static class looks for TestDataConnections.ini file in the /bin directory to obtain + /// a connection string for testing one of the supported databases. + /// The connections must be in the section [TestConnections] with names matching the connection class + /// name for the specific database, e.g.: + /// + /// [TestConnections] + /// MySqlConnection="..." + /// SqlConnection="..." + /// SqliteConnection="..." + /// + /// Note that the conn string may also be set explicitly in the [TestCase()] attribute of test classes + /// based on BasicDataServiceTest.cs. + /// + + static class DefaultTestConns + { + private static Dictionary conns = new Dictionary(); + + public static string Get(Type connType) + { + string sConn; + + if (conns.TryGetValue(connType, out sConn)) + return sConn; + + Assembly asm = Assembly.GetExecutingAssembly(); + string sType = connType.Name; + + // Note: when running from NUnit, the DLL is located in some temp dir, so how do we get + // to the INI file? Ok, so put it into the resources! + // string iniName = Path.Combine(Path.GetDirectoryName(asm.Location), "TestDataConnections.ini"); + + string[] allres = asm.GetManifestResourceNames(); + string sResFile = Array.Find(allres, s => s.Contains("TestDataConnections.ini")); + + if (String.IsNullOrEmpty(sResFile)) + throw new Exception(String.Format("Please add resource TestDataConnections.ini, with section [TestConnections] and settings like {0}=\"...\"", + sType)); + + using (Stream resource = asm.GetManifestResourceStream(sResFile)) + { + IConfigSource source = new IniConfigSource(resource); + var cfg = source.Configs["TestConnections"]; + sConn = cfg.Get(sType, ""); + } + + if (!String.IsNullOrEmpty(sConn)) + conns[connType] = sConn; + + return sConn; + } + } +} diff --git a/OpenSim/Data/Tests/BasicEstateTest.cs b/OpenSim/Data/Tests/EstateTests.cs similarity index 90% rename from OpenSim/Data/Tests/BasicEstateTest.cs rename to OpenSim/Data/Tests/EstateTests.cs index d14d405256..d6eed3dadd 100644 --- a/OpenSim/Data/Tests/BasicEstateTest.cs +++ b/OpenSim/Data/Tests/EstateTests.cs @@ -35,13 +35,57 @@ using OpenSim.Region.Framework.Interfaces; using System.Text; using log4net; using System.Reflection; +using System.Data.Common; + +#if !NUNIT25 +using NUnit.Framework.SyntaxHelpers; +#endif + + +// DBMS-specific: +using MySql.Data.MySqlClient; +using OpenSim.Data.MySQL; + +using System.Data.SqlClient; +using OpenSim.Data.MSSQL; + +using Mono.Data.Sqlite; +using OpenSim.Data.SQLite; + namespace OpenSim.Data.Tests { - public class BasicEstateTest + +#if NUNIT25 + + [TestFixture(typeof(MySqlConnection), typeof(MySQLEstateStore), Description = "Estate store tests (MySQL)")] + [TestFixture(typeof(SqlConnection), typeof(MSSQLEstateStore), Description = "Estate store tests (MS SQL Server)")] + [TestFixture(typeof(SqliteConnection), typeof(SQLiteEstateStore), Description = "Estate store tests (SQLite)")] + +#else + + [TestFixture(Description = "Estate store tests (SQLite)")] + public class SQLiteEstateTests : EstateTests + { + } + + [TestFixture(Description = "Estate store tests (MySQL)")] + public class MySqlEstateTests : EstateTests + { + } + + [TestFixture(Description = "Estate store tests (MS SQL Server)")] + public class MSSQLEstateTests : EstateTests + { + } + +#endif + + public class EstateTests : BasicDataServiceTest + where TConn : DbConnection, new() + where TEstateStore : class, IEstateDataStore, new() { public IEstateDataStore db; - public IRegionDataStore regionDb; public static UUID REGION_ID = new UUID("250d214e-1c7e-4f9b-a488-87c5e53feed7"); @@ -54,9 +98,25 @@ namespace OpenSim.Data.Tests public static UUID GROUP_ID_1 = new UUID("250d214e-1c7e-4f9b-a488-87c5e53feed5"); public static UUID GROUP_ID_2 = new UUID("250d214e-1c7e-4f9b-a488-87c5e53feed6"); - public void SuperInit() + protected override void InitService(object service) { - OpenSim.Tests.Common.TestLogging.LogToConsole(); + ClearDB(); + db = (IEstateDataStore)service; + db.Initialise(m_connStr); + } + + private void ClearDB() + { + // if a new table is added, it has to be dropped here + DropTables( + "estate_managers", + "estate_groups", + "estate_users", + "estateban", + "estate_settings", + "estate_map" + ); + ResetMigrations("EstateStore"); } #region 0Tests @@ -292,8 +352,7 @@ namespace OpenSim.Data.Tests // Letting estate store generate rows to database for us EstateSettings originalSettings = db.LoadEstateSettings(regionId, true); - SetEstateSettings( - originalSettings, + SetEstateSettings(originalSettings, estateName, parentEstateID, billableFactor, @@ -319,30 +378,6 @@ namespace OpenSim.Data.Tests estateOwner ); - originalSettings.EstateName = estateName; - originalSettings.ParentEstateID = parentEstateID; - originalSettings.BillableFactor = billableFactor; - originalSettings.PricePerMeter = pricePerMeter; - originalSettings.RedirectGridX = redirectGridX; - originalSettings.RedirectGridY = redirectGridY; - originalSettings.UseGlobalTime = useGlobalTime; - originalSettings.FixedSun = fixedSun; - originalSettings.SunPosition = sunPosition; - originalSettings.AllowVoice = allowVoice; - originalSettings.AllowDirectTeleport = allowDirectTeleport; - originalSettings.ResetHomeOnTeleport = resetHomeOnTeleport; - originalSettings.DenyAnonymous = denyAnonymous; - originalSettings.DenyIdentified = denyIdentified; - originalSettings.DenyTransacted = denyTransacted; - originalSettings.DenyMinors = denyMinors; - originalSettings.AbuseEmailToEstateOwner = abuseEmailToEstateOwner; - originalSettings.BlockDwell = blockDwell; - originalSettings.EstateSkipScripts = estateSkipScripts; - originalSettings.TaxFree = taxFree; - originalSettings.PublicAccess = publicAccess; - originalSettings.AbuseEmail = abuseEmail; - originalSettings.EstateOwner = estateOwner; - // Saving settings. db.StoreEstateSettings(originalSettings); @@ -350,8 +385,7 @@ namespace OpenSim.Data.Tests EstateSettings loadedSettings = db.LoadEstateSettings(regionId, true); // Checking that loaded values are correct. - ValidateEstateSettings( - loadedSettings, + ValidateEstateSettings(loadedSettings, estateName, parentEstateID, billableFactor, diff --git a/OpenSim/Data/Tests/BasicInventoryTest.cs b/OpenSim/Data/Tests/InventoryTests.cs similarity index 82% rename from OpenSim/Data/Tests/BasicInventoryTest.cs rename to OpenSim/Data/Tests/InventoryTests.cs index 900186b3b4..c22e26c3c9 100644 --- a/OpenSim/Data/Tests/BasicInventoryTest.cs +++ b/OpenSim/Data/Tests/InventoryTests.cs @@ -25,6 +25,8 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +// #define NUNIT25 + using System; using log4net.Config; using NUnit.Framework; @@ -33,62 +35,95 @@ using OpenMetaverse; using OpenSim.Framework; using log4net; using System.Reflection; +using System.Data.Common; + +#if !NUNIT25 +using NUnit.Framework.SyntaxHelpers; +#endif + +// DBMS-specific: +using MySql.Data.MySqlClient; +using OpenSim.Data.MySQL; + +using System.Data.SqlClient; +using OpenSim.Data.MSSQL; + +using Mono.Data.Sqlite; +using OpenSim.Data.SQLite; namespace OpenSim.Data.Tests { - public class BasicInventoryTest +#if NUNIT25 + + [TestFixture(typeof(SqliteConnection), typeof(SQLiteInventoryStore), Description = "Inventory store tests (SQLite)")] + [TestFixture(typeof(MySqlConnection), typeof(MySQLInventoryData), Description = "Inventory store tests (MySQL)")] + [TestFixture(typeof(SqlConnection), typeof(MSSQLInventoryData), Description = "Inventory store tests (MS SQL Server)")] + +#else + + [TestFixture(Description = "Inventory store tests (SQLite)")] + public class SQLiteInventoryTests : InventoryTests + { + } + + [TestFixture(Description = "Inventory store tests (MySQL)")] + public class MySqlInventoryTests : InventoryTests + { + } + + [TestFixture(Description = "Inventory store tests (MS SQL Server)")] + public class MSSQLInventoryTests : InventoryTests + { + } +#endif + + public class InventoryTests : BasicDataServiceTest + where TConn : DbConnection, new() + where TInvStore : class, IInventoryDataPlugin, new() { - //private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public IInventoryDataPlugin db; + public UUID zero = UUID.Zero; - public UUID folder1; - public UUID folder2; - public UUID folder3; - public UUID owner1; - public UUID owner2; - public UUID owner3; + public UUID folder1 = UUID.Random(); + public UUID folder2 = UUID.Random(); + public UUID folder3 = UUID.Random(); + public UUID owner1 = UUID.Random(); + public UUID owner2 = UUID.Random(); + public UUID owner3 = UUID.Random(); - public UUID item1; - public UUID item2; - public UUID item3; - public UUID asset1; - public UUID asset2; - public UUID asset3; + public UUID item1 = UUID.Random(); + public UUID item2 = UUID.Random(); + public UUID item3 = UUID.Random(); + public UUID asset1 = UUID.Random(); + public UUID asset2 = UUID.Random(); + public UUID asset3 = UUID.Random(); public string name1; - public string name2; - public string name3; - public string niname1; - public string iname1; - public string iname2; - public string iname3; + public string name2 = "First Level folder"; + public string name3 = "First Level folder 2"; + public string niname1 = "My Shirt"; + public string iname1 = "Shirt"; + public string iname2 = "Text Board"; + public string iname3 = "No Pants Barrel"; - public void SuperInit() + public InventoryTests(string conn) : base(conn) { - OpenSim.Tests.Common.TestLogging.LogToConsole(); - - folder1 = UUID.Random(); - folder2 = UUID.Random(); - folder3 = UUID.Random(); - owner1 = UUID.Random(); - owner2 = UUID.Random(); - owner3 = UUID.Random(); - item1 = UUID.Random(); - item2 = UUID.Random(); - item3 = UUID.Random(); - asset1 = UUID.Random(); - asset2 = UUID.Random(); - asset3 = UUID.Random(); - name1 = "Root Folder for " + owner1.ToString(); - name2 = "First Level folder"; - name3 = "First Level folder 2"; - niname1 = "My Shirt"; - iname1 = "Shirt"; - iname2 = "Text Board"; - iname3 = "No Pants Barrel"; + } + public InventoryTests() : this("") { } + protected override void InitService(object service) + { + ClearDB(); + db = (IInventoryDataPlugin)service; + db.Initialise(m_connStr); + } + + private void ClearDB() + { + DropTables("inventoryitems", "inventoryfolders"); + ResetMigrations("InventoryStore"); } [Test] @@ -159,8 +194,10 @@ namespace OpenSim.Data.Tests [Test] public void T013_FolderHierarchy() { - Assert.That(db.getFolderHierarchy(zero).Count, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(zero).Count, Is.EqualTo(0))"); - Assert.That(db.getFolderHierarchy(folder1).Count, Is.EqualTo(2), "Assert.That(db.getFolderHierarchy(folder1).Count, Is.EqualTo(2))"); + int n = db.getFolderHierarchy(zero).Count; // (for dbg - easier to see what's returned) + Assert.That(n, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(zero).Count, Is.EqualTo(0))"); + n = db.getFolderHierarchy(folder1).Count; + Assert.That(n, Is.EqualTo(2), "Assert.That(db.getFolderHierarchy(folder1).Count, Is.EqualTo(2))"); Assert.That(db.getFolderHierarchy(folder2).Count, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(folder2).Count, Is.EqualTo(0))"); Assert.That(db.getFolderHierarchy(folder3).Count, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(folder3).Count, Is.EqualTo(0))"); Assert.That(db.getFolderHierarchy(UUID.Random()).Count, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(UUID.Random()).Count, Is.EqualTo(0))"); diff --git a/OpenSim/Data/Tests/BasicRegionTest.cs b/OpenSim/Data/Tests/RegionTests.cs similarity index 91% rename from OpenSim/Data/Tests/BasicRegionTest.cs rename to OpenSim/Data/Tests/RegionTests.cs index dfbf5228ec..1f654d316b 100644 --- a/OpenSim/Data/Tests/BasicRegionTest.cs +++ b/OpenSim/Data/Tests/RegionTests.cs @@ -38,59 +38,112 @@ using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using log4net; using System.Reflection; +using System.Data.Common; + +#if !NUNIT25 +using NUnit.Framework.SyntaxHelpers; +#endif + +// DBMS-specific: +using MySql.Data.MySqlClient; +using OpenSim.Data.MySQL; + +using System.Data.SqlClient; +using OpenSim.Data.MSSQL; + +using Mono.Data.Sqlite; +using OpenSim.Data.SQLite; namespace OpenSim.Data.Tests { - public class BasicRegionTest +#if NUNIT25 + + [TestFixture(typeof(SqliteConnection), typeof(SQLiteRegionData), Description = "Region store tests (SQLite)")] + [TestFixture(typeof(MySqlConnection), typeof(MySqlRegionData), Description = "Region store tests (MySQL)")] + [TestFixture(typeof(SqlConnection), typeof(MSSQLRegionData), Description = "Region store tests (MS SQL Server)")] + +#else + + [TestFixture(Description = "Region store tests (SQLite)")] + public class SQLiteRegionTests : RegionTests { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + } + + [TestFixture(Description = "Region store tests (MySQL)")] + public class MySqlRegionTests : RegionTests + { + } + + [TestFixture(Description = "Region store tests (MS SQL Server)")] + public class MSSQLRegionTests : RegionTests + { + } + +#endif + + public class RegionTests : BasicDataServiceTest + where TConn : DbConnection, new() + where TRegStore : class, IRegionDataStore, new() + { + bool m_rebuildDB; + public IRegionDataStore db; public UUID zero = UUID.Zero; - public UUID region1; - public UUID region2; - public UUID region3; - public UUID region4; - public UUID prim1; - public UUID prim2; - public UUID prim3; - public UUID prim4; - public UUID prim5; - public UUID prim6; - public UUID item1; - public UUID item2; - public UUID item3; + public UUID region1 = UUID.Random(); + public UUID region2 = UUID.Random(); + public UUID region3 = UUID.Random(); + public UUID region4 = UUID.Random(); + public UUID prim1 = UUID.Random(); + public UUID prim2 = UUID.Random(); + public UUID prim3 = UUID.Random(); + public UUID prim4 = UUID.Random(); + public UUID prim5 = UUID.Random(); + public UUID prim6 = UUID.Random(); + public UUID item1 = UUID.Random(); + public UUID item2 = UUID.Random(); + public UUID item3 = UUID.Random(); - public static Random random; + public static Random random = new Random(); public string itemname1 = "item1"; - public uint localID; - - public double height1; - public double height2; + public uint localID = 1; - public void SuperInit() + public double height1 = 20; + public double height2 = 100; + + public RegionTests(string conn, bool rebuild) + : base(conn) { - OpenSim.Tests.Common.TestLogging.LogToConsole(); - - region1 = UUID.Random(); - region3 = UUID.Random(); - region4 = UUID.Random(); - prim1 = UUID.Random(); - prim2 = UUID.Random(); - prim3 = UUID.Random(); - prim4 = UUID.Random(); - prim5 = UUID.Random(); - prim6 = UUID.Random(); - item1 = UUID.Random(); - item2 = UUID.Random(); - item3 = UUID.Random(); - random = new Random(); - localID = 1; - height1 = 20; - height2 = 100; + m_rebuildDB = rebuild; } + public RegionTests() : this("", true) { } + public RegionTests(string conn) : this(conn, true) {} + public RegionTests(bool rebuild): this("", rebuild) {} + + + protected override void InitService(object service) + { + ClearDB(); + db = (IRegionDataStore)service; + db.Initialise(m_connStr); + } + + private void ClearDB() + { + string[] reg_tables = new string[] { + "prims", "primshapes", "primitems", "terrain", "land", "landaccesslist", "regionban", "regionsettings" + }; + if (m_rebuildDB) + { + DropTables(reg_tables); + ResetMigrations("RegionStore"); + }else + ClearTables(reg_tables); + } + + // Test Plan // Prims // - empty test - 001 @@ -580,68 +633,88 @@ namespace OpenSim.Data.Tests .IgnoreProperty(x=>x.PassCollision) .IgnoreProperty(x=>x.RootPart)); } + + + private SceneObjectGroup GetMySOG(string name) + { + SceneObjectGroup sog = FindSOG(name, region1); + if (sog == null) + { + sog = NewSOG(name, prim1, region1); + db.StoreObject(sog, region1); + } + return sog; + } + + // NOTE: it is a bad practice to rely on some of the previous tests having been run before. + // If the tests are run manually, one at a time, each starts with full class init (DB cleared). + // Even when all tests are run, NUnit 2.5+ no longer guarantee a specific test order. + // We shouldn't expect to find anything in the DB if we haven't put it there *in the same test*! + [Test] public void T020_PrimInventoryEmpty() { - SceneObjectGroup sog = FindSOG("object1", region1); + SceneObjectGroup sog = GetMySOG("object1"); TaskInventoryItem t = sog.GetInventoryItem(sog.RootPart.LocalId, item1); Assert.That(t, Is.Null); } - [Test] - public void T021_PrimInventoryStore() + // TODO: Is there any point to call StorePrimInventory on a list, rather than on the prim itself? + + private void StoreInventory(SceneObjectGroup sog) { - SceneObjectGroup sog = FindSOG("object1", region1); + List list = new List(); + // TODO: seriously??? this is the way we need to loop to get this? + foreach (UUID uuid in sog.RootPart.Inventory.GetInventoryList()) + { + list.Add(sog.GetInventoryItem(sog.RootPart.LocalId, uuid)); + } + + db.StorePrimInventory(sog.RootPart.UUID, list); + } + + + [Test] + public void T021_PrimInventoryBasic() + { + SceneObjectGroup sog = GetMySOG("object1"); InventoryItemBase i = NewItem(item1, zero, zero, itemname1, zero); Assert.That(sog.AddInventoryItem(null, sog.RootPart.LocalId, i, zero), Is.True); TaskInventoryItem t = sog.GetInventoryItem(sog.RootPart.LocalId, item1); Assert.That(t.Name, Is.EqualTo(itemname1), "Assert.That(t.Name, Is.EqualTo(itemname1))"); - // TODO: seriously??? this is the way we need to loop to get this? + StoreInventory(sog); - List list = new List(); - foreach (UUID uuid in sog.RootPart.Inventory.GetInventoryList()) - { - list.Add(sog.GetInventoryItem(sog.RootPart.LocalId, uuid)); - } - - db.StorePrimInventory(prim1, list); - } + SceneObjectGroup sog1 = FindSOG("object1", region1); + Assert.That(sog1, Is.Not.Null); - [Test] - public void T022_PrimInventoryRetrieve() - { - SceneObjectGroup sog = FindSOG("object1", region1); - TaskInventoryItem t = sog.GetInventoryItem(sog.RootPart.LocalId, item1); + TaskInventoryItem t1 = sog1.GetInventoryItem(sog1.RootPart.LocalId, item1); + Assert.That(t1, Is.Not.Null); + Assert.That(t1.Name, Is.EqualTo(itemname1), "Assert.That(t.Name, Is.EqualTo(itemname1))"); - Assert.That(t.Name, Is.EqualTo(itemname1), "Assert.That(t.Name, Is.EqualTo(itemname1))"); - } - - [Test] - public void T023_PrimInventoryUpdate() - { - SceneObjectGroup sog = FindSOG("object1", region1); - TaskInventoryItem t = sog.GetInventoryItem(sog.RootPart.LocalId, item1); - - t.Name = "My New Name"; - sog.UpdateInventoryItem(t); + // Updating inventory + t1.Name = "My New Name"; + sog1.UpdateInventoryItem(t1); - Assert.That(t.Name, Is.EqualTo("My New Name"), "Assert.That(t.Name, Is.EqualTo(\"My New Name\"))"); + StoreInventory(sog1); - } + SceneObjectGroup sog2 = FindSOG("object1", region1); + TaskInventoryItem t2 = sog2.GetInventoryItem(sog2.RootPart.LocalId, item1); + Assert.That(t2.Name, Is.EqualTo("My New Name"), "Assert.That(t.Name, Is.EqualTo(\"My New Name\"))"); + + // Removing inventory - [Test] - public void T024_PrimInventoryRemove() - { List list = new List(); db.StorePrimInventory(prim1, list); - SceneObjectGroup sog = FindSOG("object1", region1); - TaskInventoryItem t = sog.GetInventoryItem(sog.RootPart.LocalId, item1); + sog = FindSOG("object1", region1); + t = sog.GetInventoryItem(sog.RootPart.LocalId, item1); Assert.That(t, Is.Null); + } + [Test] public void T025_PrimInventoryPersistency() @@ -685,7 +758,7 @@ namespace OpenSim.Data.Tests int creationd = random.Next(); i.CreationDate = creationd; - SceneObjectGroup sog = FindSOG("object1", region1); + SceneObjectGroup sog = GetMySOG("object1"); Assert.That(sog.AddInventoryItem(null, sog.RootPart.LocalId, i, zero), Is.True); TaskInventoryItem t = sog.GetInventoryItem(sog.RootPart.LocalId, id); diff --git a/OpenSim/Data/Tests/Resources/TestDataConnections.ini b/OpenSim/Data/Tests/Resources/TestDataConnections.ini new file mode 100644 index 0000000000..5e68ab0ac1 --- /dev/null +++ b/OpenSim/Data/Tests/Resources/TestDataConnections.ini @@ -0,0 +1,24 @@ +; The default connections to the test databases. Used by all data tests based on BasicDataServiceTest.cs. +; This is read by code in DefaultTestConns.cs. + +; NOTE that this INI file is currently loaded as a embedded RESOURCE, which is weird and has a +; disadvantage of having to rebuild the Tests whenever the conn strings are changed. +; The only reason is that I couldn't figure out a reliable way to put this INI into the correct +; dir at runtime. If somebody can do it, that would be cool. + +; I'm using a local MSDE server for testing. Obviously, you'll have to modify +; the conn string to whatever MS SQL server is available to you. + +; If any of the conn strings is commented out, emty or not valid on your system, +; the relevant tests will be ignored, rather than fail. + +; As to SQLite, if the conn string here is empty, it will work anyway using a temporary +; file for the DB. If you want the resulting DB to persist (e.g. for performance testing, +; when filling up the tables can take a long time), explicitly specify a conn string like this: + +; SqliteConnection="URI=file:,version=3" + +[TestConnections] +MySqlConnection="Server=localhost;Port=3306;Database=opensim-nunit;User ID=opensim-nunit;Password=opensim-nunit;" +SqlConnection="Server=.\SQL2008;Database=opensim-nunit;Trusted_Connection=True;" +SqliteConnection="" \ No newline at end of file diff --git a/OpenSim/Framework/AgentCircuitData.cs b/OpenSim/Framework/AgentCircuitData.cs index 353e5bf96d..783a8337a5 100644 --- a/OpenSim/Framework/AgentCircuitData.cs +++ b/OpenSim/Framework/AgentCircuitData.cs @@ -107,6 +107,11 @@ namespace OpenSim.Framework /// public string ServiceSessionID = string.Empty; + /// + /// Viewer's version string + /// + public string Viewer; + /// /// Position the Agent's Avatar starts in the region /// @@ -136,6 +141,7 @@ namespace OpenSim.Framework BaseFolder = new UUID(cAgent.BaseFolder); CapsPath = cAgent.CapsPath; ChildrenCapSeeds = cAgent.ChildrenCapSeeds; + Viewer = cAgent.Viewer; } /// @@ -173,6 +179,7 @@ namespace OpenSim.Framework args["service_session_id"] = OSD.FromString(ServiceSessionID); args["start_pos"] = OSD.FromString(startpos.ToString()); args["appearance_serial"] = OSD.FromInteger(Appearance.Serial); + args["viewer"] = OSD.FromString(Viewer); if (Appearance != null) { @@ -272,6 +279,8 @@ namespace OpenSim.Framework SessionID = args["session_id"].AsUUID(); if (args["service_session_id"] != null) ServiceSessionID = args["service_session_id"].AsString(); + if (args["viewer"] != null) + Viewer = args["viewer"].AsString(); if (args["start_pos"] != null) Vector3.TryParse(args["start_pos"].AsString(), out startpos); @@ -339,6 +348,7 @@ namespace OpenSim.Framework public float startposx; public float startposy; public float startposz; + public string Viewer; public sAgentCircuitData() { @@ -360,6 +370,7 @@ namespace OpenSim.Framework BaseFolder = cAgent.BaseFolder.Guid; CapsPath = cAgent.CapsPath; ChildrenCapSeeds = cAgent.ChildrenCapSeeds; + Viewer = cAgent.Viewer; } } } diff --git a/OpenSim/Framework/AgentCircuitManager.cs b/OpenSim/Framework/AgentCircuitManager.cs index e5dbb5a81a..1ce8c34079 100644 --- a/OpenSim/Framework/AgentCircuitManager.cs +++ b/OpenSim/Framework/AgentCircuitManager.cs @@ -36,6 +36,7 @@ namespace OpenSim.Framework public class AgentCircuitManager { public Dictionary AgentCircuits = new Dictionary(); + public Dictionary AgentCircuitsByUUID = new Dictionary(); public virtual AuthenticateResponse AuthenticateSession(UUID sessionID, UUID agentID, uint circuitcode) { @@ -86,10 +87,12 @@ namespace OpenSim.Framework if (AgentCircuits.ContainsKey(circuitCode)) { AgentCircuits[circuitCode] = agentData; + AgentCircuitsByUUID[agentData.AgentID] = agentData; } else { AgentCircuits.Add(circuitCode, agentData); + AgentCircuitsByUUID[agentData.AgentID] = agentData; } } } @@ -99,10 +102,26 @@ namespace OpenSim.Framework lock (AgentCircuits) { if (AgentCircuits.ContainsKey(circuitCode)) + { + UUID agentID = AgentCircuits[circuitCode].AgentID; AgentCircuits.Remove(circuitCode); + AgentCircuitsByUUID.Remove(agentID); + } } } + public virtual void RemoveCircuit(UUID agentID) + { + lock (AgentCircuits) + { + if (AgentCircuitsByUUID.ContainsKey(agentID)) + { + uint circuitCode = AgentCircuitsByUUID[agentID].circuitcode; + AgentCircuits.Remove(circuitCode); + AgentCircuitsByUUID.Remove(agentID); + } + } + } public AgentCircuitData GetAgentCircuitData(uint circuitCode) { AgentCircuitData agentCircuit = null; @@ -110,6 +129,13 @@ namespace OpenSim.Framework return agentCircuit; } + public AgentCircuitData GetAgentCircuitData(UUID agentID) + { + AgentCircuitData agentCircuit = null; + AgentCircuitsByUUID.TryGetValue(agentID, out agentCircuit); + return agentCircuit; + } + public void UpdateAgentData(AgentCircuitData agentData) { if (AgentCircuits.ContainsKey((uint) agentData.circuitcode)) diff --git a/OpenSim/Framework/AssetBase.cs b/OpenSim/Framework/AssetBase.cs index 19ca232208..53d28be088 100644 --- a/OpenSim/Framework/AssetBase.cs +++ b/OpenSim/Framework/AssetBase.cs @@ -33,6 +33,15 @@ using OpenMetaverse; namespace OpenSim.Framework { + [Flags] + public enum AssetFlags : int + { + Normal = 0, // Immutable asset + Maptile = 1, // What it says + Rewritable = 2, // Content can be rewritten + Collectable = 4 // Can be GC'ed after some time + } + /// /// Asset class. All Assets are reference by this class or a class derived from this class /// @@ -206,6 +215,12 @@ namespace OpenSim.Framework set { m_metadata.Temporary = value; } } + public AssetFlags Flags + { + get { return m_metadata.Flags; } + set { m_metadata.Flags = value; } + } + [XmlIgnore] public AssetMetadata Metadata { @@ -233,6 +248,7 @@ namespace OpenSim.Framework private bool m_local; private bool m_temporary; private string m_creatorid; + private AssetFlags m_flags; public UUID FullID { @@ -330,5 +346,11 @@ namespace OpenSim.Framework get { return m_creatorid; } set { m_creatorid = value; } } + + public AssetFlags Flags + { + get { return m_flags; } + set { m_flags = value; } + } } } diff --git a/OpenSim/Framework/Capabilities/Caps.cs b/OpenSim/Framework/Capabilities/Caps.cs index b27d0112af..62a1e17f50 100644 --- a/OpenSim/Framework/Capabilities/Caps.cs +++ b/OpenSim/Framework/Capabilities/Caps.cs @@ -99,6 +99,7 @@ namespace OpenSim.Framework.Capabilities // private static readonly string m_remoteParcelRequestPath = "0009/";// This is in the LandManagementModule. //private string eventQueue = "0100/"; + private IScene m_Scene; private IHttpServer m_httpListener; private UUID m_agentID; private IAssetService m_assetCache; @@ -130,9 +131,10 @@ namespace OpenSim.Framework.Capabilities public FetchInventoryDescendentsCAPS CAPSFetchInventoryDescendents = null; public GetClientDelegate GetClient = null; - public Caps(IAssetService assetCache, IHttpServer httpServer, string httpListen, uint httpPort, string capsPath, + public Caps(IScene scene, IAssetService assetCache, IHttpServer httpServer, string httpListen, uint httpPort, string capsPath, UUID agent, bool dumpAssetsToFile, string regionName) { + m_Scene = scene; m_assetCache = assetCache; m_capsObjectPath = capsPath; m_httpListener = httpServer; @@ -278,7 +280,13 @@ namespace OpenSim.Framework.Capabilities public string CapsRequest(string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { - //m_log.Debug("[CAPS]: Seed Caps Request in region: " + m_regionName); + m_log.Debug("[CAPS]: Seed Caps Request in region: " + m_regionName); + + if (!m_Scene.CheckClient(m_agentID, httpRequest.RemoteIPEndPoint)) + { + m_log.DebugFormat("[CAPS]: Unauthorized CAPS client"); + return string.Empty; + } string result = LLSDHelpers.SerialiseLLSDReply(m_capsHandlers.CapsDetails); diff --git a/OpenSim/Framework/Console/CommandConsole.cs b/OpenSim/Framework/Console/CommandConsole.cs index 66f483cf22..b17dbc08de 100644 --- a/OpenSim/Framework/Console/CommandConsole.cs +++ b/OpenSim/Framework/Console/CommandConsole.cs @@ -141,7 +141,17 @@ namespace OpenSim.Framework.Console CommandInfo commandInfo = (CommandInfo)dict[String.Empty]; help.Add(commandInfo.help_text); help.Add(commandInfo.long_help); + + string descriptiveHelp = commandInfo.descriptive_help; + + // If we do have some descriptive help then insert a spacing line before and after for readability. + if (descriptiveHelp != string.Empty) + help.Add(string.Empty); + help.Add(commandInfo.descriptive_help); + + if (descriptiveHelp != string.Empty) + help.Add(string.Empty); } else { @@ -182,8 +192,7 @@ namespace OpenSim.Framework.Console public void AddCommand(string module, bool shared, string command, string help, string longhelp, CommandDelegate fn) { - AddCommand(module, shared, command, help, longhelp, - String.Empty, fn); + AddCommand(module, shared, command, help, longhelp, String.Empty, fn); } /// diff --git a/OpenSim/Framework/Console/MockConsole.cs b/OpenSim/Framework/Console/MockConsole.cs new file mode 100644 index 0000000000..9eb197750d --- /dev/null +++ b/OpenSim/Framework/Console/MockConsole.cs @@ -0,0 +1,37 @@ +using System; +using System.Threading; +using System.Collections.Generic; +using System.Text; + +namespace OpenSim.Framework.Console +{ + /// + /// This is a Fake console that's used when setting up the Scene in Unit Tests + /// Don't use this except for Unit Testing or you're in for a world of hurt when the + /// sim gets to ReadLine + /// + public class MockConsole : CommandConsole + { + public MockConsole(string defaultPrompt) : base(defaultPrompt) + { + } + public override void Output(string text) + { + } + public override void Output(string text, string level) + { + } + + public override string ReadLine(string p, bool isCommand, bool e) + { + //Thread.CurrentThread.Join(1000); + return string.Empty; + } + public override void UnlockOutput() + { + } + public override void LockOutput() + { + } + } +} diff --git a/OpenSim/Framework/Console/OpenSimAppender.cs b/OpenSim/Framework/Console/OpenSimAppender.cs index cd95506d29..72a251e9b1 100644 --- a/OpenSim/Framework/Console/OpenSimAppender.cs +++ b/OpenSim/Framework/Console/OpenSimAppender.cs @@ -66,7 +66,10 @@ namespace OpenSim.Framework.Console } else { - System.Console.Write(loggingMessage); + if (!loggingMessage.EndsWith("\n")) + System.Console.WriteLine(loggingMessage); + else + System.Console.Write(loggingMessage); } } catch (Exception e) diff --git a/OpenSim/Framework/IClientAPI.cs b/OpenSim/Framework/IClientAPI.cs index 95cd4984b0..21a2bf589e 100644 --- a/OpenSim/Framework/IClientAPI.cs +++ b/OpenSim/Framework/IClientAPI.cs @@ -75,7 +75,7 @@ namespace OpenSim.Framework public delegate void LinkObjects(IClientAPI remoteClient, uint parent, List children); - public delegate void DelinkObjects(List primIds); + public delegate void DelinkObjects(List primIds, IClientAPI client); public delegate void RequestMapBlocks(IClientAPI remoteClient, int minX, int minY, int maxX, int maxY, uint flag); @@ -461,8 +461,6 @@ namespace OpenSim.Framework public delegate void PlacesQuery(UUID QueryID, UUID TransactionID, string QueryText, uint QueryFlags, byte Category, string SimName, IClientAPI client); public delegate void AgentFOV(IClientAPI client, float verticalAngle); - - public delegate double UpdatePriorityHandler(UpdatePriorityData data); public delegate void MuteListEntryUpdate(IClientAPI client, UUID MuteID, string Name, int Flags,UUID AgentID); @@ -574,228 +572,58 @@ namespace OpenSim.Framework public float dwell; } - public struct SendAvatarData + public class EntityUpdate { - public readonly ulong RegionHandle; - public readonly string FirstName; - public readonly string LastName; - public readonly string GroupTitle; - public readonly UUID AvatarID; - public readonly uint AvatarLocalID; - public readonly Vector3 Position; - public readonly byte[] TextureEntry; - public readonly uint ParentID; - public readonly Quaternion Rotation; + public ISceneEntity Entity; + public PrimUpdateFlags Flags; - public SendAvatarData(ulong regionHandle, string firstName, string lastName, string groupTitle, UUID avatarID, - uint avatarLocalID, Vector3 position, byte[] textureEntry, uint parentID, Quaternion rotation) + public EntityUpdate(ISceneEntity entity, PrimUpdateFlags flags) { - RegionHandle = regionHandle; - FirstName = firstName; - LastName = lastName; - GroupTitle = groupTitle; - AvatarID = avatarID; - AvatarLocalID = avatarLocalID; - Position = position; - TextureEntry = textureEntry; - ParentID = parentID; - Rotation = rotation; + Entity = entity; + Flags = flags; } } - public struct SendAvatarTerseData - { - public readonly ulong RegionHandle; - public readonly ushort TimeDilation; - public readonly uint LocalID; - public readonly Vector3 Position; - public readonly Vector3 Velocity; - public readonly Vector3 Acceleration; - public readonly Quaternion Rotation; - public readonly Vector4 CollisionPlane; - public readonly UUID AgentID; - public readonly byte[] TextureEntry; - public readonly double Priority; - - public SendAvatarTerseData(ulong regionHandle, ushort timeDilation, uint localID, Vector3 position, Vector3 velocity, - Vector3 acceleration, Quaternion rotation, Vector4 collisionPlane, UUID agentid, byte[] textureEntry, double priority) - { - RegionHandle = regionHandle; - TimeDilation = timeDilation; - LocalID = localID; - Position = position; - Velocity = velocity; - Acceleration = acceleration; - Rotation = rotation; - CollisionPlane = collisionPlane; - AgentID = agentid; - TextureEntry = textureEntry; - Priority = priority; - } - } - - public struct SendPrimitiveTerseData - { - public readonly ulong RegionHandle; - public readonly ushort TimeDilation; - public readonly uint LocalID; - public readonly Vector3 Position; - public readonly Quaternion Rotation; - public readonly Vector3 Velocity; - public readonly Vector3 Acceleration; - public readonly Vector3 AngularVelocity; - public readonly UUID AssetID; - public readonly UUID OwnerID; - public readonly int AttachPoint; - public readonly byte[] TextureEntry; - public readonly double Priority; - - public SendPrimitiveTerseData(ulong regionHandle, ushort timeDilation, uint localID, Vector3 position, - Quaternion rotation, Vector3 velocity, Vector3 acceleration, Vector3 rotationalvelocity, - UUID assetID, UUID ownerID, int attachPoint, byte[] textureEntry, double priority) - { - RegionHandle = regionHandle; - TimeDilation = timeDilation; - LocalID = localID; - Position = position; - Rotation = rotation; - Velocity = velocity; - Acceleration = acceleration; - AngularVelocity = rotationalvelocity; - AssetID = assetID; - OwnerID = ownerID; - AttachPoint = attachPoint; - TextureEntry = textureEntry; - Priority = priority; - } - } - - public struct SendPrimitiveData - { - private ulong m_regionHandle; - private ushort m_timeDilation; - private uint m_localID; - private PrimitiveBaseShape m_primShape; - private Vector3 m_pos; - private Vector3 m_vel; - private Vector3 m_acc; - private Quaternion m_rotation; - private Vector3 m_rvel; - private PrimFlags m_flags; - private UUID m_objectID; - private UUID m_ownerID; - private string m_text; - private byte[] m_color; - private uint m_parentID; - private byte[] m_particleSystem; - private byte m_clickAction; - private byte m_material; - private byte[] m_textureanim; - private bool m_attachment; - private uint m_AttachPoint; - private UUID m_AssetId; - private UUID m_SoundId; - private double m_SoundVolume; - private byte m_SoundFlags; - private double m_SoundRadius; - private double m_priority; - - public SendPrimitiveData(ulong regionHandle, ushort timeDilation, uint localID, PrimitiveBaseShape primShape, - Vector3 pos, Vector3 vel, Vector3 acc, Quaternion rotation, Vector3 rvel, - uint flags, UUID objectID, UUID ownerID, string text, byte[] color, - uint parentID, byte[] particleSystem, byte clickAction, byte material, double priority) : - this(regionHandle, timeDilation, localID, primShape, pos, vel, acc, rotation, rvel, flags, objectID, - ownerID, text, color, parentID, particleSystem, clickAction, material, new byte[0], false, 0, UUID.Zero, - UUID.Zero, 0, 0, 0, priority) { } - - public SendPrimitiveData(ulong regionHandle, ushort timeDilation, uint localID, PrimitiveBaseShape primShape, - Vector3 pos, Vector3 vel, Vector3 acc, Quaternion rotation, Vector3 rvel, - uint flags, - UUID objectID, UUID ownerID, string text, byte[] color, uint parentID, - byte[] particleSystem, - byte clickAction, byte material, byte[] textureanim, bool attachment, - uint AttachPoint, UUID AssetId, UUID SoundId, double SoundVolume, byte SoundFlags, - double SoundRadius, double priority) - { - this.m_regionHandle = regionHandle; - this.m_timeDilation = timeDilation; - this.m_localID = localID; - this.m_primShape = primShape; - this.m_pos = pos; - this.m_vel = vel; - this.m_acc = acc; - this.m_rotation = rotation; - this.m_rvel = rvel; - this.m_flags = (PrimFlags)flags; - this.m_objectID = objectID; - this.m_ownerID = ownerID; - this.m_text = text; - this.m_color = color; - this.m_parentID = parentID; - this.m_particleSystem = particleSystem; - this.m_clickAction = clickAction; - this.m_material = material; - this.m_textureanim = textureanim; - this.m_attachment = attachment; - this.m_AttachPoint = AttachPoint; - this.m_AssetId = AssetId; - this.m_SoundId = SoundId; - this.m_SoundVolume = SoundVolume; - this.m_SoundFlags = SoundFlags; - this.m_SoundRadius = SoundRadius; - this.m_priority = priority; - } - - public ulong regionHandle { get { return this.m_regionHandle; } } - public ushort timeDilation { get { return this.m_timeDilation; } } - public uint localID { get { return this.m_localID; } } - public PrimitiveBaseShape primShape { get { return this.m_primShape; } } - public Vector3 pos { get { return this.m_pos; } } - public Vector3 vel { get { return this.m_vel; } } - public Vector3 acc { get { return this.m_acc; } } - public Quaternion rotation { get { return this.m_rotation; } } - public Vector3 rvel { get { return this.m_rvel; } } - public PrimFlags flags { get { return this.m_flags; } } - public UUID objectID { get { return this.m_objectID; } } - public UUID ownerID { get { return this.m_ownerID; } } - public string text { get { return this.m_text; } } - public byte[] color { get { return this.m_color; } } - public uint parentID { get { return this.m_parentID; } } - public byte[] particleSystem { get { return this.m_particleSystem; } } - public byte clickAction { get { return this.m_clickAction; } } - public byte material { get { return this.m_material; } } - public byte[] textureanim { get { return this.m_textureanim; } } - public bool attachment { get { return this.m_attachment; } } - public uint AttachPoint { get { return this.m_AttachPoint; } } - public UUID AssetId { get { return this.m_AssetId; } } - public UUID SoundId { get { return this.m_SoundId; } } - public double SoundVolume { get { return this.m_SoundVolume; } } - public byte SoundFlags { get { return this.m_SoundFlags; } } - public double SoundRadius { get { return this.m_SoundRadius; } } - public double priority { get { return this.m_priority; } } - } - - public struct UpdatePriorityData { - private double m_priority; - private uint m_localID; - - public UpdatePriorityData(double priority, uint localID) { - this.m_priority = priority; - this.m_localID = localID; - } - - public double priority { get { return this.m_priority; } } - public uint localID { get { return this.m_localID; } } - } - + /// + /// Specifies the fields that have been changed when sending a prim or + /// avatar update + /// [Flags] - public enum StateUpdateTypes + public enum PrimUpdateFlags : uint { None = 0, - AvatarTerse = 1, - PrimitiveTerse = AvatarTerse << 1, - PrimitiveFull = PrimitiveTerse << 1, - All = AvatarTerse | PrimitiveTerse | PrimitiveFull, + AttachmentPoint = 1 << 0, + Material = 1 << 1, + ClickAction = 1 << 2, + Scale = 1 << 3, + ParentID = 1 << 4, + PrimFlags = 1 << 5, + PrimData = 1 << 6, + MediaURL = 1 << 7, + ScratchPad = 1 << 8, + Textures = 1 << 9, + TextureAnim = 1 << 10, + NameValue = 1 << 11, + Position = 1 << 12, + Rotation = 1 << 13, + Velocity = 1 << 14, + Acceleration = 1 << 15, + AngularVelocity = 1 << 16, + CollisionPlane = 1 << 17, + Text = 1 << 18, + Particles = 1 << 19, + ExtraData = 1 << 20, + Sound = 1 << 21, + Joint = 1 << 22, + FullUpdate = UInt32.MaxValue + } + + public static class PrimUpdateFlagsExtensions + { + public static bool HasFlag(this PrimUpdateFlags updateFlags, PrimUpdateFlags flag) + { + return (updateFlags & flag) == flag; + } } public interface IClientAPI @@ -1161,6 +989,7 @@ namespace OpenSim.Framework void SendInstantMessage(GridInstantMessage im); + void SendGenericMessage(string method, List message); void SendGenericMessage(string method, List message); void SendLayerData(float[] map); @@ -1192,27 +1021,20 @@ namespace OpenSim.Framework void SendMoneyBalance(UUID transaction, bool success, byte[] description, int balance); void SendPayPrice(UUID objectID, int[] payPrice); - void SendAvatarData(SendAvatarData data); - - void SendAvatarTerseUpdate(SendAvatarTerseData data); - void SendCoarseLocationUpdate(List users, List CoarseLocations); void AttachObject(uint localID, Quaternion rotation, byte attachPoint, UUID ownerID); void SetChildAgentThrottle(byte[] throttle); - void SendPrimitiveToClient(SendPrimitiveData data); - - void SendPrimTerseUpdate(SendPrimitiveTerseData data); - - void ReprioritizeUpdates(StateUpdateTypes type, UpdatePriorityHandler handler); + void SendAvatarDataImmediate(ISceneEntity avatar); + void SendPrimUpdate(ISceneEntity entity, PrimUpdateFlags updateFlags); + void ReprioritizeUpdates(); + void FlushPrimUpdates(); void SendInventoryFolderDetails(UUID ownerID, UUID folderID, List items, List folders, int version, bool fetchFolders, bool fetchItems); - void FlushPrimUpdates(); - void SendInventoryItemDetails(UUID ownerID, InventoryItemBase item); /// diff --git a/OpenSim/Framework/IScene.cs b/OpenSim/Framework/IScene.cs index 19ab409098..6798b7be8a 100644 --- a/OpenSim/Framework/IScene.cs +++ b/OpenSim/Framework/IScene.cs @@ -102,5 +102,7 @@ namespace OpenSim.Framework void AddCommand(object module, string command, string shorthelp, string longhelp, CommandDelegate callback); ISceneObject DeserializeObject(string representation); + + bool CheckClient(UUID agentID, System.Net.IPEndPoint ep); } } diff --git a/OpenSim/Framework/Servers/MessageServerInfo.cs b/OpenSim/Framework/ISceneEntity.cs similarity index 80% rename from OpenSim/Framework/Servers/MessageServerInfo.cs rename to OpenSim/Framework/ISceneEntity.cs index 57ceb7184c..5ac364f994 100644 --- a/OpenSim/Framework/Servers/MessageServerInfo.cs +++ b/OpenSim/Framework/ISceneEntity.cs @@ -1,4 +1,4 @@ -/* +/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * @@ -25,24 +25,14 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -using System.Collections.Generic; +using OpenMetaverse; -namespace OpenSim.Framework.Servers +namespace OpenSim.Framework { - public class MessageServerInfo + public interface ISceneEntity { - public string URI; - public string sendkey; - public string recvkey; - public List responsibleForRegions; - - public MessageServerInfo() - { - } - - public override string ToString() - { - return URI; - } + UUID UUID { get; } + uint LocalId { get; } + Vector3 AbsolutePosition { get; } } } diff --git a/OpenSim/Framework/Lazy.cs b/OpenSim/Framework/Lazy.cs new file mode 100644 index 0000000000..8a417ac64b --- /dev/null +++ b/OpenSim/Framework/Lazy.cs @@ -0,0 +1,236 @@ +// +// Lazy.cs +// +// Authors: +// Zoltan Varga (vargaz@gmail.com) +// Marek Safar (marek.safar@gmail.com) +// +// Copyright (C) 2009 Novell +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// + +using System; +using System.Runtime.Serialization; +using System.Runtime.InteropServices; +using System.Security.Permissions; +using System.Threading; +using System.Diagnostics; + +namespace OpenSim.Framework +{ + public enum LazyThreadSafetyMode + { + None, + PublicationOnly, + ExecutionAndPublication + } + + [SerializableAttribute] + [ComVisibleAttribute(false)] + [HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)] + public class Lazy + { + T value; + bool inited; + LazyThreadSafetyMode mode; + Func factory; + object monitor; + Exception exception; + + public Lazy() + : this(LazyThreadSafetyMode.ExecutionAndPublication) + { + } + + public Lazy(Func valueFactory) + : this(valueFactory, LazyThreadSafetyMode.ExecutionAndPublication) + { + } + + public Lazy(bool isThreadSafe) + : this(() => Activator.CreateInstance(), isThreadSafe ? LazyThreadSafetyMode.ExecutionAndPublication : LazyThreadSafetyMode.None) + { + } + + public Lazy(Func valueFactory, bool isThreadSafe) + : this(valueFactory, isThreadSafe ? LazyThreadSafetyMode.ExecutionAndPublication : LazyThreadSafetyMode.None) + { + } + + public Lazy(LazyThreadSafetyMode mode) + : this(() => Activator.CreateInstance(), mode) + { + } + + public Lazy(Func valueFactory, LazyThreadSafetyMode mode) + { + if (valueFactory == null) + throw new ArgumentNullException("valueFactory"); + this.factory = valueFactory; + if (mode != LazyThreadSafetyMode.None) + monitor = new object(); + this.mode = mode; + } + + // Don't trigger expensive initialization + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + public T Value + { + get + { + if (inited) + return value; + if (exception != null) + throw exception; + + return InitValue(); + } + } + + T InitValue() + { + switch (mode) + { + case LazyThreadSafetyMode.None: + { + var init_factory = factory; + if (init_factory == null) + throw exception = new InvalidOperationException("The initialization function tries to access Value on this instance"); + try + { + factory = null; + T v = init_factory(); + value = v; + Thread.MemoryBarrier(); + inited = true; + } + catch (Exception ex) + { + exception = ex; + throw; + } + break; + } + case LazyThreadSafetyMode.PublicationOnly: + { + var init_factory = factory; + T v; + + //exceptions are ignored + if (init_factory != null) + v = init_factory(); + else + v = default(T); + + lock (monitor) + { + if (inited) + return value; + value = v; + Thread.MemoryBarrier(); + inited = true; + factory = null; + } + break; + } + case LazyThreadSafetyMode.ExecutionAndPublication: + { + lock (monitor) + { + if (inited) + return value; + + if (factory == null) + throw exception = new InvalidOperationException("The initialization function tries to access Value on this instance"); + + var init_factory = factory; + try + { + factory = null; + T v = init_factory(); + value = v; + Thread.MemoryBarrier(); + inited = true; + } + catch (Exception ex) + { + exception = ex; + throw; + } + } + break; + } + default: + throw new InvalidOperationException("Invalid LazyThreadSafetyMode " + mode); + } + + if (monitor == null) + { + value = factory(); + inited = true; + } + else + { + lock (monitor) + { + if (inited) + return value; + + if (factory == null) + throw new InvalidOperationException("The initialization function tries to access Value on this instance"); + + var init_factory = factory; + try + { + factory = null; + T v = init_factory(); + value = v; + Thread.MemoryBarrier(); + inited = true; + } + catch + { + factory = init_factory; + throw; + } + } + } + + return value; + } + + public bool IsValueCreated + { + get + { + return inited; + } + } + + public override string ToString() + { + if (inited) + return value.ToString(); + else + return "Value is not created"; + } + } +} diff --git a/OpenSim/Framework/PrimitiveBaseShape.cs b/OpenSim/Framework/PrimitiveBaseShape.cs index 1208b97300..4d1de22eeb 100644 --- a/OpenSim/Framework/PrimitiveBaseShape.cs +++ b/OpenSim/Framework/PrimitiveBaseShape.cs @@ -236,7 +236,7 @@ namespace OpenSim.Framework catch { } m_log.Warn("[SHAPE]: Failed to decode texture, length=" + ((m_textureEntry != null) ? m_textureEntry.Length : 0)); - return new Primitive.TextureEntry(null); + return new Primitive.TextureEntry(UUID.Zero); } set { m_textureEntry = value.GetBytes(); } diff --git a/OpenSim/Framework/Serialization/ArchiveConstants.cs b/OpenSim/Framework/Serialization/ArchiveConstants.cs index 1cd80db24d..475a9de0cb 100644 --- a/OpenSim/Framework/Serialization/ArchiveConstants.cs +++ b/OpenSim/Framework/Serialization/ArchiveConstants.cs @@ -25,6 +25,7 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +using System; using System.Collections.Generic; using OpenMetaverse; @@ -85,6 +86,11 @@ namespace OpenSim.Framework.Serialization /// public const string INVENTORY_NODE_NAME_COMPONENT_SEPARATOR = "__"; + /// + /// Template used for creating filenames in OpenSim Archives. + /// + public const string OAR_OBJECT_FILENAME_TEMPLATE = "{0}_{1:000}-{2:000}-{3:000}__{4}.xml"; + /// /// Extensions used for asset types in the archive /// @@ -139,5 +145,32 @@ namespace OpenSim.Framework.Serialization EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "texture.tga"] = (sbyte)AssetType.TextureTGA; EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "trashfolder.txt"] = (sbyte)AssetType.TrashFolder; } + + /// + /// Create the filename used to store an object in an OpenSim Archive. + /// + /// + /// + /// + /// + public static string CreateOarObjectFilename(string objectName, UUID uuid, Vector3 pos) + { + return string.Format( + OAR_OBJECT_FILENAME_TEMPLATE, objectName, + Math.Round(pos.X), Math.Round(pos.Y), Math.Round(pos.Z), + uuid); + } + + /// + /// Create the path used to store an object in an OpenSim Archives. + /// + /// + /// + /// + /// + public static string CreateOarObjectPath(string objectName, UUID uuid, Vector3 pos) + { + return OBJECTS_PATH + CreateOarObjectFilename(objectName, uuid, pos); + } } } diff --git a/OpenSim/Framework/Serialization/TarArchiveWriter.cs b/OpenSim/Framework/Serialization/TarArchiveWriter.cs index 0bd639ff3a..fca909f2d8 100644 --- a/OpenSim/Framework/Serialization/TarArchiveWriter.cs +++ b/OpenSim/Framework/Serialization/TarArchiveWriter.cs @@ -28,7 +28,9 @@ using System; using System.Collections.Generic; using System.IO; +using System.Reflection; using System.Text; +using log4net; namespace OpenSim.Framework.Serialization { @@ -37,7 +39,7 @@ namespace OpenSim.Framework.Serialization /// public class TarArchiveWriter { - //private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); +// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected static ASCIIEncoding m_asciiEncoding = new ASCIIEncoding(); protected static UTF8Encoding m_utf8Encoding = new UTF8Encoding(); @@ -148,6 +150,9 @@ namespace OpenSim.Framework.Serialization /// protected void WriteEntry(string filePath, byte[] data, char fileType) { +// m_log.DebugFormat( +// "[TAR ARCHIVE WRITER]: Data for {0} is {1} bytes", filePath, (null == data ? "null" : data.Length.ToString())); + byte[] header = new byte[512]; // file path field (100) diff --git a/OpenSim/Framework/Serialization/Tests/LandDataSerializerTests.cs b/OpenSim/Framework/Serialization/Tests/LandDataSerializerTests.cs index 14e04621a4..70e87b3c08 100644 --- a/OpenSim/Framework/Serialization/Tests/LandDataSerializerTests.cs +++ b/OpenSim/Framework/Serialization/Tests/LandDataSerializerTests.cs @@ -96,15 +96,19 @@ namespace OpenSim.Framework.Serialization.Tests [Test] public void LandDataSerializerSerializeTest() { - string serialized = LandDataSerializer.Serialize(this.land); + string serialized = LandDataSerializer.Serialize(this.land).Replace("\r\n", "\n"); Assert.That(serialized.Length > 0, "Serialize(LandData) returned empty string"); - Assert.That(serialized == LandDataSerializerTest.preSerialized, - "result of Serialize(LandData) does not match expected result"); - string serializedWithParcelAccessList = LandDataSerializer.Serialize(this.landWithParcelAccessList); - Assert.That(serializedWithParcelAccessList.Length > 0, + // adding a simple boolean variable because resharper nUnit integration doesn't like this + // XML data in the Assert.That statement. Not sure why. + bool result = (serialized == preSerialized); + Assert.That(result, "result of Serialize LandData does not match expected result"); + + string serializedWithParcelAccessList = LandDataSerializer.Serialize(this.landWithParcelAccessList).Replace("\r\n", "\n"); + Assert.That(serializedWithParcelAccessList.Length > 0, "Serialize(LandData) returned empty string for LandData object with ParcelAccessList"); - Assert.That(serializedWithParcelAccessList == LandDataSerializerTest.preSerializedWithParcelAccessList, + result = (serializedWithParcelAccessList == preSerializedWithParcelAccessList); + Assert.That(result, "result of Serialize(LandData) does not match expected result (pre-serialized with parcel access list"); } diff --git a/OpenSim/Framework/Servers/BaseOpenSimServer.cs b/OpenSim/Framework/Servers/BaseOpenSimServer.cs index 655df9df78..f0f8d0186b 100644 --- a/OpenSim/Framework/Servers/BaseOpenSimServer.cs +++ b/OpenSim/Framework/Servers/BaseOpenSimServer.cs @@ -286,7 +286,11 @@ namespace OpenSim.Framework.Servers EnhanceVersionInformation(); - m_log.Info("[STARTUP]: Version: " + m_version + "\n"); + m_log.Info("[STARTUP]: OpenSimulator version: " + m_version + Environment.NewLine); + // clr version potentially is more confusing than helpful, since it doesn't tell us if we're running under Mono/MS .NET and + // the clr version number doesn't match the project version number under Mono. + //m_log.Info("[STARTUP]: Virtual machine runtime version: " + Environment.Version + Environment.NewLine); + m_log.Info("[STARTUP]: Operating system version: " + Environment.OSVersion + Environment.NewLine); StartupSpecific(); diff --git a/OpenSim/Framework/Servers/HttpServer/SynchronousRestFormsRequester.cs b/OpenSim/Framework/Servers/HttpServer/SynchronousRestFormsRequester.cs index 4543fd5e99..b0cf34d16e 100644 --- a/OpenSim/Framework/Servers/HttpServer/SynchronousRestFormsRequester.cs +++ b/OpenSim/Framework/Servers/HttpServer/SynchronousRestFormsRequester.cs @@ -81,7 +81,7 @@ namespace OpenSim.Framework.Servers.HttpServer } catch (Exception e) { - m_log.DebugFormat("[FORMS]: exception occured on sending request {0}", e.Message); + m_log.DebugFormat("[FORMS]: exception occured on sending request to {0}: {1}", requestUrl, e.Message); } finally { diff --git a/OpenSim/Framework/TaskInventoryItem.cs b/OpenSim/Framework/TaskInventoryItem.cs index 2b0096bd46..2cb78957f5 100644 --- a/OpenSim/Framework/TaskInventoryItem.cs +++ b/OpenSim/Framework/TaskInventoryItem.cs @@ -122,6 +122,8 @@ namespace OpenSim.Framework private int _type = 0; private UUID _oldID; + private bool _ownerChanged = false; + public UUID AssetID { get { return _assetID; @@ -320,6 +322,15 @@ namespace OpenSim.Framework } } + public bool OwnerChanged { + get { + return _ownerChanged; + } + set { + _ownerChanged = value; + } + } + // See ICloneable #region ICloneable Members diff --git a/OpenSim/Framework/WebUtil.cs b/OpenSim/Framework/WebUtil.cs index 2843e202be..94862a6372 100644 --- a/OpenSim/Framework/WebUtil.cs +++ b/OpenSim/Framework/WebUtil.cs @@ -146,18 +146,23 @@ namespace OpenSim.Framework { using (Stream responseStream = response.GetResponseStream()) { + string responseStr = null; + try { - string responseStr = responseStream.GetStreamString(); + responseStr = responseStream.GetStreamString(); OSD responseOSD = OSDParser.Deserialize(responseStr); if (responseOSD.Type == OSDType.Map) return (OSDMap)responseOSD; else errorMessage = "Response format was invalid."; } - catch + catch (Exception ex) { - errorMessage = "Failed to parse the response."; + if (!String.IsNullOrEmpty(responseStr)) + errorMessage = "Failed to parse the response:\n" + responseStr; + else + errorMessage = "Failed to retrieve the response: " + ex.Message; } } } diff --git a/OpenSim/Region/Application/Application.cs b/OpenSim/Region/Application/Application.cs index 7721cdf491..b860cf6bc0 100644 --- a/OpenSim/Region/Application/Application.cs +++ b/OpenSim/Region/Application/Application.cs @@ -105,7 +105,7 @@ namespace OpenSim // Check if the system is compatible with OpenSimulator. // Ensures that the minimum system requirements are met - m_log.Info("Performing compatibility checks... "); + m_log.Info("Performing compatibility checks... \n"); string supported = String.Empty; if (Util.IsEnvironmentSupported(ref supported)) { @@ -120,6 +120,113 @@ namespace OpenSim Culture.SetCurrentCulture(); + // Validate that the user has the most basic configuration done + // If not, offer to do the most basic configuration for them warning them along the way of the importance of + // reading these files. + /* + m_log.Info("Checking for reguired configuration...\n"); + + bool OpenSim_Ini = (File.Exists(Path.Combine(Util.configDir(), "OpenSim.ini"))) + || (File.Exists(Path.Combine(Util.configDir(), "opensim.ini"))) + || (File.Exists(Path.Combine(Util.configDir(), "openSim.ini"))) + || (File.Exists(Path.Combine(Util.configDir(), "Opensim.ini"))); + + bool StanaloneCommon_ProperCased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "StandaloneCommon.ini")); + bool StanaloneCommon_lowercased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "standalonecommon.ini")); + bool GridCommon_ProperCased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "GridCommon.ini")); + bool GridCommon_lowerCased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "gridcommon.ini")); + + if ((OpenSim_Ini) + && ( + (StanaloneCommon_ProperCased + || StanaloneCommon_lowercased + || GridCommon_ProperCased + || GridCommon_lowerCased + ))) + { + m_log.Info("Required Configuration Files Found\n"); + } + else + { + MainConsole.Instance = new LocalConsole("Region"); + string resp = MainConsole.Instance.CmdPrompt( + "\n\n*************Required Configuration files not found.*************\n\n OpenSimulator will not run without these files.\n\nRemember, these file names are Case Sensitive in Linux and Proper Cased.\n1. ./OpenSim.ini\nand\n2. ./config-include/StandaloneCommon.ini \nor\n3. ./config-include/GridCommon.ini\n\nAlso, you will want to examine these files in great detail because only the basic system will load by default. OpenSimulator can do a LOT more if you spend a little time going through these files.\n\n" + ": " + "Do you want to copy the most basic Defaults from standalone?", + "yes"); + if (resp == "yes") + { + + if (!(OpenSim_Ini)) + { + try + { + File.Copy(Path.Combine(Util.configDir(), "OpenSim.ini.example"), + Path.Combine(Util.configDir(), "OpenSim.ini")); + } catch (UnauthorizedAccessException) + { + MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, Make sure OpenSim has have the required permissions\n"); + } catch (ArgumentException) + { + MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, The current directory is invalid.\n"); + } catch (System.IO.PathTooLongException) + { + MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the Path to these files is too long.\n"); + } catch (System.IO.DirectoryNotFoundException) + { + MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the current directory is reporting as not found.\n"); + } catch (System.IO.FileNotFoundException) + { + MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the example is not found, please make sure that the example files exist.\n"); + } catch (System.IO.IOException) + { + // Destination file exists already or a hard drive failure... .. so we can just drop this one + //MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the example is not found, please make sure that the example files exist.\n"); + } catch (System.NotSupportedException) + { + MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, The current directory is invalid.\n"); + } + + } + if (!(StanaloneCommon_ProperCased || StanaloneCommon_lowercased)) + { + try + { + File.Copy(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "StandaloneCommon.ini.example"), + Path.Combine(Path.Combine(Util.configDir(), "config-include"), "StandaloneCommon.ini")); + } + catch (UnauthorizedAccessException) + { + MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, Make sure OpenSim has the required permissions\n"); + } + catch (ArgumentException) + { + MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, The current directory is invalid.\n"); + } + catch (System.IO.PathTooLongException) + { + MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, the Path to these files is too long.\n"); + } + catch (System.IO.DirectoryNotFoundException) + { + MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, the current directory is reporting as not found.\n"); + } + catch (System.IO.FileNotFoundException) + { + MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, the example is not found, please make sure that the example files exist.\n"); + } + catch (System.IO.IOException) + { + // Destination file exists already or a hard drive failure... .. so we can just drop this one + //MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the example is not found, please make sure that the example files exist.\n"); + } + catch (System.NotSupportedException) + { + MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, The current directory is invalid.\n"); + } + } + } + MainConsole.Instance = null; + } + */ configSource.Alias.AddAlias("On", true); configSource.Alias.AddAlias("Off", false); configSource.Alias.AddAlias("True", true); @@ -145,6 +252,8 @@ namespace OpenSim // load Crash directory config m_crashDir = configSource.Configs["Startup"].GetString("crash_dir", m_crashDir); + + if (background) { m_sim = new OpenSimBackground(configSource); @@ -152,8 +261,14 @@ namespace OpenSim } else { + + + + m_sim = new OpenSim(configSource); + + m_sim.Startup(); while (true) diff --git a/OpenSim/Region/Application/ConfigurationLoader.cs b/OpenSim/Region/Application/ConfigurationLoader.cs index 4ca6595501..cac5fa99c8 100644 --- a/OpenSim/Region/Application/ConfigurationLoader.cs +++ b/OpenSim/Region/Application/ConfigurationLoader.cs @@ -349,12 +349,6 @@ namespace OpenSim m_configSettings.See_into_region_from_neighbor = startupConfig.GetBoolean("see_into_this_sim_from_neighbor", true); m_configSettings.StorageDll = startupConfig.GetString("storage_plugin"); - if (m_configSettings.StorageDll == "OpenSim.DataStore.MonoSqlite.dll") - { - m_configSettings.StorageDll = "OpenSim.Data.SQLite.dll"; - m_log.Warn("WARNING: OpenSim.DataStore.MonoSqlite.dll is deprecated. Set storage_plugin to OpenSim.Data.SQLite.dll."); - Thread.Sleep(3000); - } m_configSettings.StorageConnectionString = startupConfig.GetString("storage_connection_string"); diff --git a/OpenSim/Region/Application/OpenSim.cs b/OpenSim/Region/Application/OpenSim.cs index 139503074f..a09b903bfc 100644 --- a/OpenSim/Region/Application/OpenSim.cs +++ b/OpenSim/Region/Application/OpenSim.cs @@ -251,14 +251,20 @@ namespace OpenSim "Save named prim to XML2", SavePrimsXml2); m_console.Commands.AddCommand("region", false, "load oar", - "load oar [--merge] [--skip-assets] ", - "Load a region's data from OAR archive. --merge will merge the oar with the existing scene. --skip-assets will load the oar but ignore the assets it contains", + "load oar [--merge] [--skip-assets] []", + "Load a region's data from an OAR archive.", + "--merge will merge the OAR with the existing scene." + Environment.NewLine + + "--skip-assets will load the OAR but ignore the assets it contains." + Environment.NewLine + + "The path can be either a filesystem location or a URI." + + " If this is not given then the command looks for an OAR named region.oar in the current directory.", LoadOar); m_console.Commands.AddCommand("region", false, "save oar", - "save oar ", - "Save a region's data to an OAR archive", - "More information on forthcoming options here soon", SaveOar); + "save oar []", + "Save a region's data to an OAR archive.", + "The OAR path must be a filesystem path." + + " If this is not given then the oar is saved to region.oar in the current directory.", + SaveOar); m_console.Commands.AddCommand("region", false, "edit scale", "edit scale ", diff --git a/OpenSim/Region/Application/OpenSimBase.cs b/OpenSim/Region/Application/OpenSimBase.cs index 06ffa917f5..83be61ee63 100644 --- a/OpenSim/Region/Application/OpenSimBase.cs +++ b/OpenSim/Region/Application/OpenSimBase.cs @@ -349,7 +349,7 @@ namespace OpenSim // moved these here as the terrain texture has to be created after the modules are initialized // and has to happen before the region is registered with the grid. - scene.CreateTerrainTexture(false); + scene.CreateTerrainTexture(); // TODO : Try setting resource for region xstats here on scene MainServer.Instance.AddStreamHandler(new Region.Framework.Scenes.RegionStatsHandler(regionInfo)); diff --git a/OpenSim/Region/ClientStack/LindenUDP/LLClientView.cs b/OpenSim/Region/ClientStack/LindenUDP/LLClientView.cs index 216c499afc..61f2002be3 100644 --- a/OpenSim/Region/ClientStack/LindenUDP/LLClientView.cs +++ b/OpenSim/Region/ClientStack/LindenUDP/LLClientView.cs @@ -51,44 +51,6 @@ using System.Linq; namespace OpenSim.Region.ClientStack.LindenUDP { - #region Enums - - /// - /// Specifies the fields that have been changed when sending a prim or - /// avatar update - /// - [Flags] - public enum PrimUpdateFlags : uint - { - None = 0, - AttachmentPoint = 1 << 0, - Material = 1 << 1, - ClickAction = 1 << 2, - Scale = 1 << 3, - ParentID = 1 << 4, - PrimFlags = 1 << 5, - PrimData = 1 << 6, - MediaURL = 1 << 7, - ScratchPad = 1 << 8, - Textures = 1 << 9, - TextureAnim = 1 << 10, - NameValue = 1 << 11, - Position = 1 << 12, - Rotation = 1 << 13, - Velocity = 1 << 14, - Acceleration = 1 << 15, - AngularVelocity = 1 << 16, - CollisionPlane = 1 << 17, - Text = 1 << 18, - Particles = 1 << 19, - ExtraData = 1 << 20, - Sound = 1 << 21, - Joint = 1 << 22, - FullUpdate = UInt32.MaxValue - } - - #endregion Enums - public delegate bool PacketMethod(IClientAPI simClient, Packet packet); /// @@ -354,9 +316,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP private readonly IGroupsModule m_GroupsModule; private int m_cachedTextureSerial; - protected PriorityQueue m_avatarTerseUpdates; - private PriorityQueue m_primTerseUpdates; - private PriorityQueue m_primFullUpdates; + private PriorityQueue m_entityUpdates; + private Prioritizer m_prioritizer; /// /// List used in construction of data blocks for an object update packet. This is to stop us having to @@ -467,9 +428,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP m_scene = scene; - m_avatarTerseUpdates = new PriorityQueue(); - m_primTerseUpdates = new PriorityQueue(); - m_primFullUpdates = new PriorityQueue(m_scene.Entities.Count); + m_entityUpdates = new PriorityQueue(m_scene.Entities.Count); m_fullUpdateDataBlocksBuilder = new List(); m_killRecord = new HashSet(); @@ -496,6 +455,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP m_propertiesPacketTimer = new Timer(100); m_propertiesPacketTimer.Elapsed += ProcessObjectPropertiesPacket; + m_prioritizer = new Prioritizer(m_scene); + RegisterLocalPacketHandlers(); } @@ -859,6 +820,21 @@ namespace OpenSim.Region.ClientStack.LindenUDP } } + public void SendGenericMessage(string method, List message) + { + GenericMessagePacket gmp = new GenericMessagePacket(); + gmp.MethodData.Method = Util.StringToBytes256(method); + gmp.ParamList = new GenericMessagePacket.ParamListBlock[message.Count]; + int i = 0; + foreach (string val in message) + { + gmp.ParamList[i] = new GenericMessagePacket.ParamListBlock(); + gmp.ParamList[i++].Parameter = Util.StringToBytes256(val); + } + + OutPacket(gmp, ThrottleOutPacketType.Task); + } + public void SendGenericMessage(string method, List message) { GenericMessagePacket gmp = new GenericMessagePacket(); @@ -1523,7 +1499,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP kill.Header.Reliable = true; kill.Header.Zerocoded = true; - lock (m_primFullUpdates.SyncRoot) + lock (m_entityUpdates.SyncRoot) { m_killRecord.Add(localID); OutPacket(kill, ThrottleOutPacketType.State); @@ -3423,71 +3399,24 @@ namespace OpenSim.Region.ClientStack.LindenUDP /// /// Send an ObjectUpdate packet with information about an avatar /// - public void SendAvatarData(SendAvatarData data) + public void SendAvatarDataImmediate(ISceneEntity avatar) { + ScenePresence presence = avatar as ScenePresence; + if (presence == null) + return; + ObjectUpdatePacket objupdate = (ObjectUpdatePacket)PacketPool.Instance.GetPacket(PacketType.ObjectUpdate); objupdate.Header.Zerocoded = true; - objupdate.RegionData.RegionHandle = data.RegionHandle; + objupdate.RegionData.RegionHandle = presence.RegionHandle; objupdate.RegionData.TimeDilation = ushort.MaxValue; objupdate.ObjectData = new ObjectUpdatePacket.ObjectDataBlock[1]; - objupdate.ObjectData[0] = CreateAvatarUpdateBlock(data); + objupdate.ObjectData[0] = CreateAvatarUpdateBlock(presence); OutPacket(objupdate, ThrottleOutPacketType.Task); } - /// - /// Send a terse positional/rotation/velocity update about an avatar - /// to the client. This avatar can be that of the client itself. - /// - public virtual void SendAvatarTerseUpdate(SendAvatarTerseData data) - { - if (data.Priority == double.NaN) - { - m_log.Error("[LLClientView] SendAvatarTerseUpdate received a NaN priority, dropping update"); - return; - } - - Quaternion rotation = data.Rotation; - if (rotation.W == 0.0f && rotation.X == 0.0f && rotation.Y == 0.0f && rotation.Z == 0.0f) - rotation = Quaternion.Identity; - - ImprovedTerseObjectUpdatePacket.ObjectDataBlock terseBlock = CreateImprovedTerseBlock(data); - - lock (m_avatarTerseUpdates.SyncRoot) - m_avatarTerseUpdates.Enqueue(data.Priority, terseBlock, data.LocalID); - - // If we received an update about our own avatar, process the avatar update priority queue immediately - if (data.AgentID == m_agentId) - ProcessAvatarTerseUpdates(); - } - - protected void ProcessAvatarTerseUpdates() - { - ImprovedTerseObjectUpdatePacket terse = (ImprovedTerseObjectUpdatePacket)PacketPool.Instance.GetPacket(PacketType.ImprovedTerseObjectUpdate); - terse.Header.Reliable = false; - terse.Header.Zerocoded = true; - - //terse.RegionData = new ImprovedTerseObjectUpdatePacket.RegionDataBlock(); - terse.RegionData.RegionHandle = Scene.RegionInfo.RegionHandle; - terse.RegionData.TimeDilation = (ushort)(Scene.TimeDilation * ushort.MaxValue); - - lock (m_avatarTerseUpdates.SyncRoot) - { - int count = Math.Min(m_avatarTerseUpdates.Count, m_udpServer.AvatarTerseUpdatesPerPacket); - if (count == 0) - return; - - terse.ObjectData = new ImprovedTerseObjectUpdatePacket.ObjectDataBlock[count]; - for (int i = 0; i < count; i++) - terse.ObjectData[i] = m_avatarTerseUpdates.Dequeue(); - } - - // HACK: Using the task category until the tiered reprioritization code is in - OutPacket(terse, ThrottleOutPacketType.Task); - } - public void SendCoarseLocationUpdate(List users, List CoarseLocations) { if (!IsActive) return; // We don't need to update inactive clients. @@ -3532,172 +3461,186 @@ namespace OpenSim.Region.ClientStack.LindenUDP #region Primitive Packet/Data Sending Methods - public void SendPrimitiveToClient(SendPrimitiveData data) + /// + /// Generate one of the object update packets based on PrimUpdateFlags + /// and broadcast the packet to clients + /// + public void SendPrimUpdate(ISceneEntity entity, PrimUpdateFlags updateFlags) { -// string text = data.text; -// if (text.IndexOf("\n") >= 0) -// text = text.Remove(text.IndexOf("\n")); -// m_log.DebugFormat( -// "[CLIENT]: Placing request to send full info about prim {0} text {1} to client {2}", -// data.localID, text, Name); - - if (data.priority == double.NaN) - { - m_log.Error("[LLClientView] SendPrimitiveToClient received a NaN priority, dropping update"); - return; - } + double priority = m_prioritizer.GetUpdatePriority(this, entity); - Quaternion rotation = data.rotation; - if (rotation.W == 0.0f && rotation.X == 0.0f && rotation.Y == 0.0f && rotation.Z == 0.0f) - rotation = Quaternion.Identity; - - if (data.AttachPoint > 30 && data.ownerID != AgentId) // Someone else's HUD - return; - if (data.primShape.State != 0 && data.parentID == 0 && data.primShape.PCode == 9) - return; - - ObjectUpdatePacket.ObjectDataBlock objectData = CreatePrimUpdateBlock(data); - - lock (m_primFullUpdates.SyncRoot) - m_primFullUpdates.Enqueue(data.priority, objectData, data.localID); + lock (m_entityUpdates.SyncRoot) + m_entityUpdates.Enqueue(priority, new EntityUpdate(entity, updateFlags), entity.LocalId); } - void ProcessPrimFullUpdates() + private void ProcessEntityUpdates(int maxUpdates) { - ObjectUpdatePacket outPacket = (ObjectUpdatePacket)PacketPool.Instance.GetPacket(PacketType.ObjectUpdate); - outPacket.Header.Zerocoded = true; + Lazy> objectUpdateBlocks = new Lazy>(); + Lazy> compressedUpdateBlocks = new Lazy>(); + Lazy> terseUpdateBlocks = new Lazy>(); - outPacket.RegionData.RegionHandle = Scene.RegionInfo.RegionHandle; - outPacket.RegionData.TimeDilation = (ushort)(Scene.TimeDilation * ushort.MaxValue); + if (maxUpdates <= 0) maxUpdates = Int32.MaxValue; + int updatesThisCall = 0; - lock (m_primFullUpdates.SyncRoot) + lock (m_entityUpdates.SyncRoot) { - int count = Math.Min(m_primFullUpdates.Count, m_udpServer.PrimFullUpdatesPerPacket); - if (count == 0) - return; - - m_fullUpdateDataBlocksBuilder.Clear(); - - for (int i = 0; i < count; i++) + EntityUpdate update; + while (updatesThisCall < maxUpdates && m_entityUpdates.TryDequeue(out update)) { - ObjectUpdatePacket.ObjectDataBlock block = m_primFullUpdates.Dequeue(); + ++updatesThisCall; - if (!m_killRecord.Contains(block.ID)) + #region UpdateFlags to packet type conversion + + PrimUpdateFlags updateFlags = update.Flags; + + bool canUseCompressed = true; + bool canUseImproved = true; + + // Compressed object updates only make sense for LL primitives + if (!(update.Entity is SceneObjectPart)) { - m_fullUpdateDataBlocksBuilder.Add(block); - -// string text = Util.FieldToString(outPacket.ObjectData[i].Text); -// if (text.IndexOf("\n") >= 0) -// text = text.Remove(text.IndexOf("\n")); -// m_log.DebugFormat( -// "[CLIENT]: Sending full info about prim {0} text {1} to client {2}", -// outPacket.ObjectData[i].ID, text, Name); + canUseCompressed = false; } -// else -// { -// m_log.WarnFormat( -// "[CLIENT]: Preventing full update for {0} after kill to {1}", block.ID, Name); -// } + + if (updateFlags.HasFlag(PrimUpdateFlags.FullUpdate)) + { + canUseCompressed = false; + canUseImproved = false; + } + else + { + if (updateFlags.HasFlag(PrimUpdateFlags.Velocity) || + updateFlags.HasFlag(PrimUpdateFlags.Acceleration) || + updateFlags.HasFlag(PrimUpdateFlags.CollisionPlane) || + updateFlags.HasFlag(PrimUpdateFlags.Joint)) + { + canUseCompressed = false; + } + + if (updateFlags.HasFlag(PrimUpdateFlags.PrimFlags) || + updateFlags.HasFlag(PrimUpdateFlags.ParentID) || + updateFlags.HasFlag(PrimUpdateFlags.Scale) || + updateFlags.HasFlag(PrimUpdateFlags.PrimData) || + updateFlags.HasFlag(PrimUpdateFlags.Text) || + updateFlags.HasFlag(PrimUpdateFlags.NameValue) || + updateFlags.HasFlag(PrimUpdateFlags.ExtraData) || + updateFlags.HasFlag(PrimUpdateFlags.TextureAnim) || + updateFlags.HasFlag(PrimUpdateFlags.Sound) || + updateFlags.HasFlag(PrimUpdateFlags.Particles) || + updateFlags.HasFlag(PrimUpdateFlags.Material) || + updateFlags.HasFlag(PrimUpdateFlags.ClickAction) || + updateFlags.HasFlag(PrimUpdateFlags.MediaURL) || + updateFlags.HasFlag(PrimUpdateFlags.Joint)) + { + canUseImproved = false; + } + } + + #endregion UpdateFlags to packet type conversion + + #region Block Construction + + // TODO: Remove this once we can build compressed updates + canUseCompressed = false; + + if (!canUseImproved && !canUseCompressed) + { + if (update.Entity is ScenePresence) + objectUpdateBlocks.Value.Add(CreateAvatarUpdateBlock((ScenePresence)update.Entity)); + else + objectUpdateBlocks.Value.Add(CreatePrimUpdateBlock((SceneObjectPart)update.Entity, this.m_agentId)); + } + else if (!canUseImproved) + { + compressedUpdateBlocks.Value.Add(CreateCompressedUpdateBlock((SceneObjectPart)update.Entity, updateFlags)); + } + else + { + terseUpdateBlocks.Value.Add(CreateImprovedTerseBlock(update.Entity, updateFlags.HasFlag(PrimUpdateFlags.Textures))); + } + + #endregion Block Construction } + } - outPacket.ObjectData = m_fullUpdateDataBlocksBuilder.ToArray(); - - OutPacket(outPacket, ThrottleOutPacketType.State); - } + #region Packet Sending + + const float TIME_DILATION = 1.0f; + ushort timeDilation = Utils.FloatToUInt16(TIME_DILATION, 0.0f, 1.0f); + + if (objectUpdateBlocks.IsValueCreated) + { + List blocks = objectUpdateBlocks.Value; + + ObjectUpdatePacket packet = (ObjectUpdatePacket)PacketPool.Instance.GetPacket(PacketType.ObjectUpdate); + packet.RegionData.RegionHandle = m_scene.RegionInfo.RegionHandle; + packet.RegionData.TimeDilation = timeDilation; + packet.ObjectData = new ObjectUpdatePacket.ObjectDataBlock[blocks.Count]; + + for (int i = 0; i < blocks.Count; i++) + packet.ObjectData[i] = blocks[i]; + + OutPacket(packet, ThrottleOutPacketType.Task, true); + } + + if (compressedUpdateBlocks.IsValueCreated) + { + List blocks = compressedUpdateBlocks.Value; + + ObjectUpdateCompressedPacket packet = (ObjectUpdateCompressedPacket)PacketPool.Instance.GetPacket(PacketType.ObjectUpdateCompressed); + packet.RegionData.RegionHandle = m_scene.RegionInfo.RegionHandle; + packet.RegionData.TimeDilation = timeDilation; + packet.ObjectData = new ObjectUpdateCompressedPacket.ObjectDataBlock[blocks.Count]; + + for (int i = 0; i < blocks.Count; i++) + packet.ObjectData[i] = blocks[i]; + + OutPacket(packet, ThrottleOutPacketType.Task, true); + } + + if (terseUpdateBlocks.IsValueCreated) + { + List blocks = terseUpdateBlocks.Value; + + ImprovedTerseObjectUpdatePacket packet = new ImprovedTerseObjectUpdatePacket(); + packet.RegionData.RegionHandle = m_scene.RegionInfo.RegionHandle; + packet.RegionData.TimeDilation = timeDilation; + packet.ObjectData = new ImprovedTerseObjectUpdatePacket.ObjectDataBlock[blocks.Count]; + + for (int i = 0; i < blocks.Count; i++) + packet.ObjectData[i] = blocks[i]; + + OutPacket(packet, ThrottleOutPacketType.Task, true); + } + + #endregion Packet Sending } - public void SendPrimTerseUpdate(SendPrimitiveTerseData data) + public void ReprioritizeUpdates() { - if (data.Priority == double.NaN) - { - m_log.Error("[LLClientView] SendPrimTerseUpdate received a NaN priority, dropping update"); - return; - } + //m_log.Debug("[CLIENT]: Reprioritizing prim updates for " + m_firstName + " " + m_lastName); - Quaternion rotation = data.Rotation; - if (rotation.W == 0.0f && rotation.X == 0.0f && rotation.Y == 0.0f && rotation.Z == 0.0f) - rotation = Quaternion.Identity; - - if (data.AttachPoint > 30 && data.OwnerID != AgentId) // Someone else's HUD - return; - - ImprovedTerseObjectUpdatePacket.ObjectDataBlock objectData = CreateImprovedTerseBlock(data); - - lock (m_primTerseUpdates.SyncRoot) - m_primTerseUpdates.Enqueue(data.Priority, objectData, data.LocalID); + lock (m_entityUpdates.SyncRoot) + m_entityUpdates.Reprioritize(UpdatePriorityHandler); } - void ProcessPrimTerseUpdates() + private bool UpdatePriorityHandler(ref double priority, uint localID) { - ImprovedTerseObjectUpdatePacket outPacket = (ImprovedTerseObjectUpdatePacket)PacketPool.Instance.GetPacket(PacketType.ImprovedTerseObjectUpdate); - outPacket.Header.Reliable = false; - outPacket.Header.Zerocoded = true; - - outPacket.RegionData.RegionHandle = Scene.RegionInfo.RegionHandle; - outPacket.RegionData.TimeDilation = (ushort)(Scene.TimeDilation * ushort.MaxValue); - - lock (m_primTerseUpdates.SyncRoot) + EntityBase entity; + if (m_scene.Entities.TryGetValue(localID, out entity)) { - int count = Math.Min(m_primTerseUpdates.Count, m_udpServer.PrimTerseUpdatesPerPacket); - if (count == 0) - return; - - outPacket.ObjectData = new ImprovedTerseObjectUpdatePacket.ObjectDataBlock[count]; - for (int i = 0; i < count; i++) - outPacket.ObjectData[i] = m_primTerseUpdates.Dequeue(); + priority = m_prioritizer.GetUpdatePriority(this, entity); } - OutPacket(outPacket, ThrottleOutPacketType.State); - } - - public void ReprioritizeUpdates(StateUpdateTypes type, UpdatePriorityHandler handler) - { - PriorityQueue.UpdatePriorityHandler terse_update_priority_handler = - delegate(ref double priority, uint local_id) - { - priority = handler(new UpdatePriorityData(priority, local_id)); - return priority != double.NaN; - }; - PriorityQueue.UpdatePriorityHandler update_priority_handler = - delegate(ref double priority, uint local_id) - { - priority = handler(new UpdatePriorityData(priority, local_id)); - return priority != double.NaN; - }; - - if ((type & StateUpdateTypes.AvatarTerse) != 0) - { - lock (m_avatarTerseUpdates.SyncRoot) - m_avatarTerseUpdates.Reprioritize(terse_update_priority_handler); - } - - if ((type & StateUpdateTypes.PrimitiveFull) != 0) - { - lock (m_primFullUpdates.SyncRoot) - m_primFullUpdates.Reprioritize(update_priority_handler); - } - - if ((type & StateUpdateTypes.PrimitiveTerse) != 0) - { - lock (m_primTerseUpdates.SyncRoot) - m_primTerseUpdates.Reprioritize(terse_update_priority_handler); - } + return priority != double.NaN; } public void FlushPrimUpdates() { - while (m_primFullUpdates.Count > 0) - { - ProcessPrimFullUpdates(); - } - while (m_primTerseUpdates.Count > 0) - { - ProcessPrimTerseUpdates(); - } - while (m_avatarTerseUpdates.Count > 0) - { - ProcessAvatarTerseUpdates(); - } + m_log.Debug("[CLIENT]: Flushing prim updates to " + m_firstName + " " + m_lastName); + + while (m_entityUpdates.Count > 0) + ProcessEntityUpdates(-1); } #endregion Primitive Packet/Data Sending Methods @@ -3730,26 +3673,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP { if ((categories & ThrottleOutPacketTypeFlags.Task) != 0) { - lock (m_avatarTerseUpdates.SyncRoot) - { - if (m_avatarTerseUpdates.Count > 0) - ProcessAvatarTerseUpdates(); - } - } - - if ((categories & ThrottleOutPacketTypeFlags.State) != 0) - { - lock (m_primFullUpdates.SyncRoot) - { - if (m_primFullUpdates.Count > 0) - ProcessPrimFullUpdates(); - } - - lock (m_primTerseUpdates.SyncRoot) - { - if (m_primTerseUpdates.Count > 0) - ProcessPrimTerseUpdates(); - } + if (m_entityUpdates.Count > 0) + ProcessEntityUpdates(m_udpServer.PrimUpdatesPerCallback); } if ((categories & ThrottleOutPacketTypeFlags.Texture) != 0) @@ -4407,22 +4332,55 @@ namespace OpenSim.Region.ClientStack.LindenUDP #region Helper Methods - protected ImprovedTerseObjectUpdatePacket.ObjectDataBlock CreateImprovedTerseBlock(SendAvatarTerseData data) + protected ImprovedTerseObjectUpdatePacket.ObjectDataBlock CreateImprovedTerseBlock(ISceneEntity entity, bool sendTexture) { - return CreateImprovedTerseBlock(true, data.LocalID, 0, data.CollisionPlane, data.Position, data.Velocity, - data.Acceleration, data.Rotation, Vector3.Zero, data.TextureEntry); - } + #region ScenePresence/SOP Handling - protected ImprovedTerseObjectUpdatePacket.ObjectDataBlock CreateImprovedTerseBlock(SendPrimitiveTerseData data) - { - return CreateImprovedTerseBlock(false, data.LocalID, data.AttachPoint, Vector4.Zero, data.Position, data.Velocity, - data.Acceleration, data.Rotation, data.AngularVelocity, data.TextureEntry); - } + bool avatar = (entity is ScenePresence); + uint localID = entity.LocalId; + uint attachPoint; + Vector4 collisionPlane; + Vector3 position, velocity, acceleration, angularVelocity; + Quaternion rotation; + byte[] textureEntry; + + if (entity is ScenePresence) + { + ScenePresence presence = (ScenePresence)entity; + + attachPoint = 0; + collisionPlane = presence.CollisionPlane; + position = presence.OffsetPosition; + velocity = presence.Velocity; + acceleration = Vector3.Zero; + angularVelocity = Vector3.Zero; + rotation = presence.Rotation; + + if (sendTexture) + textureEntry = presence.Appearance.Texture.GetBytes(); + else + textureEntry = null; + } + else + { + SceneObjectPart part = (SceneObjectPart)entity; + + attachPoint = part.AttachmentPoint; + collisionPlane = Vector4.Zero; + position = part.RelativePosition; + velocity = part.Velocity; + acceleration = part.Acceleration; + angularVelocity = part.AngularVelocity; + rotation = part.RotationOffset; + + if (sendTexture) + textureEntry = part.Shape.TextureEntry; + else + textureEntry = null; + } + + #endregion ScenePresence/SOP Handling - protected ImprovedTerseObjectUpdatePacket.ObjectDataBlock CreateImprovedTerseBlock(bool avatar, uint localID, int attachPoint, - Vector4 collisionPlane, Vector3 position, Vector3 velocity, Vector3 acceleration, Quaternion rotation, - Vector3 angularVelocity, byte[] textureEntry) - { int pos = 0; byte[] data = new byte[(avatar ? 60 : 44)]; @@ -4494,12 +4452,12 @@ namespace OpenSim.Region.ClientStack.LindenUDP return block; } - protected ObjectUpdatePacket.ObjectDataBlock CreateAvatarUpdateBlock(SendAvatarData data) + protected ObjectUpdatePacket.ObjectDataBlock CreateAvatarUpdateBlock(ScenePresence data) { byte[] objectData = new byte[76]; - Vector4.UnitW.ToBytes(objectData, 0); // TODO: Collision plane support - data.Position.ToBytes(objectData, 16); + data.CollisionPlane.ToBytes(objectData, 0); + data.OffsetPosition.ToBytes(objectData, 16); //data.Velocity.ToBytes(objectData, 28); //data.Acceleration.ToBytes(objectData, 40); data.Rotation.ToBytes(objectData, 52); @@ -4509,12 +4467,12 @@ namespace OpenSim.Region.ClientStack.LindenUDP update.Data = Utils.EmptyBytes; update.ExtraParams = new byte[1]; - update.FullID = data.AvatarID; - update.ID = data.AvatarLocalID; + update.FullID = data.UUID; + update.ID = data.LocalId; update.Material = (byte)Material.Flesh; update.MediaURL = Utils.EmptyBytes; - update.NameValue = Utils.StringToBytes("FirstName STRING RW SV " + data.FirstName + "\nLastName STRING RW SV " + - data.LastName + "\nTitle STRING RW SV " + data.GroupTitle); + update.NameValue = Utils.StringToBytes("FirstName STRING RW SV " + data.Firstname + "\nLastName STRING RW SV " + + data.Lastname + "\nTitle STRING RW SV " + data.Grouptitle); update.ObjectData = objectData; update.ParentID = data.ParentID; update.PathCurve = 16; @@ -4523,102 +4481,116 @@ namespace OpenSim.Region.ClientStack.LindenUDP update.PCode = (byte)PCode.Avatar; update.ProfileCurve = 1; update.PSBlock = Utils.EmptyBytes; - update.Scale = new Vector3(0.45f,0.6f,1.9f); + update.Scale = new Vector3(0.45f, 0.6f, 1.9f); update.Text = Utils.EmptyBytes; update.TextColor = new byte[4]; update.TextureAnim = Utils.EmptyBytes; - update.TextureEntry = data.TextureEntry ?? Utils.EmptyBytes; - update.UpdateFlags = (uint)(PrimFlags.Physics | PrimFlags.ObjectModify | PrimFlags.ObjectCopy | PrimFlags.ObjectAnyOwner | PrimFlags.ObjectYouOwner | PrimFlags.ObjectMove | PrimFlags.InventoryEmpty | PrimFlags.ObjectTransfer | PrimFlags.ObjectOwnerModify);//61 + (9 << 8) + (130 << 16) + (16 << 24); // TODO: Replace these numbers with PrimFlags + update.TextureEntry = (data.Appearance.Texture != null) ? data.Appearance.Texture.GetBytes() : Utils.EmptyBytes; + update.UpdateFlags = (uint)( + PrimFlags.Physics | PrimFlags.ObjectModify | PrimFlags.ObjectCopy | PrimFlags.ObjectAnyOwner | + PrimFlags.ObjectYouOwner | PrimFlags.ObjectMove | PrimFlags.InventoryEmpty | PrimFlags.ObjectTransfer | + PrimFlags.ObjectOwnerModify); return update; } - protected ObjectUpdatePacket.ObjectDataBlock CreatePrimUpdateBlock(SendPrimitiveData data) + protected ObjectUpdatePacket.ObjectDataBlock CreatePrimUpdateBlock(SceneObjectPart data, UUID recipientID) { byte[] objectData = new byte[60]; - data.pos.ToBytes(objectData, 0); - data.vel.ToBytes(objectData, 12); - data.acc.ToBytes(objectData, 24); - data.rotation.ToBytes(objectData, 36); - data.rvel.ToBytes(objectData, 48); + data.RelativePosition.ToBytes(objectData, 0); + data.Velocity.ToBytes(objectData, 12); + data.Acceleration.ToBytes(objectData, 24); + data.RotationOffset.ToBytes(objectData, 36); + data.AngularVelocity.ToBytes(objectData, 48); ObjectUpdatePacket.ObjectDataBlock update = new ObjectUpdatePacket.ObjectDataBlock(); - update.ClickAction = (byte)data.clickAction; + update.ClickAction = (byte)data.ClickAction; update.CRC = 0; - update.ExtraParams = data.primShape.ExtraParams ?? Utils.EmptyBytes; - update.FullID = data.objectID; - update.ID = data.localID; + update.ExtraParams = data.Shape.ExtraParams ?? Utils.EmptyBytes; + update.FullID = data.UUID; + update.ID = data.LocalId; //update.JointAxisOrAnchor = Vector3.Zero; // These are deprecated //update.JointPivot = Vector3.Zero; //update.JointType = 0; - update.Material = data.material; + update.Material = data.Material; update.MediaURL = Utils.EmptyBytes; // FIXME: Support this in OpenSim - if (data.attachment) + if (data.IsAttachment) { - update.NameValue = Util.StringToBytes256("AttachItemID STRING RW SV " + data.AssetId); - update.State = (byte)((data.AttachPoint % 16) * 16 + (data.AttachPoint / 16)); + update.NameValue = Util.StringToBytes256("AttachItemID STRING RW SV " + data.FromItemID); + update.State = (byte)((data.AttachmentPoint % 16) * 16 + (data.AttachmentPoint / 16)); } else { update.NameValue = Utils.EmptyBytes; - update.State = data.primShape.State; + update.State = data.Shape.State; } - update.ObjectData = objectData; - update.ParentID = data.parentID; - update.PathBegin = data.primShape.PathBegin; - update.PathCurve = data.primShape.PathCurve; - update.PathEnd = data.primShape.PathEnd; - update.PathRadiusOffset = data.primShape.PathRadiusOffset; - update.PathRevolutions = data.primShape.PathRevolutions; - update.PathScaleX = data.primShape.PathScaleX; - update.PathScaleY = data.primShape.PathScaleY; - update.PathShearX = data.primShape.PathShearX; - update.PathShearY = data.primShape.PathShearY; - update.PathSkew = data.primShape.PathSkew; - update.PathTaperX = data.primShape.PathTaperX; - update.PathTaperY = data.primShape.PathTaperY; - update.PathTwist = data.primShape.PathTwist; - update.PathTwistBegin = data.primShape.PathTwistBegin; - update.PCode = data.primShape.PCode; - update.ProfileBegin = data.primShape.ProfileBegin; - update.ProfileCurve = data.primShape.ProfileCurve; - update.ProfileEnd = data.primShape.ProfileEnd; - update.ProfileHollow = data.primShape.ProfileHollow; - update.PSBlock = data.particleSystem ?? Utils.EmptyBytes; - update.TextColor = data.color ?? Color4.Black.GetBytes(true); - update.TextureAnim = data.textureanim ?? Utils.EmptyBytes; - update.TextureEntry = data.primShape.TextureEntry ?? Utils.EmptyBytes; - update.Scale = data.primShape.Scale; - update.Text = Util.StringToBytes256(data.text); - update.UpdateFlags = (uint)data.flags; - if (data.SoundId != UUID.Zero) + update.ObjectData = objectData; + update.ParentID = data.ParentID; + update.PathBegin = data.Shape.PathBegin; + update.PathCurve = data.Shape.PathCurve; + update.PathEnd = data.Shape.PathEnd; + update.PathRadiusOffset = data.Shape.PathRadiusOffset; + update.PathRevolutions = data.Shape.PathRevolutions; + update.PathScaleX = data.Shape.PathScaleX; + update.PathScaleY = data.Shape.PathScaleY; + update.PathShearX = data.Shape.PathShearX; + update.PathShearY = data.Shape.PathShearY; + update.PathSkew = data.Shape.PathSkew; + update.PathTaperX = data.Shape.PathTaperX; + update.PathTaperY = data.Shape.PathTaperY; + update.PathTwist = data.Shape.PathTwist; + update.PathTwistBegin = data.Shape.PathTwistBegin; + update.PCode = data.Shape.PCode; + update.ProfileBegin = data.Shape.ProfileBegin; + update.ProfileCurve = data.Shape.ProfileCurve; + update.ProfileEnd = data.Shape.ProfileEnd; + update.ProfileHollow = data.Shape.ProfileHollow; + update.PSBlock = data.ParticleSystem ?? Utils.EmptyBytes; + update.TextColor = data.GetTextColor().GetBytes(false); + update.TextureAnim = data.TextureAnimation ?? Utils.EmptyBytes; + update.TextureEntry = data.Shape.TextureEntry ?? Utils.EmptyBytes; + update.Scale = data.Shape.Scale; + update.Text = Util.StringToBytes256(data.Text); + + #region PrimFlags + + PrimFlags flags = (PrimFlags)m_scene.Permissions.GenerateClientFlags(recipientID, data.UUID); + + // Don't send the CreateSelected flag to everyone + flags &= ~PrimFlags.CreateSelected; + + if (recipientID == data.OwnerID) { - update.Sound = data.SoundId; - update.OwnerID = data.ownerID; - update.Gain = (float)data.SoundVolume; + if (data.CreateSelected) + { + // Only send this flag once, then unset it + flags |= PrimFlags.CreateSelected; + data.CreateSelected = false; + } + } + + update.UpdateFlags = (uint)flags; + + #endregion PrimFlags + + if (data.Sound != UUID.Zero) + { + update.Sound = data.Sound; + update.OwnerID = data.OwnerID; + update.Gain = (float)data.SoundGain; update.Radius = (float)data.SoundRadius; update.Flags = data.SoundFlags; } - switch ((PCode)data.primShape.PCode) + switch ((PCode)data.Shape.PCode) { case PCode.Grass: case PCode.Tree: case PCode.NewTree: - update.Data = new byte[] { data.primShape.State }; + update.Data = new byte[] { data.Shape.State }; break; default: - // TODO: Support ScratchPad - //if (prim.ScratchPad != null) - //{ - // update.Data = new byte[prim.ScratchPad.Length]; - // Buffer.BlockCopy(prim.ScratchPad, 0, update.Data, 0, update.Data.Length); - //} - //else - //{ - // update.Data = Utils.EmptyBytes; - //} update.Data = Utils.EmptyBytes; break; } @@ -4626,6 +4598,12 @@ namespace OpenSim.Region.ClientStack.LindenUDP return update; } + protected ObjectUpdateCompressedPacket.ObjectDataBlock CreateCompressedUpdateBlock(SceneObjectPart part, PrimUpdateFlags updateFlags) + { + // TODO: Implement this + return null; + } + public void SendNameReply(UUID profileId, string firstname, string lastname) { UUIDNameReplyPacket packet = (UUIDNameReplyPacket)PacketPool.Instance.GetPacket(PacketType.UUIDNameReply); @@ -4932,8 +4910,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP (x.AgentID != lastarg.AgentID) ? "X" : " "); } * */ - - // save this set of arguments for next time m_lastAgentUpdate = xb; @@ -4961,10 +4937,14 @@ namespace OpenSim.Region.ClientStack.LindenUDP arg.SessionID = x.SessionID; arg.State = x.State; + UpdateAgent handlerPreAgentUpdate = OnPreAgentUpdate; UpdateAgent handlerAgentUpdate = OnAgentUpdate; + if (handlerPreAgentUpdate != null) + OnPreAgentUpdate(this, arg); if (handlerAgentUpdate != null) OnAgentUpdate(this, arg); + handlerPreAgentUpdate = null; handlerAgentUpdate = null; } @@ -6185,7 +6165,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP DelinkObjects handlerDelinkObjects = OnDelinkObjects; if (handlerDelinkObjects != null) { - handlerDelinkObjects(prims); + handlerDelinkObjects(prims, this); } return true; @@ -11612,26 +11592,26 @@ namespace OpenSim.Region.ClientStack.LindenUDP } #region PriorityQueue - public class PriorityQueue + public class PriorityQueue { - internal delegate bool UpdatePriorityHandler(ref TPriority priority, uint local_id); + internal delegate bool UpdatePriorityHandler(ref double priority, uint local_id); private MinHeap[] m_heaps = new MinHeap[1]; private Dictionary m_lookupTable; - private Comparison m_comparison; + private Comparison m_comparison; private object m_syncRoot = new object(); internal PriorityQueue() : - this(MinHeap.DEFAULT_CAPACITY, Comparer.Default) { } + this(MinHeap.DEFAULT_CAPACITY, Comparer.Default) { } internal PriorityQueue(int capacity) : - this(capacity, Comparer.Default) { } - internal PriorityQueue(IComparer comparer) : - this(new Comparison(comparer.Compare)) { } - internal PriorityQueue(Comparison comparison) : + this(capacity, Comparer.Default) { } + internal PriorityQueue(IComparer comparer) : + this(new Comparison(comparer.Compare)) { } + internal PriorityQueue(Comparison comparison) : this(MinHeap.DEFAULT_CAPACITY, comparison) { } - internal PriorityQueue(int capacity, IComparer comparer) : - this(capacity, new Comparison(comparer.Compare)) { } - internal PriorityQueue(int capacity, Comparison comparison) + internal PriorityQueue(int capacity, IComparer comparer) : + this(capacity, new Comparison(comparer.Compare)) { } + internal PriorityQueue(int capacity, Comparison comparison) { m_lookupTable = new Dictionary(capacity); @@ -11652,12 +11632,15 @@ namespace OpenSim.Region.ClientStack.LindenUDP } } - public bool Enqueue(TPriority priority, TValue value, uint local_id) + public bool Enqueue(double priority, EntityUpdate value, uint local_id) { LookupItem item; if (m_lookupTable.TryGetValue(local_id, out item)) { + // Combine flags + value.Flags |= item.Heap[item.Handle].Value.Flags; + item.Heap[item.Handle] = new MinHeapItem(priority, value, local_id, this.m_comparison); return false; } @@ -11670,7 +11653,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP } } - internal TValue Peek() + internal EntityUpdate Peek() { for (int i = 0; i < m_heaps.Length; ++i) if (m_heaps[i].Count > 0) @@ -11678,7 +11661,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP throw new InvalidOperationException(string.Format("The {0} is empty", this.GetType().ToString())); } - internal TValue Dequeue() + internal bool TryDequeue(out EntityUpdate value) { for (int i = 0; i < m_heaps.Length; ++i) { @@ -11686,16 +11669,19 @@ namespace OpenSim.Region.ClientStack.LindenUDP { MinHeapItem item = m_heaps[i].RemoveMin(); m_lookupTable.Remove(item.LocalID); - return item.Value; + value = item.Value; + return true; } } - throw new InvalidOperationException(string.Format("The {0} is empty", this.GetType().ToString())); + + value = default(EntityUpdate); + return false; } internal void Reprioritize(UpdatePriorityHandler handler) { MinHeapItem item; - TPriority priority; + double priority; foreach (LookupItem lookup in new List(this.m_lookupTable.Values)) { @@ -11721,16 +11707,16 @@ namespace OpenSim.Region.ClientStack.LindenUDP #region MinHeapItem private struct MinHeapItem : IComparable { - private TPriority priority; - private TValue value; + private double priority; + private EntityUpdate value; private uint local_id; - private Comparison comparison; + private Comparison comparison; - internal MinHeapItem(TPriority priority, TValue value, uint local_id) : - this(priority, value, local_id, Comparer.Default) { } - internal MinHeapItem(TPriority priority, TValue value, uint local_id, IComparer comparer) : - this(priority, value, local_id, new Comparison(comparer.Compare)) { } - internal MinHeapItem(TPriority priority, TValue value, uint local_id, Comparison comparison) + internal MinHeapItem(double priority, EntityUpdate value, uint local_id) : + this(priority, value, local_id, Comparer.Default) { } + internal MinHeapItem(double priority, EntityUpdate value, uint local_id, IComparer comparer) : + this(priority, value, local_id, new Comparison(comparer.Compare)) { } + internal MinHeapItem(double priority, EntityUpdate value, uint local_id, Comparison comparison) { this.priority = priority; this.value = value; @@ -11738,8 +11724,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP this.comparison = comparison; } - internal TPriority Priority { get { return this.priority; } } - internal TValue Value { get { return this.value; } } + internal double Priority { get { return this.priority; } } + internal EntityUpdate Value { get { return this.value; } } internal uint LocalID { get { return this.local_id; } } public override string ToString() @@ -11854,4 +11840,4 @@ namespace OpenSim.Region.ClientStack.LindenUDP OutPacket(dialog, ThrottleOutPacketType.Task); } } -} \ No newline at end of file +} diff --git a/OpenSim/Region/ClientStack/LindenUDP/LLUDPServer.cs b/OpenSim/Region/ClientStack/LindenUDP/LLUDPServer.cs index 41e41e47a7..1b81105248 100644 --- a/OpenSim/Region/ClientStack/LindenUDP/LLUDPServer.cs +++ b/OpenSim/Region/ClientStack/LindenUDP/LLUDPServer.cs @@ -99,15 +99,9 @@ namespace OpenSim.Region.ClientStack.LindenUDP /// The measured resolution of Environment.TickCount public readonly float TickCountResolution; - /// Number of terse prim updates to put on the queue each time the + /// Number of prim updates to put on the queue each time the /// OnQueueEmpty event is triggered for updates - public readonly int PrimTerseUpdatesPerPacket; - /// Number of terse avatar updates to put on the queue each time the - /// OnQueueEmpty event is triggered for updates - public readonly int AvatarTerseUpdatesPerPacket; - /// Number of full prim updates to put on the queue each time the - /// OnQueueEmpty event is triggered for updates - public readonly int PrimFullUpdatesPerPacket; + public readonly int PrimUpdatesPerCallback; /// Number of texture packets to put on the queue each time the /// OnQueueEmpty event is triggered for textures public readonly int TextureSendLimit; @@ -191,9 +185,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP m_recvBufferSize = config.GetInt("client_socket_rcvbuf_size", 0); sceneThrottleBps = config.GetInt("scene_throttle_max_bps", 0); - PrimTerseUpdatesPerPacket = config.GetInt("PrimTerseUpdatesPerPacket", 25); - AvatarTerseUpdatesPerPacket = config.GetInt("AvatarTerseUpdatesPerPacket", 10); - PrimFullUpdatesPerPacket = config.GetInt("PrimFullUpdatesPerPacket", 100); + PrimUpdatesPerCallback = config.GetInt("PrimUpdatesPerCallback", 100); TextureSendLimit = config.GetInt("TextureSendLimit", 20); m_defaultRTO = config.GetInt("DefaultRTO", 0); @@ -201,9 +193,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP } else { - PrimTerseUpdatesPerPacket = 25; - AvatarTerseUpdatesPerPacket = 10; - PrimFullUpdatesPerPacket = 100; + PrimUpdatesPerCallback = 100; TextureSendLimit = 20; } diff --git a/OpenSim/Region/CoreModules/Agent/Capabilities/CapabilitiesModule.cs b/OpenSim/Region/CoreModules/Agent/Capabilities/CapabilitiesModule.cs index 2a1355b9ef..a6f5d97ad2 100644 --- a/OpenSim/Region/CoreModules/Agent/Capabilities/CapabilitiesModule.cs +++ b/OpenSim/Region/CoreModules/Agent/Capabilities/CapabilitiesModule.cs @@ -107,7 +107,7 @@ namespace OpenSim.Region.CoreModules.Agent.Capabilities } Caps caps - = new Caps( + = new Caps(m_scene, m_scene.AssetService, MainServer.Instance, m_scene.RegionInfo.ExternalHostName, MainServer.Instance.Port, capsObjectPath, agentId, m_scene.DumpAssetsToFile, m_scene.RegionInfo.RegionName); diff --git a/OpenSim/Region/CoreModules/Avatar/Assets/GetTextureModule.cs b/OpenSim/Region/CoreModules/Avatar/Assets/GetTextureModule.cs index 53d2cefeac..f8e3d595c9 100644 --- a/OpenSim/Region/CoreModules/Avatar/Assets/GetTextureModule.cs +++ b/OpenSim/Region/CoreModules/Avatar/Assets/GetTextureModule.cs @@ -121,6 +121,7 @@ namespace OpenSim.Region.CoreModules.Avatar.ObjectCaps UUID textureID; if (!String.IsNullOrEmpty(textureStr) && UUID.TryParse(textureStr, out textureID)) { + //m_log.DebugFormat("[GETTEXTURE]: {0}", textureID); AssetBase texture; if (!String.IsNullOrEmpty(REDIRECT_URL)) @@ -167,6 +168,7 @@ namespace OpenSim.Region.CoreModules.Avatar.ObjectCaps private void SendTexture(OSHttpRequest request, OSHttpResponse response, AssetBase texture) { string range = request.Headers.GetOne("Range"); + //m_log.DebugFormat("[GETTEXTURE]: Range {0}", range); if (!String.IsNullOrEmpty(range)) { // Range request diff --git a/OpenSim/Region/CoreModules/Avatar/Chat/ChatModule.cs b/OpenSim/Region/CoreModules/Avatar/Chat/ChatModule.cs index 6dacbba0df..02f0968c40 100644 --- a/OpenSim/Region/CoreModules/Avatar/Chat/ChatModule.cs +++ b/OpenSim/Region/CoreModules/Avatar/Chat/ChatModule.cs @@ -264,6 +264,10 @@ namespace OpenSim.Region.CoreModules.Avatar.Chat fromName = avatar.Name; sourceType = ChatSourceType.Agent; } + else if (c.SenderUUID != UUID.Zero) + { + fromID = c.SenderUUID; + } // m_log.DebugFormat("[CHAT] Broadcast: fromID {0} fromName {1}, cType {2}, sType {3}", fromID, fromName, cType, sourceType); diff --git a/OpenSim/Region/CoreModules/Avatar/Combat/CombatModule.cs b/OpenSim/Region/CoreModules/Avatar/Combat/CombatModule.cs index 9df60743ae..a895d6e838 100644 --- a/OpenSim/Region/CoreModules/Avatar/Combat/CombatModule.cs +++ b/OpenSim/Region/CoreModules/Avatar/Combat/CombatModule.cs @@ -143,10 +143,11 @@ namespace OpenSim.Region.CoreModules.Avatar.Combat.CombatModule } private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, UUID regionID) - { - ILandObject obj = avatar.Scene.LandChannel.GetLandObject(avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y); + { try { + ILandObject obj = avatar.Scene.LandChannel.GetLandObject(avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y); + if ((obj.LandData.Flags & (uint)ParcelFlags.AllowDamage) != 0) { avatar.Invulnerable = false; diff --git a/OpenSim/Region/CoreModules/Avatar/Dialog/DialogModule.cs b/OpenSim/Region/CoreModules/Avatar/Dialog/DialogModule.cs index c31266c0e1..b5c3176d8e 100644 --- a/OpenSim/Region/CoreModules/Avatar/Dialog/DialogModule.cs +++ b/OpenSim/Region/CoreModules/Avatar/Dialog/DialogModule.cs @@ -81,14 +81,14 @@ namespace OpenSim.Region.CoreModules.Avatar.Dialog { ScenePresence sp = m_scene.GetScenePresence(agentID); - if (sp != null) + if (sp != null && !sp.IsChildAgent) sp.ControllingClient.SendAgentAlertMessage(message, modal); } public void SendAlertToUser(string firstName, string lastName, string message, bool modal) { ScenePresence presence = m_scene.GetScenePresence(firstName, lastName); - if(presence != null) + if (presence != null && !presence.IsChildAgent) presence.ControllingClient.SendAgentAlertMessage(message, modal); } @@ -119,7 +119,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Dialog } ScenePresence sp = m_scene.GetScenePresence(avatarID); - if (sp != null) + if (sp != null && !sp.IsChildAgent) sp.ControllingClient.SendDialog(objectName, objectID, ownerFirstName, ownerLastName, message, textureID, ch, buttonlabels); } @@ -128,21 +128,13 @@ namespace OpenSim.Region.CoreModules.Avatar.Dialog { ScenePresence sp = m_scene.GetScenePresence(avatarID); - if (sp != null) + if (sp != null && !sp.IsChildAgent) sp.ControllingClient.SendLoadURL(objectName, objectID, ownerID, groupOwned, message, url); } - public void SendNotificationToUsersInEstate( - UUID fromAvatarID, string fromAvatarName, string message) - { - // TODO: This does not yet do what it says on the tin - it only sends the message to users in the same - // region as the sending avatar. - SendNotificationToUsersInRegion(fromAvatarID, fromAvatarName, message); - } - public void SendTextBoxToUser(UUID avatarid, string message, int chatChannel, string name, UUID objectid, UUID ownerid) { - UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, ownerid); + UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, ownerid); string ownerFirstName, ownerLastName; if (account != null) { @@ -155,12 +147,10 @@ namespace OpenSim.Region.CoreModules.Avatar.Dialog ownerLastName = "user)"; } - ScenePresence sp = m_scene.GetScenePresence(avatarid); - if (sp != null) { + if (sp != null && !sp.IsChildAgent) sp.ControllingClient.SendTextBoxRequest(message, chatChannel, name, ownerFirstName, ownerLastName, objectid); - } } public void SendNotificationToUsersInRegion( @@ -215,4 +205,4 @@ namespace OpenSim.Region.CoreModules.Avatar.Dialog return result; } } -} +} \ No newline at end of file diff --git a/OpenSim/Region/CoreModules/Avatar/Friends/FriendsModule.cs b/OpenSim/Region/CoreModules/Avatar/Friends/FriendsModule.cs index 312db38ed0..0c81f446f1 100644 --- a/OpenSim/Region/CoreModules/Avatar/Friends/FriendsModule.cs +++ b/OpenSim/Region/CoreModules/Avatar/Friends/FriendsModule.cs @@ -149,7 +149,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends if (m_FriendsService == null) { - m_log.Error("[FRIENDS]: No Connector defined in section Friends, or filed to load, cannot continue"); + m_log.Error("[FRIENDS]: No Connector defined in section Friends, or failed to load, cannot continue"); throw new Exception("Connector load error"); } @@ -345,8 +345,10 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(client.Scene.RegionInfo.ScopeID, new UUID(im.fromAgentID)); im.fromAgentName = account.FirstName + " " + account.LastName; + PresenceInfo presence = null; PresenceInfo[] presences = PresenceService.GetAgents(new string[] { fid }); - PresenceInfo presence = PresenceInfo.GetOnlinePresence(presences); + if (presences != null && presences.Length > 0) + presence = presences[0]; if (presence != null) im.offline = 0; @@ -365,6 +367,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends List GetOnlineFriends(UUID userID) { List friendList = new List(); + List online = new List(); foreach (FriendInfo fi in m_Friends[userID].Friends) { @@ -372,18 +375,15 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends friendList.Add(fi.Friend); } + if (friendList.Count == 0) + // no friends whatsoever + return online; + PresenceInfo[] presence = PresenceService.GetAgents(friendList.ToArray()); - List online = new List(); - foreach (PresenceInfo pi in presence) - { - if (pi.Online) - { - online.Add(new UUID(pi.UserID)); - //m_log.DebugFormat("[XXX] {0} friend online {1}", userID, pi.UserID); - } - } + online.Add(new UUID(pi.UserID)); + //m_log.DebugFormat("[XXX] {0} friend online {1}", userID, pi.UserID); return online; } @@ -459,11 +459,14 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends // The friend is not here [as root]. Let's forward. PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() }); - PresenceInfo friendSession = PresenceInfo.GetOnlinePresence(friendSessions); - if (friendSession != null) + if (friendSessions != null && friendSessions.Length > 0) { - GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID); - m_FriendsSimConnector.StatusNotify(region, userID, friendID, online); + PresenceInfo friendSession = friendSessions[0]; + if (friendSession != null) + { + GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID); + m_FriendsSimConnector.StatusNotify(region, userID, friendID, online); + } } // Friend is not online. Ignore. @@ -501,13 +504,15 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends // The prospective friend is not here [as root]. Let's forward. PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() }); - PresenceInfo friendSession = PresenceInfo.GetOnlinePresence(friendSessions); - if (friendSession != null) + if (friendSessions != null && friendSessions.Length > 0) { - GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID); - m_FriendsSimConnector.FriendshipOffered(region, agentID, friendID, im.message); + PresenceInfo friendSession = friendSessions[0]; + if (friendSession != null) + { + GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID); + m_FriendsSimConnector.FriendshipOffered(region, agentID, friendID, im.message); + } } - // If the prospective friend is not online, he'll get the message upon login. } @@ -533,14 +538,16 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends // The friend is not here PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() }); - PresenceInfo friendSession = PresenceInfo.GetOnlinePresence(friendSessions); - if (friendSession != null) + if (friendSessions != null && friendSessions.Length > 0) { - GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID); - m_FriendsSimConnector.FriendshipApproved(region, agentID, client.Name, friendID); - client.SendAgentOnline(new UUID[] { friendID }); + PresenceInfo friendSession = friendSessions[0]; + if (friendSession != null) + { + GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID); + m_FriendsSimConnector.FriendshipApproved(region, agentID, client.Name, friendID); + client.SendAgentOnline(new UUID[] { friendID }); + } } - } private void OnDenyFriendRequest(IClientAPI client, UUID agentID, UUID friendID, List callingCardFolders) @@ -559,11 +566,14 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends return; PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() }); - PresenceInfo friendSession = PresenceInfo.GetOnlinePresence(friendSessions); - if (friendSession != null) + if (friendSessions != null && friendSessions.Length > 0) { - GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID); - m_FriendsSimConnector.FriendshipDenied(region, agentID, client.Name, friendID); + PresenceInfo friendSession = friendSessions[0]; + if (friendSession != null) + { + GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID); + m_FriendsSimConnector.FriendshipDenied(region, agentID, client.Name, friendID); + } } } @@ -586,11 +596,14 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends return; PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { exfriendID.ToString() }); - PresenceInfo friendSession = PresenceInfo.GetOnlinePresence(friendSessions); - if (friendSession != null) + if (friendSessions != null && friendSessions.Length > 0) { - GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID); - m_FriendsSimConnector.FriendshipTerminated(region, agentID, exfriendID); + PresenceInfo friendSession = friendSessions[0]; + if (friendSession != null) + { + GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID); + m_FriendsSimConnector.FriendshipTerminated(region, agentID, exfriendID); + } } } @@ -628,13 +641,16 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends return; PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { target.ToString() }); - PresenceInfo friendSession = PresenceInfo.GetOnlinePresence(friendSessions); - if (friendSession != null) + if (friendSessions != null && friendSessions.Length > 0) { - GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID); - // TODO: You might want to send the delta to save the lookup - // on the other end!! - m_FriendsSimConnector.GrantRights(region, requester, target, myFlags, rights); + PresenceInfo friendSession = friendSessions[0]; + if (friendSession != null) + { + GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID); + // TODO: You might want to send the delta to save the lookup + // on the other end!! + m_FriendsSimConnector.GrantRights(region, requester, target, myFlags, rights); + } } } } diff --git a/OpenSim/Region/CoreModules/Avatar/InstantMessage/MessageTransferModule.cs b/OpenSim/Region/CoreModules/Avatar/InstantMessage/MessageTransferModule.cs index ad050a1410..5d20e63646 100644 --- a/OpenSim/Region/CoreModules/Avatar/InstantMessage/MessageTransferModule.cs +++ b/OpenSim/Region/CoreModules/Avatar/InstantMessage/MessageTransferModule.cs @@ -471,7 +471,6 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage if (m_UserRegionMap.ContainsKey(toAgentID)) { upd = new PresenceInfo(); - upd.Online = true; upd.RegionID = m_UserRegionMap[toAgentID]; // We need to compare the current regionhandle with the previous region handle @@ -493,15 +492,8 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage { // Non-cached user agent lookup. PresenceInfo[] presences = PresenceService.GetAgents(new string[] { toAgentID.ToString() }); - if (presences != null) - { - foreach (PresenceInfo p in presences) - if (p.Online) - { - upd = presences[0]; - break; - } - } + if (presences != null && presences.Length > 0) + upd = presences[0]; if (upd != null) { @@ -525,61 +517,53 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage if (upd != null) { - if (upd.Online) + GridRegion reginfo = m_Scenes[0].GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, + upd.RegionID); + if (reginfo != null) { - GridRegion reginfo = m_Scenes[0].GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, - upd.RegionID); - if (reginfo != null) + Hashtable msgdata = ConvertGridInstantMessageToXMLRPC(im); + // Not actually used anymore, left in for compatibility + // Remove at next interface change + // + msgdata["region_handle"] = 0; + bool imresult = doIMSending(reginfo, msgdata); + if (imresult) { - Hashtable msgdata = ConvertGridInstantMessageToXMLRPC(im); - // Not actually used anymore, left in for compatibility - // Remove at next interface change - // - msgdata["region_handle"] = 0; - bool imresult = doIMSending(reginfo, msgdata); - if (imresult) + // IM delivery successful, so store the Agent's location in our local cache. + lock (m_UserRegionMap) { - // IM delivery successful, so store the Agent's location in our local cache. - lock (m_UserRegionMap) + if (m_UserRegionMap.ContainsKey(toAgentID)) { - if (m_UserRegionMap.ContainsKey(toAgentID)) - { - m_UserRegionMap[toAgentID] = upd.RegionID; - } - else - { - m_UserRegionMap.Add(toAgentID, upd.RegionID); - } + m_UserRegionMap[toAgentID] = upd.RegionID; + } + else + { + m_UserRegionMap.Add(toAgentID, upd.RegionID); } - result(true); - } - else - { - // try again, but lookup user this time. - // Warning, this must call the Async version - // of this method or we'll be making thousands of threads - // The version within the spawned thread is SendGridInstantMessageViaXMLRPCAsync - // The version that spawns the thread is SendGridInstantMessageViaXMLRPC - - // This is recursive!!!!! - SendGridInstantMessageViaXMLRPCAsync(im, result, - upd.RegionID); } + result(true); } else { - m_log.WarnFormat("[GRID INSTANT MESSAGE]: Unable to find region {0}", upd.RegionID); - HandleUndeliveredMessage(im, result); + // try again, but lookup user this time. + // Warning, this must call the Async version + // of this method or we'll be making thousands of threads + // The version within the spawned thread is SendGridInstantMessageViaXMLRPCAsync + // The version that spawns the thread is SendGridInstantMessageViaXMLRPC + + // This is recursive!!!!! + SendGridInstantMessageViaXMLRPCAsync(im, result, + upd.RegionID); } } else { + m_log.WarnFormat("[GRID INSTANT MESSAGE]: Unable to find region {0}", upd.RegionID); HandleUndeliveredMessage(im, result); } } else { - m_log.WarnFormat("[GRID INSTANT MESSAGE]: Unable to find user {0}", toAgentID); HandleUndeliveredMessage(im, result); } } diff --git a/OpenSim/Region/CoreModules/Avatar/InstantMessage/PresenceModule.cs b/OpenSim/Region/CoreModules/Avatar/InstantMessage/PresenceModule.cs index bafad827a6..dd17f3c26b 100644 --- a/OpenSim/Region/CoreModules/Avatar/InstantMessage/PresenceModule.cs +++ b/OpenSim/Region/CoreModules/Avatar/InstantMessage/PresenceModule.cs @@ -133,20 +133,14 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage foreach (PresenceInfo pi in status) { UUID uuid = new UUID(pi.UserID); - if (pi.Online) - { - if (!online.Contains(uuid)) - { - online.Add(uuid); - if (offline.Contains(uuid)) - offline.Remove(uuid); - } - } - else - { - if (!online.Contains(uuid) && !offline.Contains(uuid)) - offline.Add(uuid); - } + if (!online.Contains(uuid)) + online.Add(uuid); + } + foreach (string s in args) + { + UUID uuid = new UUID(s); + if (!online.Contains(uuid) && !offline.Contains(uuid)) + offline.Add(uuid); } if (online.Count > 0) diff --git a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveReadRequest.cs b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveReadRequest.cs index dc7439c6da..806aa4f155 100644 --- a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveReadRequest.cs +++ b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveReadRequest.cs @@ -37,7 +37,6 @@ using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; - using OpenSim.Framework.Communications.Osp; using OpenSim.Framework.Serialization; using OpenSim.Framework.Serialization.External; @@ -72,7 +71,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver scene, userInfo, invPath, - new GZipStream(new FileStream(loadPath, FileMode.Open), CompressionMode.Decompress)) + new GZipStream(ArchiveHelpers.GetStream(loadPath), CompressionMode.Decompress)) { } diff --git a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveWriteRequest.cs b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveWriteRequest.cs index cfe3caa849..8f3f65b0b6 100644 --- a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveWriteRequest.cs +++ b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveWriteRequest.cs @@ -37,7 +37,6 @@ using OpenSim.Framework; using OpenSim.Framework.Serialization; using OpenSim.Framework.Serialization.External; using OpenSim.Framework.Communications; - using OpenSim.Framework.Communications.Osp; using OpenSim.Region.CoreModules.World.Archiver; using OpenSim.Region.Framework.Scenes; diff --git a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiverModule.cs b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiverModule.cs index f57099912c..307db974b8 100644 --- a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiverModule.cs +++ b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiverModule.cs @@ -91,13 +91,26 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver scene.AddCommand( this, "load iar", - "load iar []", - "Load user inventory archive.", HandleLoadInvConsoleCommand); + "load iar []", + "Load user inventory archive (IAR).", + " is user's first name." + Environment.NewLine + + " is user's last name." + Environment.NewLine + + " is the path inside the user's inventory where the IAR should be loaded." + Environment.NewLine + + " is the user's password." + Environment.NewLine + + " is the filesystem path or URI from which to load the IAR." + + string.Format(" If this is not given then the filename {0} in the current directory is used", DEFAULT_INV_BACKUP_FILENAME), + HandleLoadInvConsoleCommand); scene.AddCommand( this, "save iar", - "save iar []", - "Save user inventory archive.", HandleSaveInvConsoleCommand); + "save iar []", + "Save user inventory archive (IAR).", + " is the user's first name." + Environment.NewLine + + " is the user's last name." + Environment.NewLine + + " is the path inside the user's inventory for the folder/item to be saved." + Environment.NewLine + + " is the filesystem path at which to save the IAR." + + string.Format(" If this is not given then the filename {0} in the current directory is used", DEFAULT_INV_BACKUP_FILENAME), + HandleSaveInvConsoleCommand); m_aScene = scene; } diff --git a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/Tests/InventoryArchiverTests.cs b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/Tests/InventoryArchiverTests.cs index 9c95e78f49..c81f295d8c 100644 --- a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/Tests/InventoryArchiverTests.cs +++ b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/Tests/InventoryArchiverTests.cs @@ -38,7 +38,6 @@ using OpenSim.Framework; using OpenSim.Framework.Serialization; using OpenSim.Framework.Serialization.External; using OpenSim.Framework.Communications; - using OpenSim.Framework.Communications.Osp; using OpenSim.Region.CoreModules.Avatar.Inventory.Archiver; using OpenSim.Region.CoreModules.World.Serialiser; @@ -77,125 +76,118 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests // Commenting for now! The mock inventory service needs more beef, at least for // GetFolderForType // REFACTORING PROBLEM. This needs to be rewritten. + //[Test] + public void TestSaveIarV0_1() + { + TestHelper.InMethod(); + log4net.Config.XmlConfigurator.Configure(); -// [Test] -// public void TestSaveIarV0_1() -// { -// TestHelper.InMethod(); -// //log4net.Config.XmlConfigurator.Configure(); + InventoryArchiverModule archiverModule = new InventoryArchiverModule(true); -// InventoryArchiverModule archiverModule = new InventoryArchiverModule(true); + Scene scene = SceneSetupHelpers.SetupScene("Inventory"); + SceneSetupHelpers.SetupSceneModules(scene, archiverModule); -// Scene scene = SceneSetupHelpers.SetupScene("Inventory"); -// SceneSetupHelpers.SetupSceneModules(scene, archiverModule); -// CommunicationsManager cm = scene.CommsManager; - -// // Create user -// string userFirstName = "Jock"; -// string userLastName = "Stirrup"; -// UUID userId = UUID.Parse("00000000-0000-0000-0000-000000000020"); - -// lock (this) -// { -// UserProfileTestUtils.CreateUserWithInventory( -// cm, userFirstName, userLastName, userId, InventoryReceived); -// Monitor.Wait(this, 60000); -// } + // Create user + string userFirstName = "Jock"; + string userLastName = "Stirrup"; + string userPassword = "troll"; + UUID userId = UUID.Parse("00000000-0000-0000-0000-000000000020"); + UserProfileTestUtils.CreateUserWithInventory(scene, userFirstName, userLastName, userId, userPassword); -// // Create asset -// SceneObjectGroup object1; -// SceneObjectPart part1; -// { -// string partName = "My Little Dog Object"; -// UUID ownerId = UUID.Parse("00000000-0000-0000-0000-000000000040"); -// PrimitiveBaseShape shape = PrimitiveBaseShape.CreateSphere(); -// Vector3 groupPosition = new Vector3(10, 20, 30); -// Quaternion rotationOffset = new Quaternion(20, 30, 40, 50); -// Vector3 offsetPosition = new Vector3(5, 10, 15); + // Create asset + SceneObjectGroup object1; + SceneObjectPart part1; + { + string partName = "My Little Dog Object"; + UUID ownerId = UUID.Parse("00000000-0000-0000-0000-000000000040"); + PrimitiveBaseShape shape = PrimitiveBaseShape.CreateSphere(); + Vector3 groupPosition = new Vector3(10, 20, 30); + Quaternion rotationOffset = new Quaternion(20, 30, 40, 50); + Vector3 offsetPosition = new Vector3(5, 10, 15); -// part1 -// = new SceneObjectPart( -// ownerId, shape, groupPosition, rotationOffset, offsetPosition); -// part1.Name = partName; + part1 + = new SceneObjectPart( + ownerId, shape, groupPosition, rotationOffset, offsetPosition); + part1.Name = partName; -// object1 = new SceneObjectGroup(part1); -// scene.AddNewSceneObject(object1, false); -// } + object1 = new SceneObjectGroup(part1); + scene.AddNewSceneObject(object1, false); + } -// UUID asset1Id = UUID.Parse("00000000-0000-0000-0000-000000000060"); -// AssetBase asset1 = AssetHelpers.CreateAsset(asset1Id, object1); -// scene.AssetService.Store(asset1); + UUID asset1Id = UUID.Parse("00000000-0000-0000-0000-000000000060"); + AssetBase asset1 = AssetHelpers.CreateAsset(asset1Id, object1); + scene.AssetService.Store(asset1); -// // Create item -// UUID item1Id = UUID.Parse("00000000-0000-0000-0000-000000000080"); -// InventoryItemBase item1 = new InventoryItemBase(); -// item1.Name = "My Little Dog"; -// item1.AssetID = asset1.FullID; -// item1.ID = item1Id; -// InventoryFolderBase objsFolder -// = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, userId, "Objects"); -// item1.Folder = objsFolder.ID; -// scene.AddInventoryItem(userId, item1); + // Create item + UUID item1Id = UUID.Parse("00000000-0000-0000-0000-000000000080"); + InventoryItemBase item1 = new InventoryItemBase(); + item1.Name = "My Little Dog"; + item1.AssetID = asset1.FullID; + item1.ID = item1Id; + InventoryFolderBase objsFolder + = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, userId, "Objects"); + item1.Folder = objsFolder.ID; + scene.AddInventoryItem(userId, item1); -// MemoryStream archiveWriteStream = new MemoryStream(); -// archiverModule.OnInventoryArchiveSaved += SaveCompleted; + MemoryStream archiveWriteStream = new MemoryStream(); + archiverModule.OnInventoryArchiveSaved += SaveCompleted; -// mre.Reset(); -// archiverModule.ArchiveInventory( -// Guid.NewGuid(), userFirstName, userLastName, "Objects", "troll", archiveWriteStream); -// mre.WaitOne(60000, false); + mre.Reset(); + archiverModule.ArchiveInventory( + Guid.NewGuid(), userFirstName, userLastName, "Objects", userPassword, archiveWriteStream); + mre.WaitOne(60000, false); -// byte[] archive = archiveWriteStream.ToArray(); -// MemoryStream archiveReadStream = new MemoryStream(archive); -// TarArchiveReader tar = new TarArchiveReader(archiveReadStream); + byte[] archive = archiveWriteStream.ToArray(); + MemoryStream archiveReadStream = new MemoryStream(archive); + TarArchiveReader tar = new TarArchiveReader(archiveReadStream); -// //bool gotControlFile = false; -// bool gotObject1File = false; -// //bool gotObject2File = false; -// string expectedObject1FileName = InventoryArchiveWriteRequest.CreateArchiveItemName(item1); -// string expectedObject1FilePath = string.Format( -// "{0}{1}{2}", -// ArchiveConstants.INVENTORY_PATH, -// InventoryArchiveWriteRequest.CreateArchiveFolderName(objsFolder), -// expectedObject1FileName); + //bool gotControlFile = false; + bool gotObject1File = false; + //bool gotObject2File = false; + string expectedObject1FileName = InventoryArchiveWriteRequest.CreateArchiveItemName(item1); + string expectedObject1FilePath = string.Format( + "{0}{1}{2}", + ArchiveConstants.INVENTORY_PATH, + InventoryArchiveWriteRequest.CreateArchiveFolderName(objsFolder), + expectedObject1FileName); -// string filePath; -// TarArchiveReader.TarEntryType tarEntryType; + string filePath; + TarArchiveReader.TarEntryType tarEntryType; // Console.WriteLine("Reading archive"); -// while (tar.ReadEntry(out filePath, out tarEntryType) != null) -// { -// Console.WriteLine("Got {0}", filePath); + while (tar.ReadEntry(out filePath, out tarEntryType) != null) + { + Console.WriteLine("Got {0}", filePath); -//// if (ArchiveConstants.CONTROL_FILE_PATH == filePath) -//// { -//// gotControlFile = true; -//// } - -// if (filePath.StartsWith(ArchiveConstants.INVENTORY_PATH) && filePath.EndsWith(".xml")) +// if (ArchiveConstants.CONTROL_FILE_PATH == filePath) // { -//// string fileName = filePath.Remove(0, "Objects/".Length); -//// -//// if (fileName.StartsWith(part1.Name)) -//// { -// Assert.That(expectedObject1FilePath, Is.EqualTo(filePath)); -// gotObject1File = true; -//// } -//// else if (fileName.StartsWith(part2.Name)) -//// { -//// Assert.That(fileName, Is.EqualTo(expectedObject2FileName)); -//// gotObject2File = true; -//// } +// gotControlFile = true; // } -// } + + if (filePath.StartsWith(ArchiveConstants.INVENTORY_PATH) && filePath.EndsWith(".xml")) + { +// string fileName = filePath.Remove(0, "Objects/".Length); +// +// if (fileName.StartsWith(part1.Name)) +// { + Assert.That(expectedObject1FilePath, Is.EqualTo(filePath)); + gotObject1File = true; +// } +// else if (fileName.StartsWith(part2.Name)) +// { +// Assert.That(fileName, Is.EqualTo(expectedObject2FileName)); +// gotObject2File = true; +// } + } + } -//// Assert.That(gotControlFile, Is.True, "No control file in archive"); -// Assert.That(gotObject1File, Is.True, "No item1 file in archive"); -//// Assert.That(gotObject2File, Is.True, "No object2 file in archive"); +// Assert.That(gotControlFile, Is.True, "No control file in archive"); + Assert.That(gotObject1File, Is.True, "No item1 file in archive"); +// Assert.That(gotObject2File, Is.True, "No object2 file in archive"); -// // TODO: Test presence of more files and contents of files. -// } + // TODO: Test presence of more files and contents of files. + } /// /// Test loading a V0.1 OpenSim Inventory Archive (subject to change since there is no fixed format yet) where @@ -541,56 +533,41 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests /// /// Test replication of an archive path to the user's inventory. /// - //[Test] - //public void TestReplicateArchivePathToUserInventory() - //{ - // TestHelper.InMethod(); + [Test] + public void TestReplicateArchivePathToUserInventory() + { + TestHelper.InMethod(); + //log4net.Config.XmlConfigurator.Configure(); + + Scene scene = SceneSetupHelpers.SetupScene("inventory"); + UserAccount ua1 = UserProfileTestUtils.CreateUserWithInventory(scene); + + Dictionary foldersCreated = new Dictionary(); + List nodesLoaded = new List(); + + string folder1Name = "a"; + string folder2Name = "b"; + string itemName = "c.lsl"; + + string folder1ArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder1Name, UUID.Random()); + string folder2ArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder2Name, UUID.Random()); + string itemArchiveName = InventoryArchiveWriteRequest.CreateArchiveItemName(itemName, UUID.Random()); + + string itemArchivePath + = string.Format( + "{0}{1}{2}{3}", + ArchiveConstants.INVENTORY_PATH, folder1ArchiveName, folder2ArchiveName, itemArchiveName); - // //log4net.Config.XmlConfigurator.Configure(); - - // Scene scene = SceneSetupHelpers.SetupScene("inventory"); - // CommunicationsManager commsManager = scene.CommsManager; - // CachedUserInfo userInfo; + new InventoryArchiveReadRequest(scene, ua1, null, (Stream)null) + .ReplicateArchivePathToUserInventory( + itemArchivePath, false, scene.InventoryService.GetRootFolder(ua1.PrincipalID), + foldersCreated, nodesLoaded); - // lock (this) - // { - // // !!! REFACTORING PROBLEM. This needs to be rewritten - // userInfo = UserProfileTestUtils.CreateUserWithInventory(commsManager, InventoryReceived); - // Monitor.Wait(this, 60000); - // } - - // //Console.WriteLine("userInfo.RootFolder 1: {0}", userInfo.RootFolder); - - // Dictionary foldersCreated = new Dictionary(); - // List nodesLoaded = new List(); - - // string folder1Name = "a"; - // string folder2Name = "b"; - // string itemName = "c.lsl"; - - // string folder1ArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder1Name, UUID.Random()); - // string folder2ArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder2Name, UUID.Random()); - // string itemArchiveName = InventoryArchiveWriteRequest.CreateArchiveItemName(itemName, UUID.Random()); - - // string itemArchivePath - // = string.Format( - // "{0}{1}{2}{3}", - // ArchiveConstants.INVENTORY_PATH, folder1ArchiveName, folder2ArchiveName, itemArchiveName); - - // //Console.WriteLine("userInfo.RootFolder 2: {0}", userInfo.RootFolder); - - // new InventoryArchiveReadRequest(scene, userInfo, null, (Stream)null) - // .ReplicateArchivePathToUserInventory( - // itemArchivePath, false, scene.InventoryService.GetRootFolder(userInfo.UserProfile.ID), - // foldersCreated, nodesLoaded); - - // //Console.WriteLine("userInfo.RootFolder 3: {0}", userInfo.RootFolder); - // //InventoryFolderImpl folder1 = userInfo.RootFolder.FindFolderByPath("a"); - // InventoryFolderBase folder1 - // = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, userInfo.UserProfile.ID, "a"); - // Assert.That(folder1, Is.Not.Null, "Could not find folder a"); - // InventoryFolderBase folder2 = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, folder1, "b"); - // Assert.That(folder2, Is.Not.Null, "Could not find folder b"); - //} + InventoryFolderBase folder1 + = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, ua1.PrincipalID, "a"); + Assert.That(folder1, Is.Not.Null, "Could not find folder a"); + InventoryFolderBase folder2 = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, folder1, "b"); + Assert.That(folder2, Is.Not.Null, "Could not find folder b"); + } } -} +} \ No newline at end of file diff --git a/OpenSim/Region/CoreModules/Framework/EntityTransfer/EntityTransferModule.cs b/OpenSim/Region/CoreModules/Framework/EntityTransfer/EntityTransferModule.cs index 80c0af8461..ef37f63622 100644 --- a/OpenSim/Region/CoreModules/Framework/EntityTransfer/EntityTransferModule.cs +++ b/OpenSim/Region/CoreModules/Framework/EntityTransfer/EntityTransferModule.cs @@ -290,7 +290,10 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer agentCircuit.child = true; agentCircuit.Appearance = sp.Appearance; if (currentAgentCircuit != null) + { agentCircuit.ServiceURLs = currentAgentCircuit.ServiceURLs; + agentCircuit.Viewer = currentAgentCircuit.Viewer; + } if (NeedsNewAgent(oldRegionX, newRegionX, oldRegionY, newRegionY)) { @@ -523,11 +526,12 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer { m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Request to teleport {0} {1} home", client.FirstName, client.LastName); - OpenSim.Services.Interfaces.PresenceInfo pinfo = m_aScene.PresenceService.GetAgent(client.SessionId); + //OpenSim.Services.Interfaces.PresenceInfo pinfo = m_aScene.PresenceService.GetAgent(client.SessionId); + GridUserInfo uinfo = m_aScene.GridUserService.GetGridUserInfo(client.AgentId.ToString()); - if (pinfo != null) + if (uinfo != null) { - GridRegion regionInfo = m_aScene.GridService.GetRegionByUUID(UUID.Zero, pinfo.HomeRegionID); + GridRegion regionInfo = m_aScene.GridService.GetRegionByUUID(UUID.Zero, uinfo.HomeRegionID); if (regionInfo == null) { // can't find the Home region: Tell viewer and abort @@ -536,7 +540,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer } // a little eekie that this goes back to Scene and with a forced cast, will fix that at some point... ((Scene)(client.Scene)).RequestTeleportLocation( - client, regionInfo.RegionHandle, pinfo.HomePosition, pinfo.HomeLookAt, + client, regionInfo.RegionHandle, uinfo.HomePosition, uinfo.HomeLookAt, (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaHome)); } } @@ -986,7 +990,10 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer agent.child = true; agent.Appearance = sp.Appearance; if (currentAgentCircuit != null) + { agent.ServiceURLs = currentAgentCircuit.ServiceURLs; + agent.Viewer = currentAgentCircuit.Viewer; + } if (newRegions.Contains(neighbour.RegionHandle)) { diff --git a/OpenSim/Region/CoreModules/Framework/EntityTransfer/HGEntityTransferModule.cs b/OpenSim/Region/CoreModules/Framework/EntityTransfer/HGEntityTransferModule.cs index 28593fc8d8..7d26e3ff5f 100644 --- a/OpenSim/Region/CoreModules/Framework/EntityTransfer/HGEntityTransferModule.cs +++ b/OpenSim/Region/CoreModules/Framework/EntityTransfer/HGEntityTransferModule.cs @@ -154,7 +154,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer bool success = connector.LoginAgentToGrid(agentCircuit, reg, finalDestination, out reason); if (success) // Log them out of this grid - m_aScene.PresenceService.LogoutAgent(agentCircuit.SessionID, sp.AbsolutePosition, sp.Lookat); + m_aScene.PresenceService.LogoutAgent(agentCircuit.SessionID); return success; } @@ -238,6 +238,21 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer { if (obj.IsLoggingOut) { + object sp = null; + if (obj.Scene.TryGetScenePresence(obj.AgentId, out sp)) + { + if (((ScenePresence)sp).IsChildAgent) + return; + } + + // Let's find out if this is a foreign user or a local user + UserAccount account = m_aScene.UserAccountService.GetUserAccount(m_aScene.RegionInfo.ScopeID, obj.AgentId); + if (account != null) + { + // local grid user + return; + } + AgentCircuitData aCircuit = ((Scene)(obj.Scene)).AuthenticateHandler.GetAgentCircuitData(obj.CircuitCode); if (aCircuit.ServiceURLs.ContainsKey("HomeURI")) diff --git a/OpenSim/Region/CoreModules/Framework/InventoryAccess/HGInventoryAccessModule.cs b/OpenSim/Region/CoreModules/Framework/InventoryAccess/HGInventoryAccessModule.cs index 93aeb9440f..2ab46aa33f 100644 --- a/OpenSim/Region/CoreModules/Framework/InventoryAccess/HGInventoryAccessModule.cs +++ b/OpenSim/Region/CoreModules/Framework/InventoryAccess/HGInventoryAccessModule.cs @@ -119,9 +119,22 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess /// /// DeleteToInventory /// - public override UUID DeleteToInventory(DeRezAction action, UUID folderID, SceneObjectGroup objectGroup, IClientAPI remoteClient) + public override UUID DeleteToInventory(DeRezAction action, UUID folderID, List objectGroups, IClientAPI remoteClient) { - UUID assetID = base.DeleteToInventory(action, folderID, objectGroup, remoteClient); + UUID ret = UUID.Zero; + + // HACK: Only works for lists of length one. + // Intermediate version, just to make things compile + foreach (SceneObjectGroup g in objectGroups) + ret = DeleteToInventory(action, folderID, g, remoteClient); + + return ret; + } + + public virtual UUID DeleteToInventory(DeRezAction action, UUID folderID, + SceneObjectGroup objectGroup, IClientAPI remoteClient) + { + UUID assetID = base.DeleteToInventory(action, folderID, new List() {objectGroup}, remoteClient); if (!assetID.Equals(UUID.Zero)) { diff --git a/OpenSim/Region/CoreModules/Framework/InventoryAccess/InventoryAccessModule.cs b/OpenSim/Region/CoreModules/Framework/InventoryAccess/InventoryAccessModule.cs index 2352cedef4..3035d889e7 100644 --- a/OpenSim/Region/CoreModules/Framework/InventoryAccess/InventoryAccessModule.cs +++ b/OpenSim/Region/CoreModules/Framework/InventoryAccess/InventoryAccessModule.cs @@ -188,6 +188,20 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess /// /// /// + public virtual UUID DeleteToInventory(DeRezAction action, UUID folderID, + List objectGroups, IClientAPI remoteClient) + { + // HACK: This is only working for lists containing a single item! + // It's just a hack to make this WIP compile and run. Nothing + // currently calls this with multiple items. + UUID ret = UUID.Zero; + + foreach (SceneObjectGroup g in objectGroups) + ret = DeleteToInventory(action, folderID, g, remoteClient); + + return ret; + } + public virtual UUID DeleteToInventory(DeRezAction action, UUID folderID, SceneObjectGroup objectGroup, IClientAPI remoteClient) { @@ -502,8 +516,9 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess group.RootPart.IsAttachment = true; } - // For attachments, we must make sure that only a single object update occurs after we've finished - // all the necessary operations. + // If we're rezzing an attachment then don't ask AddNewSceneObject() to update the client since + // we'll be doing that later on. Scheduling more than one full update during the attachment + // process causes some clients to fail to display the attachment properly. m_Scene.AddNewSceneObject(group, true, false); // m_log.InfoFormat("ray end point for inventory rezz is {0} {1} {2} ", RayEnd.X, RayEnd.Y, RayEnd.Z); diff --git a/OpenSim/Region/CoreModules/RegionSync/RegionSyncModule/RegionSyncAvatar.cs b/OpenSim/Region/CoreModules/RegionSync/RegionSyncModule/RegionSyncAvatar.cs index b1e774154e..6b097a7e8c 100644 --- a/OpenSim/Region/CoreModules/RegionSync/RegionSyncModule/RegionSyncAvatar.cs +++ b/OpenSim/Region/CoreModules/RegionSync/RegionSyncModule/RegionSyncAvatar.cs @@ -547,11 +547,7 @@ namespace OpenSim.Region.Examples.RegionSyncModule { } - public virtual void SendAvatarData(SendAvatarData data) - { - } - - public virtual void SendAvatarTerseUpdate(SendAvatarTerseData data) + public virtual void SendAvatarDataImmediate(ISceneEntity avatar) { } @@ -559,6 +555,10 @@ namespace OpenSim.Region.Examples.RegionSyncModule { } + public void SendPrimUpdate(ISceneEntity entity, PrimUpdateFlags updateFlags) + { + } + public virtual void AttachObject(uint localID, Quaternion rotation, byte attachPoint, UUID ownerID) { } @@ -567,15 +567,7 @@ namespace OpenSim.Region.Examples.RegionSyncModule { } - public virtual void SendPrimitiveToClient(SendPrimitiveData data) - { - } - - public virtual void SendPrimTerseUpdate(SendPrimitiveTerseData data) - { - } - - public virtual void ReprioritizeUpdates(StateUpdateTypes type, UpdatePriorityHandler handler) + public virtual void ReprioritizeUpdates() { } diff --git a/OpenSim/Region/CoreModules/Resources/CoreModulePlugin.addin.xml b/OpenSim/Region/CoreModules/Resources/CoreModulePlugin.addin.xml index aaa318cabb..ee070756fd 100644 --- a/OpenSim/Region/CoreModules/Resources/CoreModulePlugin.addin.xml +++ b/OpenSim/Region/CoreModules/Resources/CoreModulePlugin.addin.xml @@ -45,6 +45,7 @@ + @@ -58,9 +59,11 @@ - + + + diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Hypergrid/HypergridServiceInConnectorModule.cs b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Hypergrid/HypergridServiceInConnectorModule.cs index c6848bb394..235914a0b0 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Hypergrid/HypergridServiceInConnectorModule.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Hypergrid/HypergridServiceInConnectorModule.cs @@ -113,10 +113,10 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsIn.Hypergrid ISimulationService simService = scene.RequestModuleInterface(); m_HypergridHandler = new GatekeeperServiceInConnector(m_Config, MainServer.Instance, simService); - scene.RegisterModuleInterface(m_HypergridHandler.GateKeeper); new UserAgentServerConnector(m_Config, MainServer.Instance); } + scene.RegisterModuleInterface(m_HypergridHandler.GateKeeper); } #endregion diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/RemoteGridServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/RemoteGridServiceConnector.cs index 2c234d274e..46741a58ec 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/RemoteGridServiceConnector.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/RemoteGridServiceConnector.cs @@ -191,10 +191,17 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid public override List GetRegionsByName(UUID scopeID, string name, int maxNumber) { List rinfo = m_LocalGridService.GetRegionsByName(scopeID, name, maxNumber); + //m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Local GetRegionsByName {0} found {1} regions", name, rinfo.Count); List grinfo = base.GetRegionsByName(scopeID, name, maxNumber); if (grinfo != null) - rinfo.AddRange(grinfo); + { + //m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Remote GetRegionsByName {0} found {1} regions", name, grinfo.Count); + foreach (GridRegion r in grinfo) + if (rinfo.Find(delegate(GridRegion gr) { return gr.RegionID == r.RegionID; }) == null) + rinfo.Add(r); + } + return rinfo; } diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/GridUser/ActivityDetector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/GridUser/ActivityDetector.cs new file mode 100644 index 0000000000..83c8eac8b3 --- /dev/null +++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/GridUser/ActivityDetector.cs @@ -0,0 +1,108 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +using System; +using System.Collections.Generic; +using System.Reflection; + +using OpenSim.Framework; +using OpenSim.Region.Framework.Scenes; +using OpenSim.Services.Interfaces; + +using OpenMetaverse; +using log4net; + +namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.GridUser +{ + public class ActivityDetector + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private IGridUserService m_GridUserService; + private Scene m_aScene; + + public ActivityDetector(IGridUserService guservice) + { + m_GridUserService = guservice; + m_log.DebugFormat("[ACTIVITY DETECTOR]: starting "); + } + + public void AddRegion(Scene scene) + { + // For now the only events we listen to are these + // But we could trigger the position update more often + scene.EventManager.OnMakeRootAgent += OnMakeRootAgent; + scene.EventManager.OnNewClient += OnNewClient; + + if (m_aScene == null) + m_aScene = scene; + } + + public void RemoveRegion(Scene scene) + { + scene.EventManager.OnMakeRootAgent -= OnMakeRootAgent; + scene.EventManager.OnNewClient -= OnNewClient; + } + + public void OnMakeRootAgent(ScenePresence sp) + { + m_log.DebugFormat("[ACTIVITY DETECTOR]: Detected root presence {0} in {1}", sp.UUID, sp.Scene.RegionInfo.RegionName); + + m_GridUserService.SetLastPosition(sp.UUID.ToString(), sp.Scene.RegionInfo.RegionID, sp.AbsolutePosition, sp.Lookat); + } + + public void OnNewClient(IClientAPI client) + { + client.OnConnectionClosed += OnConnectionClose; + } + + public void OnConnectionClose(IClientAPI client) + { + if (client.IsLoggingOut) + { + object sp = null; + Vector3 position = new Vector3(128, 128, 0); + Vector3 lookat = new Vector3(0, 1, 0); + + if (client.Scene.TryGetScenePresence(client.AgentId, out sp)) + { + if (sp is ScenePresence) + { + if (((ScenePresence)sp).IsChildAgent) + return; + + position = ((ScenePresence)sp).AbsolutePosition; + lookat = ((ScenePresence)sp).Lookat; + } + } + m_log.DebugFormat("[ACTIVITY DETECTOR]: Detected client logout {0} in {1}", client.AgentId, client.Scene.RegionInfo.RegionName); + m_GridUserService.LoggedOut(client.AgentId.ToString(), client.Scene.RegionInfo.RegionID, position, lookat); + } + + } + + } +} diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/GridUser/LocalGridUserServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/GridUser/LocalGridUserServiceConnector.cs index d5fae232d6..d914a576e1 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/GridUser/LocalGridUserServiceConnector.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/GridUser/LocalGridUserServiceConnector.cs @@ -41,13 +41,19 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.GridUser { public class LocalGridUserServicesConnector : ISharedRegionModule, IGridUserService { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + private static readonly ILog m_log = + LogManager.GetLogger( + MethodBase.GetCurrentMethod().DeclaringType); - private IGridUserService m_service; + private IGridUserService m_GridUserService; + + private ActivityDetector m_ActivityDetector; private bool m_Enabled = false; - public Type ReplaceableInterface + #region ISharedRegionModule + + public Type ReplaceableInterface { get { return null; } } @@ -68,7 +74,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.GridUser IConfig userConfig = source.Configs["GridUserService"]; if (userConfig == null) { - m_log.Error("[LOCAL GRID USER SERVICE CONNECTOR]: GridUserService missing from ini files"); + m_log.Error("[LOCAL GRID USER SERVICE CONNECTOR]: GridUserService missing from OpenSim.ini"); return; } @@ -81,15 +87,20 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.GridUser } Object[] args = new Object[] { source }; - m_service = ServerUtils.LoadPlugin(serviceDll, args); + m_GridUserService = ServerUtils.LoadPlugin(serviceDll, args); - if (m_service == null) + if (m_GridUserService == null) { - m_log.Error("[LOCAL GRID USER SERVICE CONNECTOR]: Can't load GridUser service"); + m_log.ErrorFormat( + "[LOCAL GRID USER SERVICE CONNECTOR]: Cannot load user account service specified as {0}", serviceDll); return; } + + m_ActivityDetector = new ActivityDetector(this); + m_Enabled = true; - m_log.Info("[LOCAL GRID USER SERVICE CONNECTOR]: Local GridUser connector enabled"); + + m_log.Info("[LOCAL GRID USER SERVICE CONNECTOR]: Local grid user connector enabled"); } } } @@ -111,29 +122,57 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.GridUser if (!m_Enabled) return; - scene.RegisterModuleInterface(m_service); + scene.RegisterModuleInterface(m_GridUserService); + m_ActivityDetector.AddRegion(scene); } public void RemoveRegion(Scene scene) { if (!m_Enabled) return; + + scene.UnregisterModuleInterface(this); + m_ActivityDetector.RemoveRegion(scene); } public void RegionLoaded(Scene scene) { if (!m_Enabled) return; + + m_log.InfoFormat("[LOCAL GRID USER SERVICE CONNECTOR]: Enabled local grid user for region {0}", scene.RegionInfo.RegionName); + } + + #endregion + + #region IGridUserService + + public GridUserInfo LoggedIn(string userID) + { + return m_GridUserService.LoggedIn(userID); + } + + public bool LoggedOut(string userID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt) + { + return m_GridUserService.LoggedOut(userID, regionID, lastPosition, lastLookAt); + } + + public bool SetHome(string userID, UUID homeID, Vector3 homePosition, Vector3 homeLookAt) + { + return m_GridUserService.SetHome(userID, homeID, homePosition, homeLookAt); + } + + public bool SetLastPosition(string userID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt) + { + return m_GridUserService.SetLastPosition(userID, regionID, lastPosition, lastLookAt); } public GridUserInfo GetGridUserInfo(string userID) { - return m_service.GetGridUserInfo(userID); - } - - public bool StoreGridUserInfo(GridUserInfo info) - { - return m_service.StoreGridUserInfo(info); + return m_GridUserService.GetGridUserInfo(userID); } + + #endregion + } -} \ No newline at end of file +} diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/GridUser/RemoteGridUserServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/GridUser/RemoteGridUserServiceConnector.cs new file mode 100644 index 0000000000..e3e2e619c1 --- /dev/null +++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/GridUser/RemoteGridUserServiceConnector.cs @@ -0,0 +1,153 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +using System; +using System.Collections.Generic; +using System.Reflection; + +using OpenSim.Region.Framework.Interfaces; +using OpenSim.Region.Framework.Scenes; +using OpenSim.Server.Base; +using OpenSim.Services.Interfaces; +using OpenSim.Services.Connectors; + +using OpenMetaverse; +using log4net; +using Nini.Config; + +namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.GridUser +{ + public class RemoteGridUserServicesConnector : ISharedRegionModule, IGridUserService + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + #region ISharedRegionModule + + private bool m_Enabled = false; + + private ActivityDetector m_ActivityDetector; + private IGridUserService m_RemoteConnector; + + public Type ReplaceableInterface + { + get { return null; } + } + + public string Name + { + get { return "RemoteGridUserServicesConnector"; } + } + + public void Initialise(IConfigSource source) + { + IConfig moduleConfig = source.Configs["Modules"]; + if (moduleConfig != null) + { + string name = moduleConfig.GetString("GridUserServices", ""); + if (name == Name) + { + m_RemoteConnector = new GridUserServicesConnector(source); + + m_Enabled = true; + + m_ActivityDetector = new ActivityDetector(this); + + m_log.Info("[REMOTE GRID USER CONNECTOR]: Remote grid user enabled"); + } + } + + } + + public void PostInitialise() + { + } + + public void Close() + { + } + + public void AddRegion(Scene scene) + { + if (!m_Enabled) + return; + + scene.RegisterModuleInterface(this); + m_ActivityDetector.AddRegion(scene); + + m_log.InfoFormat("[REMOTE GRID USER CONNECTOR]: Enabled remote grid user for region {0}", scene.RegionInfo.RegionName); + + } + + public void RemoveRegion(Scene scene) + { + if (!m_Enabled) + return; + + m_ActivityDetector.RemoveRegion(scene); + } + + public void RegionLoaded(Scene scene) + { + if (!m_Enabled) + return; + + } + + #endregion + + #region IGridUserService + + public GridUserInfo LoggedIn(string userID) + { + m_log.Warn("[REMOTE GRID USER CONNECTOR]: LoggedIn not implemented at the simulators"); + return null; + } + + public bool LoggedOut(string userID, UUID region, Vector3 position, Vector3 lookat) + { + return m_RemoteConnector.LoggedOut(userID, region, position, lookat); + } + + + public bool SetHome(string userID, UUID regionID, Vector3 position, Vector3 lookAt) + { + return m_RemoteConnector.SetHome(userID, regionID, position, lookAt); + } + + public bool SetLastPosition(string userID, UUID regionID, Vector3 position, Vector3 lookAt) + { + return m_RemoteConnector.SetLastPosition(userID, regionID, position, lookAt); + } + + public GridUserInfo GetGridUserInfo(string userID) + { + return m_RemoteConnector.GetGridUserInfo(userID); + } + + #endregion + + } +} diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/HGInventoryBroker.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/HGInventoryBroker.cs index 54508ccfa8..e09db154aa 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/HGInventoryBroker.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/HGInventoryBroker.cs @@ -41,20 +41,21 @@ using OpenMetaverse; namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory { - public class HGInventoryBroker : BaseInventoryConnector, INonSharedRegionModule, IInventoryService + public class HGInventoryBroker : ISharedRegionModule, IInventoryService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); - private static bool m_Initialized = false; private static bool m_Enabled = false; - private static IInventoryService m_GridService; - private static ISessionAuthInventoryService m_HGService; + private static IInventoryService m_LocalGridInventoryService; + private Dictionary m_connectors = new Dictionary(); - private Scene m_Scene; - private IUserAccountService m_UserAccountService; + // A cache of userIDs --> ServiceURLs, for HGBroker only + protected Dictionary m_InventoryURLs = new Dictionary(); + + private List m_Scenes = new List(); public Type ReplaceableInterface { @@ -68,67 +69,45 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory public void Initialise(IConfigSource source) { - if (!m_Initialized) + IConfig moduleConfig = source.Configs["Modules"]; + if (moduleConfig != null) { - IConfig moduleConfig = source.Configs["Modules"]; - if (moduleConfig != null) + string name = moduleConfig.GetString("InventoryServices", ""); + if (name == Name) { - string name = moduleConfig.GetString("InventoryServices", ""); - if (name == Name) + IConfig inventoryConfig = source.Configs["InventoryService"]; + if (inventoryConfig == null) { - IConfig inventoryConfig = source.Configs["InventoryService"]; - if (inventoryConfig == null) - { - m_log.Error("[HG INVENTORY CONNECTOR]: InventoryService missing from OpenSim.ini"); - return; - } - - string localDll = inventoryConfig.GetString("LocalGridInventoryService", - String.Empty); - string HGDll = inventoryConfig.GetString("HypergridInventoryService", - String.Empty); - - if (localDll == String.Empty) - { - m_log.Error("[HG INVENTORY CONNECTOR]: No LocalGridInventoryService named in section InventoryService"); - //return; - throw new Exception("Unable to proceed. Please make sure your ini files in config-include are updated according to .example's"); - } - - if (HGDll == String.Empty) - { - m_log.Error("[HG INVENTORY CONNECTOR]: No HypergridInventoryService named in section InventoryService"); - //return; - throw new Exception("Unable to proceed. Please make sure your ini files in config-include are updated according to .example's"); - } - - Object[] args = new Object[] { source }; - m_GridService = - ServerUtils.LoadPlugin(localDll, - args); - - m_HGService = - ServerUtils.LoadPlugin(HGDll, - args); - - if (m_GridService == null) - { - m_log.Error("[HG INVENTORY CONNECTOR]: Can't load local inventory service"); - return; - } - if (m_HGService == null) - { - m_log.Error("[HG INVENTORY CONNECTOR]: Can't load hypergrid inventory service"); - return; - } - - Init(source); - - m_Enabled = true; - m_log.Info("[HG INVENTORY CONNECTOR]: HG inventory broker enabled"); + m_log.Error("[HG INVENTORY CONNECTOR]: InventoryService missing from OpenSim.ini"); + return; } + + string localDll = inventoryConfig.GetString("LocalGridInventoryService", + String.Empty); + //string HGDll = inventoryConfig.GetString("HypergridInventoryService", + // String.Empty); + + if (localDll == String.Empty) + { + m_log.Error("[HG INVENTORY CONNECTOR]: No LocalGridInventoryService named in section InventoryService"); + //return; + throw new Exception("Unable to proceed. Please make sure your ini files in config-include are updated according to .example's"); + } + + Object[] args = new Object[] { source }; + m_LocalGridInventoryService = + ServerUtils.LoadPlugin(localDll, + args); + + if (m_LocalGridInventoryService == null) + { + m_log.Error("[HG INVENTORY CONNECTOR]: Can't load local inventory service"); + return; + } + + m_Enabled = true; + m_log.InfoFormat("[HG INVENTORY CONNECTOR]: HG inventory broker enabled with inner connector of type {0}", m_LocalGridInventoryService.GetType()); } - m_Initialized = true; } } @@ -145,19 +124,20 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory if (!m_Enabled) return; - m_Scene = scene; - m_UserAccountService = m_Scene.UserAccountService; + m_Scenes.Add(scene); scene.RegisterModuleInterface(this); - m_cache.AddRegion(scene); + + scene.EventManager.OnClientClosed += OnClientClosed; + } public void RemoveRegion(Scene scene) { if (!m_Enabled) return; - - m_cache.RemoveRegion(scene); + + m_Scenes.Remove(scene); } public void RegionLoaded(Scene scene) @@ -169,260 +149,307 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory } + #region URL Cache + + void OnClientClosed(UUID clientID, Scene scene) + { + if (m_InventoryURLs.ContainsKey(clientID)) // if it's in cache + { + ScenePresence sp = null; + foreach (Scene s in m_Scenes) + { + s.TryGetScenePresence(clientID, out sp); + if ((sp != null) && !sp.IsChildAgent && (s != scene)) + { + m_log.DebugFormat("[INVENTORY CACHE]: OnClientClosed in {0}, but user {1} still in sim. Keeping inventoryURL in cache", + scene.RegionInfo.RegionName, clientID); + return; + } + } + DropInventoryServiceURL(clientID); + } + } + + /// + /// Gets the user's inventory URL from its serviceURLs, if the user is foreign, + /// and sticks it in the cache + /// + /// + private void CacheInventoryServiceURL(UUID userID) + { + if (m_Scenes[0].UserAccountService.GetUserAccount(m_Scenes[0].RegionInfo.ScopeID, userID) == null) + { + // The user does not have a local account; let's cache its service URL + string inventoryURL = string.Empty; + ScenePresence sp = null; + foreach (Scene scene in m_Scenes) + { + scene.TryGetScenePresence(userID, out sp); + if (sp != null) + { + AgentCircuitData aCircuit = scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode); + if (aCircuit.ServiceURLs.ContainsKey("InventoryServerURI")) + { + inventoryURL = aCircuit.ServiceURLs["InventoryServerURI"].ToString(); + if (inventoryURL != null && inventoryURL != string.Empty) + { + inventoryURL = inventoryURL.Trim(new char[] { '/' }); + m_InventoryURLs.Add(userID, inventoryURL); + m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Added {0} to the cache of inventory URLs", inventoryURL); + return; + } + } + } + } + } + + // else put a null; it means that the methods should forward to local grid's inventory + m_InventoryURLs.Add(userID, null); + } + + private void DropInventoryServiceURL(UUID userID) + { + lock (m_InventoryURLs) + if (m_InventoryURLs.ContainsKey(userID)) + { + string url = m_InventoryURLs[userID]; + m_InventoryURLs.Remove(userID); + m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Removed {0} from the cache of inventory URLs", url); + } + } + + public string GetInventoryServiceURL(UUID userID) + { + if (m_InventoryURLs.ContainsKey(userID)) + return m_InventoryURLs[userID]; + + else + CacheInventoryServiceURL(userID); + + return m_InventoryURLs[userID]; + } + #endregion + #region IInventoryService - public override bool CreateUserInventory(UUID userID) + public bool CreateUserInventory(UUID userID) { - return m_GridService.CreateUserInventory(userID); + return m_LocalGridInventoryService.CreateUserInventory(userID); } - public override List GetInventorySkeleton(UUID userId) + public List GetInventorySkeleton(UUID userId) { - return m_GridService.GetInventorySkeleton(userId); + return m_LocalGridInventoryService.GetInventorySkeleton(userId); } - public override InventoryCollection GetUserInventory(UUID userID) + public InventoryCollection GetUserInventory(UUID userID) { return null; } - public override void GetUserInventory(UUID userID, InventoryReceiptCallback callback) + public void GetUserInventory(UUID userID, InventoryReceiptCallback callback) { } - // Inherited. See base - //public override InventoryFolderBase GetFolderForType(UUID userID, AssetType type) - //{ - // if (IsLocalGridUser(userID)) - // return m_GridService.GetFolderForType(userID, type); - // else - // { - // UUID sessionID = GetSessionID(userID); - // string uri = GetUserInventoryURI(userID) + "/" + userID.ToString(); - // // !!!!!! - // return null; - // //return m_HGService.GetFolderForType(uri, sessionID, type); - // } - //} - - public override InventoryCollection GetFolderContent(UUID userID, UUID folderID) + public InventoryFolderBase GetRootFolder(UUID userID) { - string uri = string.Empty; - if (!IsForeignUser(userID, out uri)) - return m_GridService.GetFolderContent(userID, folderID); - else - { - UUID sessionID = GetSessionID(userID); - uri = uri + "/" + userID.ToString(); - return m_HGService.GetFolderContent(uri, folderID, sessionID); - } + m_log.DebugFormat("[HG INVENTORY CONNECTOR]: GetRootFolder for {0}", userID); + + string invURL = GetInventoryServiceURL(userID); + + if (invURL == null) // not there, forward to local inventory connector to resolve + return m_LocalGridInventoryService.GetRootFolder(userID); + + IInventoryService connector = GetConnector(invURL); + + return connector.GetRootFolder(userID); } - public override Dictionary GetSystemFolders(UUID userID) + public InventoryFolderBase GetFolderForType(UUID userID, AssetType type) { - string uri = string.Empty; - if (!IsForeignUser(userID, out uri)) - { - // This is not pretty, but it will have to do for now - if (m_GridService is BaseInventoryConnector) - { - m_log.DebugFormat("[HG INVENTORY CONNECTOR]: GetSystemsFolders redirected to RemoteInventoryServiceConnector module"); - return ((BaseInventoryConnector)m_GridService).GetSystemFolders(userID); - } - else - { - m_log.DebugFormat("[HG INVENTORY CONNECTOR]: GetSystemsFolders redirected to GetSystemFoldersLocal"); - return GetSystemFoldersLocal(userID); - } - } - else - { - UUID sessionID = GetSessionID(userID); - uri = uri + "/" + userID.ToString(); - return m_HGService.GetSystemFolders(uri, sessionID); - } + m_log.DebugFormat("[HG INVENTORY CONNECTOR]: GetFolderForType {0} type {1}", userID, type); + + string invURL = GetInventoryServiceURL(userID); + + if (invURL == null) // not there, forward to local inventory connector to resolve + return m_LocalGridInventoryService.GetFolderForType(userID, type); + + IInventoryService connector = GetConnector(invURL); + + return connector.GetFolderForType(userID, type); } - private Dictionary GetSystemFoldersLocal(UUID userID) + public InventoryCollection GetFolderContent(UUID userID, UUID folderID) { - InventoryFolderBase root = m_GridService.GetRootFolder(userID); - if (root != null) - { - InventoryCollection content = m_GridService.GetFolderContent(userID, root.ID); - if (content != null) - { - Dictionary folders = new Dictionary(); - foreach (InventoryFolderBase folder in content.Folders) - { - //m_log.DebugFormat("[HG INVENTORY CONNECTOR]: scanning folder type {0}", (AssetType)folder.Type); - if ((folder.Type != (short)AssetType.Folder) && (folder.Type != (short)AssetType.Unknown)) - folders[(AssetType)folder.Type] = folder; - } - // Put the root folder there, as type Folder - folders[AssetType.Folder] = root; - m_log.DebugFormat("[HG INVENTORY CONNECTOR]: System folders count for {0}: {1}", userID, folders.Count); - return folders; - } - m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Root folder content not found for {0}", userID); + m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolderContent " + folderID); - } + string invURL = GetInventoryServiceURL(userID); - m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Root folder not found for {0}", userID); + if (invURL == null) // not there, forward to local inventory connector to resolve + return m_LocalGridInventoryService.GetFolderContent(userID, folderID); + + IInventoryService connector = GetConnector(invURL); + + return connector.GetFolderContent(userID, folderID); - return new Dictionary(); } - public override List GetFolderItems(UUID userID, UUID folderID) + public List GetFolderItems(UUID userID, UUID folderID) { - string uri = string.Empty; - if (!IsForeignUser(userID, out uri)) - return m_GridService.GetFolderItems(userID, folderID); - else - { - UUID sessionID = GetSessionID(userID); - uri = uri + "/" + userID.ToString(); - return m_HGService.GetFolderItems(uri, folderID, sessionID); - } + m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolderItems " + folderID); + + string invURL = GetInventoryServiceURL(userID); + + if (invURL == null) // not there, forward to local inventory connector to resolve + return m_LocalGridInventoryService.GetFolderItems(userID, folderID); + + IInventoryService connector = GetConnector(invURL); + + return connector.GetFolderItems(userID, folderID); + } - public override bool AddFolder(InventoryFolderBase folder) + public bool AddFolder(InventoryFolderBase folder) { if (folder == null) return false; - string uri = string.Empty; - if (!IsForeignUser(folder.Owner, out uri)) - return m_GridService.AddFolder(folder); - else - { - UUID sessionID = GetSessionID(folder.Owner); - uri = uri + "/" + folder.Owner.ToString(); - return m_HGService.AddFolder(uri, folder, sessionID); - } + m_log.Debug("[HG INVENTORY CONNECTOR]: AddFolder " + folder.ID); + + string invURL = GetInventoryServiceURL(folder.Owner); + + if (invURL == null) // not there, forward to local inventory connector to resolve + return m_LocalGridInventoryService.AddFolder(folder); + + IInventoryService connector = GetConnector(invURL); + + return connector.AddFolder(folder); } - public override bool UpdateFolder(InventoryFolderBase folder) + public bool UpdateFolder(InventoryFolderBase folder) { if (folder == null) return false; - string uri = string.Empty; - if (!IsForeignUser(folder.Owner, out uri)) - return m_GridService.UpdateFolder(folder); - else - { - UUID sessionID = GetSessionID(folder.Owner); - uri = uri + "/" + folder.Owner.ToString(); - return m_HGService.UpdateFolder(uri, folder, sessionID); - } + m_log.Debug("[HG INVENTORY CONNECTOR]: UpdateFolder " + folder.ID); + + string invURL = GetInventoryServiceURL(folder.Owner); + + if (invURL == null) // not there, forward to local inventory connector to resolve + return m_LocalGridInventoryService.UpdateFolder(folder); + + IInventoryService connector = GetConnector(invURL); + + return connector.UpdateFolder(folder); } - public override bool DeleteFolders(UUID ownerID, List folderIDs) + public bool DeleteFolders(UUID ownerID, List folderIDs) { if (folderIDs == null) return false; if (folderIDs.Count == 0) return false; - string uri = string.Empty; - if (!IsForeignUser(ownerID, out uri)) - return m_GridService.DeleteFolders(ownerID, folderIDs); - else - { - UUID sessionID = GetSessionID(ownerID); - uri = uri + "/" + ownerID.ToString(); - return m_HGService.DeleteFolders(uri, folderIDs, sessionID); - } + m_log.Debug("[HG INVENTORY CONNECTOR]: DeleteFolders for " + ownerID); + + string invURL = GetInventoryServiceURL(ownerID); + + if (invURL == null) // not there, forward to local inventory connector to resolve + return m_LocalGridInventoryService.DeleteFolders(ownerID, folderIDs); + + IInventoryService connector = GetConnector(invURL); + + return connector.DeleteFolders(ownerID, folderIDs); } - public override bool MoveFolder(InventoryFolderBase folder) + public bool MoveFolder(InventoryFolderBase folder) { if (folder == null) return false; - string uri = string.Empty; - if (!IsForeignUser(folder.Owner, out uri)) - return m_GridService.MoveFolder(folder); - else - { - UUID sessionID = GetSessionID(folder.Owner); - uri = uri + "/" + folder.Owner.ToString(); - return m_HGService.MoveFolder(uri, folder, sessionID); - } + m_log.Debug("[HG INVENTORY CONNECTOR]: MoveFolder for " + folder.Owner); + + string invURL = GetInventoryServiceURL(folder.Owner); + + if (invURL == null) // not there, forward to local inventory connector to resolve + return m_LocalGridInventoryService.MoveFolder(folder); + + IInventoryService connector = GetConnector(invURL); + + return connector.MoveFolder(folder); } - public override bool PurgeFolder(InventoryFolderBase folder) + public bool PurgeFolder(InventoryFolderBase folder) { if (folder == null) return false; - string uri = string.Empty; - if (!IsForeignUser(folder.Owner, out uri)) - return m_GridService.PurgeFolder(folder); - else - { - UUID sessionID = GetSessionID(folder.Owner); - uri = uri + "/" + folder.Owner.ToString(); - return m_HGService.PurgeFolder(uri, folder, sessionID); - } + m_log.Debug("[HG INVENTORY CONNECTOR]: PurgeFolder for " + folder.Owner); + + string invURL = GetInventoryServiceURL(folder.Owner); + + if (invURL == null) // not there, forward to local inventory connector to resolve + return m_LocalGridInventoryService.PurgeFolder(folder); + + IInventoryService connector = GetConnector(invURL); + + return connector.PurgeFolder(folder); } - // public bool AddItem(InventoryItemBase item) inherited - // Uses AddItemPlain - - protected override bool AddItemPlain(InventoryItemBase item) + public bool AddItem(InventoryItemBase item) { if (item == null) return false; - string uri = string.Empty; - if (!IsForeignUser(item.Owner, out uri)) - { - return m_GridService.AddItem(item); - } - else - { - UUID sessionID = GetSessionID(item.Owner); - uri = uri + "/" + item.Owner.ToString(); - return m_HGService.AddItem(uri, item, sessionID); - } + m_log.Debug("[HG INVENTORY CONNECTOR]: AddItem " + item.ID); + + string invURL = GetInventoryServiceURL(item.Owner); + + if (invURL == null) // not there, forward to local inventory connector to resolve + return m_LocalGridInventoryService.AddItem(item); + + IInventoryService connector = GetConnector(invURL); + + return connector.AddItem(item); } - public override bool UpdateItem(InventoryItemBase item) + public bool UpdateItem(InventoryItemBase item) { if (item == null) return false; - string uri = string.Empty; - if (!IsForeignUser(item.Owner, out uri)) - return m_GridService.UpdateItem(item); - else - { - UUID sessionID = GetSessionID(item.Owner); - uri = uri + "/" + item.Owner.ToString(); - return m_HGService.UpdateItem(uri, item, sessionID); - } + m_log.Debug("[HG INVENTORY CONNECTOR]: UpdateItem " + item.ID); + + string invURL = GetInventoryServiceURL(item.Owner); + + if (invURL == null) // not there, forward to local inventory connector to resolve + return m_LocalGridInventoryService.UpdateItem(item); + + IInventoryService connector = GetConnector(invURL); + + return connector.UpdateItem(item); } - public override bool MoveItems(UUID ownerID, List items) + public bool MoveItems(UUID ownerID, List items) { if (items == null) return false; if (items.Count == 0) return true; - string uri = string.Empty; - if (!IsForeignUser(ownerID, out uri)) - return m_GridService.MoveItems(ownerID, items); - else - { - UUID sessionID = GetSessionID(ownerID); - uri = uri + "/" + ownerID.ToString(); - return m_HGService.MoveItems(uri, items, sessionID); - } + m_log.Debug("[HG INVENTORY CONNECTOR]: MoveItems for " + ownerID); + + string invURL = GetInventoryServiceURL(ownerID); + + if (invURL == null) // not there, forward to local inventory connector to resolve + return m_LocalGridInventoryService.MoveItems(ownerID, items); + + IInventoryService connector = GetConnector(invURL); + + return connector.MoveItems(ownerID, items); } - public override bool DeleteItems(UUID ownerID, List itemIDs) + public bool DeleteItems(UUID ownerID, List itemIDs) { m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Delete {0} items for user {1}", itemIDs.Count, ownerID); @@ -431,109 +458,98 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory if (itemIDs.Count == 0) return true; - string uri = string.Empty; - if (!IsForeignUser(ownerID, out uri)) - return m_GridService.DeleteItems(ownerID, itemIDs); - else - { - UUID sessionID = GetSessionID(ownerID); - uri = uri + "/" + ownerID.ToString(); - return m_HGService.DeleteItems(uri, itemIDs, sessionID); - } + m_log.Debug("[HG INVENTORY CONNECTOR]: DeleteItems for " + ownerID); + + string invURL = GetInventoryServiceURL(ownerID); + + if (invURL == null) // not there, forward to local inventory connector to resolve + return m_LocalGridInventoryService.DeleteItems(ownerID, itemIDs); + + IInventoryService connector = GetConnector(invURL); + + return connector.DeleteItems(ownerID, itemIDs); } - public override InventoryItemBase GetItem(InventoryItemBase item) + public InventoryItemBase GetItem(InventoryItemBase item) { if (item == null) return null; - m_log.DebugFormat("[HG INVENTORY CONNECTOR]: GetItem {0} for user {1}", item.ID, item.Owner); - string uri = string.Empty; - if (!IsForeignUser(item.Owner, out uri)) - return m_GridService.GetItem(item); - else - { - UUID sessionID = GetSessionID(item.Owner); - uri = uri + "/" + item.Owner.ToString(); - return m_HGService.QueryItem(uri, item, sessionID); - } + m_log.Debug("[HG INVENTORY CONNECTOR]: GetItem " + item.ID); + + string invURL = GetInventoryServiceURL(item.Owner); + + if (invURL == null) // not there, forward to local inventory connector to resolve + return m_LocalGridInventoryService.GetItem(item); + + IInventoryService connector = GetConnector(invURL); + + return connector.GetItem(item); } - public override InventoryFolderBase GetFolder(InventoryFolderBase folder) + public InventoryFolderBase GetFolder(InventoryFolderBase folder) { if (folder == null) return null; - string uri = string.Empty; - if (!IsForeignUser(folder.Owner, out uri)) - return m_GridService.GetFolder(folder); - else - { - UUID sessionID = GetSessionID(folder.Owner); - uri = uri + "/" + folder.Owner.ToString(); - return m_HGService.QueryFolder(uri, folder, sessionID); - } + m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolder " + folder.ID); + + string invURL = GetInventoryServiceURL(folder.Owner); + + if (invURL == null) // not there, forward to local inventory connector to resolve + return m_LocalGridInventoryService.GetFolder(folder); + + IInventoryService connector = GetConnector(invURL); + + return connector.GetFolder(folder); } - public override bool HasInventoryForUser(UUID userID) + public bool HasInventoryForUser(UUID userID) { return false; } - public override List GetActiveGestures(UUID userId) + public List GetActiveGestures(UUID userId) { return new List(); } - public override int GetAssetPermissions(UUID userID, UUID assetID) + public int GetAssetPermissions(UUID userID, UUID assetID) { - string uri = string.Empty; - if (!IsForeignUser(userID, out uri)) - return m_GridService.GetAssetPermissions(userID, assetID); - else - { - UUID sessionID = GetSessionID(userID); - uri = uri + "/" + userID.ToString(); - return m_HGService.GetAssetPermissions(uri, assetID, sessionID); - } + m_log.Debug("[HG INVENTORY CONNECTOR]: GetAssetPermissions " + assetID); + + string invURL = GetInventoryServiceURL(userID); + + if (invURL == null) // not there, forward to local inventory connector to resolve + return m_LocalGridInventoryService.GetAssetPermissions(userID, assetID); + + IInventoryService connector = GetConnector(invURL); + + return connector.GetAssetPermissions(userID, assetID); } #endregion - private UUID GetSessionID(UUID userID) + private IInventoryService GetConnector(string url) { - ScenePresence sp = null; - if (m_Scene.TryGetScenePresence(userID, out sp)) + IInventoryService connector = null; + lock (m_connectors) { - return sp.ControllingClient.SessionId; - } - - m_log.DebugFormat("[HG INVENTORY CONNECTOR]: scene presence for {0} not found", userID); - return UUID.Zero; - } - - private bool IsForeignUser(UUID userID, out string inventoryURL) - { - inventoryURL = string.Empty; - UserAccount account = null; - if (m_Scene.UserAccountService != null) - account = m_Scene.UserAccountService.GetUserAccount(m_Scene.RegionInfo.ScopeID, userID); - - if (account == null) // foreign user - { - ScenePresence sp = null; - m_Scene.TryGetScenePresence(userID, out sp); - if (sp != null) + if (m_connectors.ContainsKey(url)) { - AgentCircuitData aCircuit = m_Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode); - if (aCircuit.ServiceURLs.ContainsKey("InventoryServerURI")) - { - inventoryURL = aCircuit.ServiceURLs["InventoryServerURI"].ToString(); - inventoryURL = inventoryURL.Trim(new char[] { '/' }); - return true; - } + connector = m_connectors[url]; + } + else + { + // We're instantiating this class explicitly, but this won't + // work in general, because the remote grid may be running + // an inventory server that has a different protocol. + // Eventually we will want a piece of protocol asking + // the remote server about its kind. Definitely cool thing to do! + connector = new RemoteXInventoryServicesConnector(url); + m_connectors.Add(url, connector); } } - return false; + return connector; } } diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/InventoryCache.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/InventoryCache.cs index 5e06580cce..c97ab9e8da 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/InventoryCache.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/InventoryCache.cs @@ -51,6 +51,10 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory // The cache proper protected Dictionary> m_InventoryCache; + // A cache of userIDs --> ServiceURLs, for HGBroker only + protected Dictionary m_InventoryURLs = + new Dictionary(); + public virtual void Init(IConfigSource source, BaseInventoryConnector connector) { m_Scenes = new List(); @@ -89,8 +93,11 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory // If not, go get them and place them in the cache Dictionary folders = CacheSystemFolders(presence.UUID); + CacheInventoryServiceURL(presence.Scene, presence.UUID); + m_log.DebugFormat("[INVENTORY CACHE]: OnMakeRootAgent in {0}, fetched system folders for {1} {2}: count {3}", presence.Scene.RegionInfo.RegionName, presence.Firstname, presence.Lastname, folders.Count); + } void OnClientClosed(UUID clientID, Scene scene) @@ -113,6 +120,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory "[INVENTORY CACHE]: OnClientClosed in {0}, user {1} out of sim. Dropping system folders", scene.RegionInfo.RegionName, clientID); DropCachedSystemFolders(clientID); + DropInventoryServiceURL(clientID); } } @@ -174,5 +182,49 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory return null; } + + /// + /// Gets the user's inventory URL from its serviceURLs, if the user is foreign, + /// and sticks it in the cache + /// + /// + private void CacheInventoryServiceURL(Scene scene, UUID userID) + { + if (scene.UserAccountService.GetUserAccount(scene.RegionInfo.ScopeID, userID) == null) + { + // The user does not have a local account; let's cache its service URL + string inventoryURL = string.Empty; + ScenePresence sp = null; + scene.TryGetScenePresence(userID, out sp); + if (sp != null) + { + AgentCircuitData aCircuit = scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode); + if (aCircuit.ServiceURLs.ContainsKey("InventoryServerURI")) + { + inventoryURL = aCircuit.ServiceURLs["InventoryServerURI"].ToString(); + if (inventoryURL != null && inventoryURL != string.Empty) + { + inventoryURL = inventoryURL.Trim(new char[] { '/' }); + m_InventoryURLs.Add(userID, inventoryURL); + } + } + } + } + } + + private void DropInventoryServiceURL(UUID userID) + { + lock (m_InventoryURLs) + if (m_InventoryURLs.ContainsKey(userID)) + m_InventoryURLs.Remove(userID); + } + + public string GetInventoryServiceURL(UUID userID) + { + if (m_InventoryURLs.ContainsKey(userID)) + return m_InventoryURLs[userID]; + + return null; + } } } diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/LocalInventoryServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/LocalInventoryServiceConnector.cs index a2f26d5a2c..22bd04cd65 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/LocalInventoryServiceConnector.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/LocalInventoryServiceConnector.cs @@ -41,7 +41,7 @@ using OpenMetaverse; namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory { - public class LocalInventoryServicesConnector : BaseInventoryConnector, ISharedRegionModule, IInventoryService + public class LocalInventoryServicesConnector : ISharedRegionModule, IInventoryService { private static readonly ILog m_log = LogManager.GetLogger( @@ -50,7 +50,6 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory private IInventoryService m_InventoryService; private bool m_Enabled = false; - private bool m_Initialized = false; public Type ReplaceableInterface { @@ -93,23 +92,9 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory if (m_InventoryService == null) { m_log.Error("[LOCAL INVENTORY SERVICES CONNECTOR]: Can't load inventory service"); - //return; throw new Exception("Unable to proceed. Please make sure your ini files in config-include are updated according to .example's"); } - //List plugins - // = DataPluginFactory.LoadDataPlugins( - // configSettings.StandaloneInventoryPlugin, - // configSettings.StandaloneInventorySource); - - //foreach (IInventoryDataPlugin plugin in plugins) - //{ - // // Using the OSP wrapper plugin for database plugins should be made configurable at some point - // m_InventoryService.AddPlugin(new OspInventoryWrapperPlugin(plugin, this)); - //} - - Init(source); - m_Enabled = true; m_log.Info("[LOCAL INVENTORY SERVICES CONNECTOR]: Local inventory connector enabled"); } @@ -128,99 +113,60 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory { if (!m_Enabled) return; - - if (!m_Initialized) - { - m_Initialized = true; - } - -// m_log.DebugFormat( -// "[LOCAL INVENTORY SERVICES CONNECTOR]: Registering IInventoryService to scene {0}", scene.RegionInfo.RegionName); scene.RegisterModuleInterface(this); - m_cache.AddRegion(scene); } public void RemoveRegion(Scene scene) { if (!m_Enabled) return; - - m_cache.RemoveRegion(scene); } public void RegionLoaded(Scene scene) { if (!m_Enabled) return; - - m_log.InfoFormat( - "[LOCAL INVENTORY SERVICES CONNECTOR]: Enabled local inventory for region {0}", scene.RegionInfo.RegionName); } #region IInventoryService - public override bool CreateUserInventory(UUID user) + public bool CreateUserInventory(UUID user) { return m_InventoryService.CreateUserInventory(user); } - public override List GetInventorySkeleton(UUID userId) + public List GetInventorySkeleton(UUID userId) { return m_InventoryService.GetInventorySkeleton(userId); } - public override InventoryCollection GetUserInventory(UUID id) + public InventoryCollection GetUserInventory(UUID id) { return m_InventoryService.GetUserInventory(id); } - public override void GetUserInventory(UUID userID, InventoryReceiptCallback callback) + public void GetUserInventory(UUID userID, InventoryReceiptCallback callback) { m_InventoryService.GetUserInventory(userID, callback); } - // Inherited. See base - //public InventoryFolderBase GetFolderForType(UUID userID, AssetType type) - //{ - // return m_InventoryService.GetFolderForType(userID, type); - //} - - public override Dictionary GetSystemFolders(UUID userID) + public InventoryFolderBase GetRootFolder(UUID userID) { - InventoryFolderBase root = m_InventoryService.GetRootFolder(userID); - if (root != null) - { - InventoryCollection content = GetFolderContent(userID, root.ID); - if (content != null) - { - Dictionary folders = new Dictionary(); - foreach (InventoryFolderBase folder in content.Folders) - { - if ((folder.Type != (short)AssetType.Folder) && (folder.Type != (short)AssetType.Unknown)) - { - //m_log.InfoFormat("[INVENTORY CONNECTOR]: folder type {0} ", folder.Type); - folders[(AssetType)folder.Type] = folder; - } - } - // Put the root folder there, as type Folder - folders[AssetType.Folder] = root; - //m_log.InfoFormat("[INVENTORY CONNECTOR]: root folder is type {0} ", root.Type); - - return folders; - } - } - m_log.WarnFormat("[LOCAL INVENTORY SERVICES CONNECTOR]: System folders for {0} not found", userID); - return new Dictionary(); + return m_InventoryService.GetRootFolder(userID); } - public override InventoryCollection GetFolderContent(UUID userID, UUID folderID) + public InventoryFolderBase GetFolderForType(UUID userID, AssetType type) + { + return m_InventoryService.GetFolderForType(userID, type); + } + + public InventoryCollection GetFolderContent(UUID userID, UUID folderID) { return m_InventoryService.GetFolderContent(userID, folderID); } - - public override List GetFolderItems(UUID userID, UUID folderID) + public List GetFolderItems(UUID userID, UUID folderID) { return m_InventoryService.GetFolderItems(userID, folderID); } @@ -230,7 +176,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory /// /// /// true if the folder was successfully added - public override bool AddFolder(InventoryFolderBase folder) + public bool AddFolder(InventoryFolderBase folder) { return m_InventoryService.AddFolder(folder); } @@ -240,7 +186,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory /// /// /// true if the folder was successfully updated - public override bool UpdateFolder(InventoryFolderBase folder) + public bool UpdateFolder(InventoryFolderBase folder) { return m_InventoryService.UpdateFolder(folder); } @@ -250,12 +196,12 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory /// /// A folder containing the details of the new location /// true if the folder was successfully moved - public override bool MoveFolder(InventoryFolderBase folder) + public bool MoveFolder(InventoryFolderBase folder) { return m_InventoryService.MoveFolder(folder); } - public override bool DeleteFolders(UUID ownerID, List folderIDs) + public bool DeleteFolders(UUID ownerID, List folderIDs) { return m_InventoryService.DeleteFolders(ownerID, folderIDs); } @@ -265,18 +211,17 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory /// /// /// true if the folder was successfully purged - public override bool PurgeFolder(InventoryFolderBase folder) + public bool PurgeFolder(InventoryFolderBase folder) { return m_InventoryService.PurgeFolder(folder); } /// - /// Add a new item to the user's inventory, plain - /// Called by base class AddItem + /// Add a new item to the user's inventory /// /// /// true if the item was successfully added - protected override bool AddItemPlain(InventoryItemBase item) + public bool AddItem(InventoryItemBase item) { return m_InventoryService.AddItem(item); } @@ -286,13 +231,13 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory /// /// /// true if the item was successfully updated - public override bool UpdateItem(InventoryItemBase item) + public bool UpdateItem(InventoryItemBase item) { return m_InventoryService.UpdateItem(item); } - public override bool MoveItems(UUID ownerID, List items) + public bool MoveItems(UUID ownerID, List items) { return m_InventoryService.MoveItems(ownerID, items); } @@ -302,12 +247,12 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory /// /// /// true if the item was successfully deleted - public override bool DeleteItems(UUID ownerID, List itemIDs) + public bool DeleteItems(UUID ownerID, List itemIDs) { return m_InventoryService.DeleteItems(ownerID, itemIDs); } - public override InventoryItemBase GetItem(InventoryItemBase item) + public InventoryItemBase GetItem(InventoryItemBase item) { // m_log.DebugFormat("[LOCAL INVENTORY SERVICES CONNECTOR]: Requesting inventory item {0}", item.ID); @@ -322,7 +267,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory return item; } - public override InventoryFolderBase GetFolder(InventoryFolderBase folder) + public InventoryFolderBase GetFolder(InventoryFolderBase folder) { return m_InventoryService.GetFolder(folder); } @@ -332,17 +277,17 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory /// /// /// - public override bool HasInventoryForUser(UUID userID) + public bool HasInventoryForUser(UUID userID) { return m_InventoryService.HasInventoryForUser(userID); } - public override List GetActiveGestures(UUID userId) + public List GetActiveGestures(UUID userId) { return m_InventoryService.GetActiveGestures(userId); } - public override int GetAssetPermissions(UUID userID, UUID assetID) + public int GetAssetPermissions(UUID userID, UUID assetID) { return m_InventoryService.GetAssetPermissions(userID, assetID); } diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/RemoteXInventoryServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/RemoteXInventoryServiceConnector.cs new file mode 100644 index 0000000000..277060d2aa --- /dev/null +++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/RemoteXInventoryServiceConnector.cs @@ -0,0 +1,303 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using log4net; +using System; +using System.Collections.Generic; +using System.Reflection; +using Nini.Config; +using OpenSim.Framework; +using OpenSim.Framework.Statistics; + +using OpenSim.Services.Connectors; +using OpenSim.Region.Framework.Interfaces; +using OpenSim.Region.Framework.Scenes; +using OpenSim.Services.Interfaces; +using OpenMetaverse; + +namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory +{ + public class RemoteXInventoryServicesConnector : ISharedRegionModule, IInventoryService + { + private static readonly ILog m_log = + LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private bool m_Enabled = false; + private bool m_Initialized = false; + private Scene m_Scene; + private XInventoryServicesConnector m_RemoteConnector; + + public Type ReplaceableInterface + { + get { return null; } + } + + public string Name + { + get { return "RemoteXInventoryServicesConnector"; } + } + + public RemoteXInventoryServicesConnector() + { + } + + public RemoteXInventoryServicesConnector(string url) + { + m_RemoteConnector = new XInventoryServicesConnector(url); + } + + public RemoteXInventoryServicesConnector(IConfigSource source) + { + Init(source); + } + + protected void Init(IConfigSource source) + { + m_RemoteConnector = new XInventoryServicesConnector(source); + } + + + #region ISharedRegionModule + + public void Initialise(IConfigSource source) + { + IConfig moduleConfig = source.Configs["Modules"]; + if (moduleConfig != null) + { + string name = moduleConfig.GetString("InventoryServices", ""); + if (name == Name) + { + Init(source); + m_Enabled = true; + + m_log.Info("[XINVENTORY CONNECTOR]: Remote XInventory enabled"); + } + } + } + + public void PostInitialise() + { + } + + public void Close() + { + } + + public void AddRegion(Scene scene) + { + m_Scene = scene; + //m_log.Debug("[XXXX] Adding scene " + m_Scene.RegionInfo.RegionName); + + if (!m_Enabled) + return; + + if (!m_Initialized) + { + m_Initialized = true; + } + + scene.RegisterModuleInterface(this); + } + + public void RemoveRegion(Scene scene) + { + if (!m_Enabled) + return; + + } + + public void RegionLoaded(Scene scene) + { + if (!m_Enabled) + return; + + m_log.InfoFormat("[XINVENTORY CONNECTOR]: Enabled remote XInventory for region {0}", scene.RegionInfo.RegionName); + + } + + #endregion ISharedRegionModule + + #region IInventoryService + + public bool CreateUserInventory(UUID user) + { + return false; + } + + public List GetInventorySkeleton(UUID userId) + { + return new List(); + } + + public InventoryCollection GetUserInventory(UUID userID) + { + return null; + } + + public void GetUserInventory(UUID userID, InventoryReceiptCallback callback) + { + } + + public InventoryFolderBase GetRootFolder(UUID userID) + { + return m_RemoteConnector.GetRootFolder(userID); + } + + public InventoryFolderBase GetFolderForType(UUID userID, AssetType type) + { + return m_RemoteConnector.GetFolderForType(userID, type); + } + + public InventoryCollection GetFolderContent(UUID userID, UUID folderID) + { + return m_RemoteConnector.GetFolderContent(userID, folderID); + } + + public List GetFolderItems(UUID userID, UUID folderID) + { + return m_RemoteConnector.GetFolderItems(userID, folderID); + } + + public bool AddFolder(InventoryFolderBase folder) + { + if (folder == null) + return false; + + return m_RemoteConnector.AddFolder(folder); + } + + public bool UpdateFolder(InventoryFolderBase folder) + { + if (folder == null) + return false; + + return m_RemoteConnector.UpdateFolder(folder); + } + + public bool MoveFolder(InventoryFolderBase folder) + { + if (folder == null) + return false; + + return m_RemoteConnector.MoveFolder(folder); + } + + public bool DeleteFolders(UUID ownerID, List folderIDs) + { + if (folderIDs == null) + return false; + if (folderIDs.Count == 0) + return false; + + return m_RemoteConnector.DeleteFolders(ownerID, folderIDs); + } + + + public bool PurgeFolder(InventoryFolderBase folder) + { + if (folder == null) + return false; + + return m_RemoteConnector.PurgeFolder(folder); + } + + public bool AddItem(InventoryItemBase item) + { + if (item == null) + return false; + + return m_RemoteConnector.AddItem(item); + } + + public bool UpdateItem(InventoryItemBase item) + { + if (item == null) + return false; + + return m_RemoteConnector.UpdateItem(item); + } + + public bool MoveItems(UUID ownerID, List items) + { + if (items == null) + return false; + + return m_RemoteConnector.MoveItems(ownerID, items); + } + + + public bool DeleteItems(UUID ownerID, List itemIDs) + { + if (itemIDs == null) + return false; + if (itemIDs.Count == 0) + return true; + + return m_RemoteConnector.DeleteItems(ownerID, itemIDs); + } + + public InventoryItemBase GetItem(InventoryItemBase item) + { + m_log.DebugFormat("[XINVENTORY CONNECTOR]: GetItem {0}", item.ID); + if (item == null) + return null; + + if (m_RemoteConnector == null) + m_log.DebugFormat("[XINVENTORY CONNECTOR]: connector stub is null!!!"); + return m_RemoteConnector.GetItem(item); + } + + public InventoryFolderBase GetFolder(InventoryFolderBase folder) + { + m_log.DebugFormat("[XINVENTORY CONNECTOR]: GetFolder {0}", folder.ID); + if (folder == null) + return null; + + return m_RemoteConnector.GetFolder(folder); + } + + public bool HasInventoryForUser(UUID userID) + { + return false; + } + + public List GetActiveGestures(UUID userId) + { + return new List(); + } + + public int GetAssetPermissions(UUID userID, UUID assetID) + { + return m_RemoteConnector.GetAssetPermissions(userID, assetID); + } + + + #endregion + + + } +} diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/LocalPresenceServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/LocalPresenceServiceConnector.cs index c402a3face..49dd633be4 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/LocalPresenceServiceConnector.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/LocalPresenceServiceConnector.cs @@ -167,9 +167,9 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Presence return false; } - public bool LogoutAgent(UUID sessionID, Vector3 position, Vector3 lookat) + public bool LogoutAgent(UUID sessionID) { - return m_PresenceService.LogoutAgent(sessionID, position, lookat); + return m_PresenceService.LogoutAgent(sessionID); } @@ -178,9 +178,9 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Presence return m_PresenceService.LogoutRegionAgents(regionID); } - public bool ReportAgent(UUID sessionID, UUID regionID, Vector3 position, Vector3 lookAt) + public bool ReportAgent(UUID sessionID, UUID regionID) { - return m_PresenceService.ReportAgent(sessionID, regionID, position, lookAt); + return m_PresenceService.ReportAgent(sessionID, regionID); } public PresenceInfo GetAgent(UUID sessionID) @@ -193,11 +193,6 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Presence return m_PresenceService.GetAgents(userIDs); } - public bool SetHomeLocation(string userID, UUID regionID, Vector3 position, Vector3 lookAt) - { - return m_PresenceService.SetHomeLocation(userID, regionID, position, lookAt); - } - #endregion } diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/PresenceDetector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/PresenceDetector.cs index 7a75a89f4c..62b8278b22 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/PresenceDetector.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/PresenceDetector.cs @@ -72,7 +72,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Presence public void OnMakeRootAgent(ScenePresence sp) { m_log.DebugFormat("[PRESENCE DETECTOR]: Detected root presence {0} in {1}", sp.UUID, sp.Scene.RegionInfo.RegionName); - m_PresenceService.ReportAgent(sp.ControllingClient.SessionId, sp.Scene.RegionInfo.RegionID, sp.AbsolutePosition, sp.Lookat); + m_PresenceService.ReportAgent(sp.ControllingClient.SessionId, sp.Scene.RegionInfo.RegionID); } public void OnNewClient(IClientAPI client) @@ -85,19 +85,17 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Presence if (client.IsLoggingOut) { object sp = null; - Vector3 position = new Vector3(128, 128, 0); - Vector3 lookat = new Vector3(0, 1, 0); - if (client.Scene.TryGetScenePresence(client.AgentId, out sp)) { if (sp is ScenePresence) { - position = ((ScenePresence)sp).AbsolutePosition; - lookat = ((ScenePresence)sp).Lookat; + if (((ScenePresence)sp).IsChildAgent) + return; } } - m_PresenceService.LogoutAgent(client.SessionId, position, lookat); + m_log.DebugFormat("[PRESENCE DETECTOR]: Detected client logout {0} in {1}", client.AgentId, client.Scene.RegionInfo.RegionName); + m_PresenceService.LogoutAgent(client.SessionId); } } diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/RemotePresenceServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/RemotePresenceServiceConnector.cs index 865f99e10a..bf4e9abf0d 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/RemotePresenceServiceConnector.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/RemotePresenceServiceConnector.cs @@ -76,7 +76,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Presence m_PresenceDetector = new PresenceDetector(this); - m_log.Info("[INVENTORY CONNECTOR]: Remote presence enabled"); + m_log.Info("[REMOTE PRESENCE CONNECTOR]: Remote presence enabled"); } } @@ -127,9 +127,9 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Presence return false; } - public bool LogoutAgent(UUID sessionID, Vector3 position, Vector3 lookat) + public bool LogoutAgent(UUID sessionID) { - return m_RemoteConnector.LogoutAgent(sessionID, position, lookat); + return m_RemoteConnector.LogoutAgent(sessionID); } @@ -138,9 +138,9 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Presence return m_RemoteConnector.LogoutRegionAgents(regionID); } - public bool ReportAgent(UUID sessionID, UUID regionID, Vector3 position, Vector3 lookAt) + public bool ReportAgent(UUID sessionID, UUID regionID) { - return m_RemoteConnector.ReportAgent(sessionID, regionID, position, lookAt); + return m_RemoteConnector.ReportAgent(sessionID, regionID); } public PresenceInfo GetAgent(UUID sessionID) @@ -153,11 +153,6 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Presence return m_RemoteConnector.GetAgents(userIDs); } - public bool SetHomeLocation(string userID, UUID regionID, Vector3 position, Vector3 lookAt) - { - return m_RemoteConnector.SetHomeLocation(userID, regionID, position, lookAt); - } - #endregion } diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/Tests/PresenceConnectorsTests.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/Tests/PresenceConnectorsTests.cs index 63a28fc255..ef910f4c26 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/Tests/PresenceConnectorsTests.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/Tests/PresenceConnectorsTests.cs @@ -90,27 +90,25 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Presence.Tests PresenceInfo result = m_LocalConnector.GetAgent(session1); Assert.IsNotNull(result, "Retrieved GetAgent is null"); Assert.That(result.UserID, Is.EqualTo(user1), "Retrieved userID does not match"); - Assert.IsTrue(result.Online, "Agent just logged in but is offline"); UUID region1 = UUID.Random(); - bool r = m_LocalConnector.ReportAgent(session1, region1, Vector3.Zero, Vector3.Zero); + bool r = m_LocalConnector.ReportAgent(session1, region1); Assert.IsTrue(r, "First ReportAgent returned false"); result = m_LocalConnector.GetAgent(session1); Assert.That(result.RegionID, Is.EqualTo(region1), "Agent is not in the right region (region1)"); UUID region2 = UUID.Random(); - r = m_LocalConnector.ReportAgent(session1, region2, Vector3.Zero, Vector3.Zero); + r = m_LocalConnector.ReportAgent(session1, region2); Assert.IsTrue(r, "Second ReportAgent returned false"); result = m_LocalConnector.GetAgent(session1); Assert.That(result.RegionID, Is.EqualTo(region2), "Agent is not in the right region (region2)"); - r = m_LocalConnector.LogoutAgent(session1, Vector3.Zero, Vector3.UnitY); + r = m_LocalConnector.LogoutAgent(session1); Assert.IsTrue(r, "LogoutAgent returned false"); result = m_LocalConnector.GetAgent(session1); - Assert.IsNotNull(result, "Agent session disappeared from storage after logout"); - Assert.IsFalse(result.Online, "Agent is reported to be Online after logout"); + Assert.IsNull(result, "Agent session is still stored after logout"); - r = m_LocalConnector.ReportAgent(session1, region1, Vector3.Zero, Vector3.Zero); + r = m_LocalConnector.ReportAgent(session1, region1); Assert.IsFalse(r, "ReportAgent of non-logged in user returned true"); } } diff --git a/OpenSim/Region/CoreModules/World/Archiver/ArchiveHelpers.cs b/OpenSim/Region/CoreModules/World/Archiver/ArchiveHelpers.cs new file mode 100644 index 0000000000..ddc3dd7644 --- /dev/null +++ b/OpenSim/Region/CoreModules/World/Archiver/ArchiveHelpers.cs @@ -0,0 +1,128 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.IO; +using System.Net; +using OpenMetaverse; +using OpenSim.Framework.Serialization; +using OpenSim.Region.Framework.Scenes; + +namespace OpenSim.Region.CoreModules.World.Archiver +{ + /// + /// Helper methods for archive manipulation + /// + /// This is a separate class from ArchiveConstants because we need to bring in very OpenSim specific classes. + public static class ArchiveHelpers + { + /// + /// Create the filename used for objects in OpenSim Archives. + /// + /// + /// + /// + /// + public static string CreateObjectFilename(SceneObjectGroup sog) + { + return ArchiveConstants.CreateOarObjectFilename(sog.Name, sog.UUID, sog.AbsolutePosition); + } + + /// + /// Create the path used to store an object in an OpenSim Archive. + /// + /// + /// + /// + /// + public static string CreateObjectPath(SceneObjectGroup sog) + { + return ArchiveConstants.CreateOarObjectPath(sog.Name, sog.UUID, sog.AbsolutePosition); + } + + /// + /// Resolve path to a working FileStream + /// + /// + /// + public static Stream GetStream(string path) + { + if (File.Exists(path)) + { + return new FileStream(path, FileMode.Open, FileAccess.Read); + } + else + { + try + { + Uri uri = new Uri(path); + if (uri.Scheme == "file") + { + return new FileStream(uri.AbsolutePath, FileMode.Open, FileAccess.Read); + } + else + { + if (uri.Scheme != "http") + throw new Exception(String.Format("Unsupported URI scheme ({0})", path)); + + // OK, now we know we have an HTTP URI to work with + return URIFetch(uri); + } + } + catch (UriFormatException) + { + // In many cases the user will put in a plain old filename that cannot be found so assume that + // this is the problem rather than confusing the issue with a UriFormatException + throw new Exception(String.Format("Cannot find file {0}", path)); + } + } + } + + public static Stream URIFetch(Uri uri) + { + HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); + + // request.Credentials = credentials; + + request.ContentLength = 0; + request.KeepAlive = false; + + WebResponse response = request.GetResponse(); + Stream file = response.GetResponseStream(); + + // justincc: gonna ignore the content type for now and just try anything + //if (response.ContentType != "application/x-oar") + // throw new Exception(String.Format("{0} does not identify an OAR file", uri.ToString())); + + if (response.ContentLength == 0) + throw new Exception(String.Format("{0} returned an empty file", uri.ToString())); + + // return new BufferedStream(file, (int) response.ContentLength); + return new BufferedStream(file, 1000000); + } + } +} \ No newline at end of file diff --git a/OpenSim/Region/CoreModules/World/Archiver/ArchiveReadRequest.cs b/OpenSim/Region/CoreModules/World/Archiver/ArchiveReadRequest.cs index c52f029c39..bc653ce5e9 100644 --- a/OpenSim/Region/CoreModules/World/Archiver/ArchiveReadRequest.cs +++ b/OpenSim/Region/CoreModules/World/Archiver/ArchiveReadRequest.cs @@ -38,7 +38,6 @@ using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Serialization; using OpenSim.Framework.Serialization.External; - using OpenSim.Region.CoreModules.World.Terrain; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; @@ -79,7 +78,7 @@ namespace OpenSim.Region.CoreModules.World.Archiver try { - m_loadStream = new GZipStream(GetStream(loadPath), CompressionMode.Decompress); + m_loadStream = new GZipStream(ArchiveHelpers.GetStream(loadPath), CompressionMode.Decompress); } catch (EntryPointNotFoundException e) { @@ -244,7 +243,6 @@ namespace OpenSim.Region.CoreModules.World.Archiver // to the same scene (when this is possible). sceneObject.ResetIDs(); - foreach (SceneObjectPart part in sceneObject.Children.Values) { if (!ResolveUserUuid(part.CreatorID)) @@ -472,68 +470,6 @@ namespace OpenSim.Region.CoreModules.World.Archiver return true; } - /// - /// Resolve path to a working FileStream - /// - /// - /// - private Stream GetStream(string path) - { - if (File.Exists(path)) - { - return new FileStream(path, FileMode.Open, FileAccess.Read); - } - else - { - try - { - Uri uri = new Uri(path); - if (uri.Scheme == "file") - { - return new FileStream(uri.AbsolutePath, FileMode.Open, FileAccess.Read); - } - else - { - if (uri.Scheme != "http") - throw new Exception(String.Format("Unsupported URI scheme ({0})", path)); - - // OK, now we know we have an HTTP URI to work with - - return URIFetch(uri); - } - } - catch (UriFormatException) - { - // In many cases the user will put in a plain old filename that cannot be found so assume that - // this is the problem rather than confusing the issue with a UriFormatException - throw new Exception(String.Format("Cannot find file {0}", path)); - } - } - } - - private static Stream URIFetch(Uri uri) - { - HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); - - // request.Credentials = credentials; - - request.ContentLength = 0; - request.KeepAlive = false; - - WebResponse response = request.GetResponse(); - Stream file = response.GetResponseStream(); - - // justincc: gonna ignore the content type for now and just try anything - //if (response.ContentType != "application/x-oar") - // throw new Exception(String.Format("{0} does not identify an OAR file", uri.ToString())); - - if (response.ContentLength == 0) - throw new Exception(String.Format("{0} returned an empty file", uri.ToString())); - - // return new BufferedStream(file, (int) response.ContentLength); - return new BufferedStream(file, 1000000); - } - /// /// Load oar control file /// diff --git a/OpenSim/Region/CoreModules/World/Archiver/ArchiveWriteRequestExecution.cs b/OpenSim/Region/CoreModules/World/Archiver/ArchiveWriteRequestExecution.cs index 9fc6ec47c2..586d98e322 100644 --- a/OpenSim/Region/CoreModules/World/Archiver/ArchiveWriteRequestExecution.cs +++ b/OpenSim/Region/CoreModules/World/Archiver/ArchiveWriteRequestExecution.cs @@ -145,17 +145,8 @@ namespace OpenSim.Region.CoreModules.World.Archiver { //m_log.DebugFormat("[ARCHIVER]: Saving {0} {1}, {2}", entity.Name, entity.UUID, entity.GetType()); - Vector3 position = sceneObject.AbsolutePosition; - string serializedObject = m_serialiser.SerializeGroupToXml2(sceneObject); - string filename - = string.Format( - "{0}{1}_{2:000}-{3:000}-{4:000}__{5}.xml", - ArchiveConstants.OBJECTS_PATH, sceneObject.Name, - Math.Round(position.X), Math.Round(position.Y), Math.Round(position.Z), - sceneObject.UUID); - - m_archiveWriter.WriteFile(filename, serializedObject); + m_archiveWriter.WriteFile(ArchiveHelpers.CreateObjectPath(sceneObject), serializedObject); } m_log.InfoFormat("[ARCHIVER]: Added scene objects to archive."); diff --git a/OpenSim/Region/CoreModules/World/Archiver/AssetsRequest.cs b/OpenSim/Region/CoreModules/World/Archiver/AssetsRequest.cs index 4215f97343..a1451ce705 100644 --- a/OpenSim/Region/CoreModules/World/Archiver/AssetsRequest.cs +++ b/OpenSim/Region/CoreModules/World/Archiver/AssetsRequest.cs @@ -239,7 +239,7 @@ namespace OpenSim.Region.CoreModules.World.Archiver if (asset != null) { -// m_log.DebugFormat("[ARCHIVER]: Recording asset {0} as found", id); +// m_log.DebugFormat("[ARCHIVER]: Writing asset {0}", id); m_foundAssetUuids.Add(asset.FullID); m_assetsArchiver.WriteAsset(asset); } diff --git a/OpenSim/Region/CoreModules/World/Archiver/Tests/ArchiverTests.cs b/OpenSim/Region/CoreModules/World/Archiver/Tests/ArchiverTests.cs index 624dc22044..4d04af16e7 100644 --- a/OpenSim/Region/CoreModules/World/Archiver/Tests/ArchiverTests.cs +++ b/OpenSim/Region/CoreModules/World/Archiver/Tests/ArchiverTests.cs @@ -26,6 +26,7 @@ */ using System; +using System.Collections.Generic; using System.IO; using System.Reflection; using System.Threading; @@ -33,8 +34,8 @@ using log4net.Config; using NUnit.Framework; using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; +using OpenMetaverse.Assets; using OpenSim.Framework; - using OpenSim.Framework.Serialization; using OpenSim.Framework.Serialization.External; using OpenSim.Region.CoreModules.World.Serialiser; @@ -44,6 +45,9 @@ using OpenSim.Region.Framework.Scenes.Serialization; using OpenSim.Tests.Common; using OpenSim.Tests.Common.Mock; using OpenSim.Tests.Common.Setup; +using ArchiveConstants = OpenSim.Framework.Serialization.ArchiveConstants; +using TarArchiveReader = OpenSim.Framework.Serialization.TarArchiveReader; +using TarArchiveWriter = OpenSim.Framework.Serialization.TarArchiveWriter; namespace OpenSim.Region.CoreModules.World.Archiver.Tests { @@ -55,6 +59,8 @@ namespace OpenSim.Region.CoreModules.World.Archiver.Tests protected TestScene m_scene; protected ArchiverModule m_archiverModule; + + protected TaskInventoryItem m_soundItem; [SetUp] public void SetUp() @@ -124,10 +130,23 @@ namespace OpenSim.Region.CoreModules.World.Archiver.Tests //log4net.Config.XmlConfigurator.Configure(); SceneObjectPart part1 = CreateSceneObjectPart1(); - m_scene.AddNewSceneObject(new SceneObjectGroup(part1), false); + SceneObjectGroup sog1 = new SceneObjectGroup(part1); + m_scene.AddNewSceneObject(sog1, false); SceneObjectPart part2 = CreateSceneObjectPart2(); - m_scene.AddNewSceneObject(new SceneObjectGroup(part2), false); + + AssetNotecard nc = new AssetNotecard("Hello World!"); + UUID ncAssetUuid = new UUID("00000000-0000-0000-1000-000000000000"); + UUID ncItemUuid = new UUID("00000000-0000-0000-1100-000000000000"); + AssetBase ncAsset + = AssetHelpers.CreateAsset(ncAssetUuid, AssetType.Notecard, nc.AssetData, UUID.Zero); + m_scene.AssetService.Store(ncAsset); + SceneObjectGroup sog2 = new SceneObjectGroup(part2); + TaskInventoryItem ncItem + = new TaskInventoryItem { Name = "ncItem", AssetID = ncAssetUuid, ItemID = ncItemUuid }; + part2.Inventory.AddInventoryItem(ncItem, true); + + m_scene.AddNewSceneObject(sog2, false); MemoryStream archiveWriteStream = new MemoryStream(); m_scene.EventManager.OnOarFileSaved += SaveCompleted; @@ -151,18 +170,14 @@ namespace OpenSim.Region.CoreModules.World.Archiver.Tests TarArchiveReader tar = new TarArchiveReader(archiveReadStream); bool gotControlFile = false; - bool gotObject1File = false; - bool gotObject2File = false; - string expectedObject1FileName = string.Format( - "{0}_{1:000}-{2:000}-{3:000}__{4}.xml", - part1.Name, - Math.Round(part1.GroupPosition.X), Math.Round(part1.GroupPosition.Y), Math.Round(part1.GroupPosition.Z), - part1.UUID); - string expectedObject2FileName = string.Format( - "{0}_{1:000}-{2:000}-{3:000}__{4}.xml", - part2.Name, - Math.Round(part2.GroupPosition.X), Math.Round(part2.GroupPosition.Y), Math.Round(part2.GroupPosition.Z), - part2.UUID); + bool gotNcAssetFile = false; + + string expectedNcAssetFileName = string.Format("{0}_{1}", ncAssetUuid, "notecard.txt"); + + List foundPaths = new List(); + List expectedPaths = new List(); + expectedPaths.Add(ArchiveHelpers.CreateObjectPath(sog1)); + expectedPaths.Add(ArchiveHelpers.CreateObjectPath(sog2)); string filePath; TarArchiveReader.TarEntryType tarEntryType; @@ -173,26 +188,22 @@ namespace OpenSim.Region.CoreModules.World.Archiver.Tests { gotControlFile = true; } + else if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH)) + { + string fileName = filePath.Remove(0, ArchiveConstants.ASSETS_PATH.Length); + + Assert.That(fileName, Is.EqualTo(expectedNcAssetFileName)); + gotNcAssetFile = true; + } else if (filePath.StartsWith(ArchiveConstants.OBJECTS_PATH)) { - string fileName = filePath.Remove(0, ArchiveConstants.OBJECTS_PATH.Length); - - if (fileName.StartsWith(part1.Name)) - { - Assert.That(fileName, Is.EqualTo(expectedObject1FileName)); - gotObject1File = true; - } - else if (fileName.StartsWith(part2.Name)) - { - Assert.That(fileName, Is.EqualTo(expectedObject2FileName)); - gotObject2File = true; - } + foundPaths.Add(filePath); } } Assert.That(gotControlFile, Is.True, "No control file in archive"); - Assert.That(gotObject1File, Is.True, "No object1 file in archive"); - Assert.That(gotObject2File, Is.True, "No object2 file in archive"); + Assert.That(gotNcAssetFile, Is.True, "No notecard asset file in archive"); + Assert.That(foundPaths, Is.EquivalentTo(expectedPaths)); // TODO: Test presence of more files and contents of files. } diff --git a/OpenSim/Region/CoreModules/World/Estate/EstateManagementModule.cs b/OpenSim/Region/CoreModules/World/Estate/EstateManagementModule.cs index 91d40ab54a..940b535921 100644 --- a/OpenSim/Region/CoreModules/World/Estate/EstateManagementModule.cs +++ b/OpenSim/Region/CoreModules/World/Estate/EstateManagementModule.cs @@ -48,6 +48,10 @@ namespace OpenSim.Region.CoreModules.World.Estate private EstateTerrainXferHandler TerrainUploader; + public event ChangeDelegate OnRegionInfoChange; + public event ChangeDelegate OnEstateInfoChange; + public event MessageDelegate OnEstateMessage; + #region Packet Data Responders private void sendDetailedEstateData(IClientAPI remote_client, UUID invoice) @@ -137,6 +141,7 @@ namespace OpenSim.Region.CoreModules.World.Estate m_scene.RegionInfo.RegionSettings.AllowLandJoinDivide = false; m_scene.RegionInfo.RegionSettings.Save(); + TriggerRegionInfoChange(); sendRegionInfoPacketToAll(); } @@ -162,6 +167,7 @@ namespace OpenSim.Region.CoreModules.World.Estate break; } m_scene.RegionInfo.RegionSettings.Save(); + TriggerRegionInfoChange(); sendRegionInfoPacketToAll(); } @@ -187,6 +193,7 @@ namespace OpenSim.Region.CoreModules.World.Estate break; } m_scene.RegionInfo.RegionSettings.Save(); + TriggerRegionInfoChange(); sendRegionInfoPacketToAll(); } @@ -212,13 +219,14 @@ namespace OpenSim.Region.CoreModules.World.Estate m_scene.RegionInfo.RegionSettings.FixedSun = UseFixedSun; m_scene.RegionInfo.RegionSettings.SunPosition = SunHour; - TriggerEstateToolsSunUpdate(); + m_scene.TriggerEstateSunUpdate(); //m_log.Debug("[ESTATE]: UFS: " + UseFixedSun.ToString()); //m_log.Debug("[ESTATE]: SunHour: " + SunHour.ToString()); sendRegionInfoPacketToAll(); m_scene.RegionInfo.RegionSettings.Save(); + TriggerRegionInfoChange(); } private void handleEstateRestartSimRequest(IClientAPI remoteClient, int timeInSeconds) @@ -230,6 +238,7 @@ namespace OpenSim.Region.CoreModules.World.Estate { m_scene.RegionInfo.RegionSettings.Covenant = estateCovenantID; m_scene.RegionInfo.RegionSettings.Save(); + TriggerRegionInfoChange(); } private void handleEstateAccessDeltaRequest(IClientAPI remote_client, UUID invoice, int estateAccessType, UUID user) @@ -245,6 +254,7 @@ namespace OpenSim.Region.CoreModules.World.Estate { m_scene.RegionInfo.EstateSettings.AddEstateUser(user); m_scene.RegionInfo.EstateSettings.Save(); + TriggerEstateInfoChange(); remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AccessOptions, m_scene.RegionInfo.EstateSettings.EstateAccess, m_scene.RegionInfo.EstateSettings.EstateID); } else @@ -259,6 +269,7 @@ namespace OpenSim.Region.CoreModules.World.Estate { m_scene.RegionInfo.EstateSettings.RemoveEstateUser(user); m_scene.RegionInfo.EstateSettings.Save(); + TriggerEstateInfoChange(); remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AccessOptions, m_scene.RegionInfo.EstateSettings.EstateAccess, m_scene.RegionInfo.EstateSettings.EstateID); } @@ -273,6 +284,7 @@ namespace OpenSim.Region.CoreModules.World.Estate { m_scene.RegionInfo.EstateSettings.AddEstateGroup(user); m_scene.RegionInfo.EstateSettings.Save(); + TriggerEstateInfoChange(); remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AllowedGroups, m_scene.RegionInfo.EstateSettings.EstateGroups, m_scene.RegionInfo.EstateSettings.EstateID); } else @@ -286,6 +298,7 @@ namespace OpenSim.Region.CoreModules.World.Estate { m_scene.RegionInfo.EstateSettings.RemoveEstateGroup(user); m_scene.RegionInfo.EstateSettings.Save(); + TriggerEstateInfoChange(); remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AllowedGroups, m_scene.RegionInfo.EstateSettings.EstateGroups, m_scene.RegionInfo.EstateSettings.EstateID); } @@ -323,6 +336,7 @@ namespace OpenSim.Region.CoreModules.World.Estate m_scene.RegionInfo.EstateSettings.AddBan(item); m_scene.RegionInfo.EstateSettings.Save(); + TriggerEstateInfoChange(); ScenePresence s = m_scene.GetScenePresence(user); if (s != null) @@ -370,6 +384,7 @@ namespace OpenSim.Region.CoreModules.World.Estate { m_scene.RegionInfo.EstateSettings.RemoveBan(listitem.BannedUserID); m_scene.RegionInfo.EstateSettings.Save(); + TriggerEstateInfoChange(); } else { @@ -389,6 +404,7 @@ namespace OpenSim.Region.CoreModules.World.Estate { m_scene.RegionInfo.EstateSettings.AddEstateManager(user); m_scene.RegionInfo.EstateSettings.Save(); + TriggerEstateInfoChange(); remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.EstateManagers, m_scene.RegionInfo.EstateSettings.EstateManagers, m_scene.RegionInfo.EstateSettings.EstateID); } else @@ -402,6 +418,7 @@ namespace OpenSim.Region.CoreModules.World.Estate { m_scene.RegionInfo.EstateSettings.RemoveEstateManager(user); m_scene.RegionInfo.EstateSettings.Save(); + TriggerEstateInfoChange(); remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.EstateManagers, m_scene.RegionInfo.EstateSettings.EstateManagers, m_scene.RegionInfo.EstateSettings.EstateID); } @@ -424,10 +441,7 @@ namespace OpenSim.Region.CoreModules.World.Estate private void SendEstateBlueBoxMessage( IClientAPI remote_client, UUID invoice, UUID senderID, UUID sessionID, string senderName, string message) { - IDialogModule dm = m_scene.RequestModuleInterface(); - - if (dm != null) - dm.SendNotificationToUsersInEstate(senderID, senderName, message); + TriggerEstateMessage(senderID, senderName, message); } private void handleEstateDebugRegionRequest(IClientAPI remote_client, UUID invoice, UUID senderID, bool scripted, bool collisionEvents, bool physics) @@ -449,12 +463,16 @@ namespace OpenSim.Region.CoreModules.World.Estate m_scene.RegionInfo.RegionSettings.Save(); + TriggerRegionInfoChange(); m_scene.SetSceneCoreDebug(scripted, collisionEvents, physics); } private void handleEstateTeleportOneUserHomeRequest(IClientAPI remover_client, UUID invoice, UUID senderID, UUID prey) { + if (!m_scene.Permissions.CanIssueEstateCommand(remover_client.AgentId, false)) + return; + if (prey != UUID.Zero) { ScenePresence s = m_scene.GetScenePresence(prey); @@ -468,6 +486,9 @@ namespace OpenSim.Region.CoreModules.World.Estate private void handleEstateTeleportAllUsersHomeRequest(IClientAPI remover_client, UUID invoice, UUID senderID) { + if (!m_scene.Permissions.CanIssueEstateCommand(remover_client.AgentId, false)) + return; + m_scene.ForEachScenePresence(delegate(ScenePresence sp) { if (sp.UUID != senderID) @@ -860,8 +881,9 @@ namespace OpenSim.Region.CoreModules.World.Estate m_scene.RegionInfo.EstateSettings.DenyMinors = false; m_scene.RegionInfo.EstateSettings.Save(); + TriggerEstateInfoChange(); - TriggerEstateToolsSunUpdate(); + m_scene.TriggerEstateSunUpdate(); sendDetailedEstateData(remoteClient, invoice); } @@ -927,6 +949,7 @@ namespace OpenSim.Region.CoreModules.World.Estate break; } m_scene.RegionInfo.RegionSettings.Save(); + TriggerRegionInfoChange(); sendRegionInfoPacketToAll(); } @@ -972,6 +995,7 @@ namespace OpenSim.Region.CoreModules.World.Estate break; } m_scene.RegionInfo.RegionSettings.Save(); + TriggerRegionInfoChange(); sendRegionHandshakeToAll(); } } @@ -983,7 +1007,7 @@ namespace OpenSim.Region.CoreModules.World.Estate { // Sets up the sun module based no the saved Estate and Region Settings // DO NOT REMOVE or the sun will stop working - TriggerEstateToolsSunUpdate(); + m_scene.TriggerEstateSunUpdate(); } public void Close() @@ -1004,40 +1028,6 @@ namespace OpenSim.Region.CoreModules.World.Estate #region Other Functions - private void TriggerEstateToolsSunUpdate() - { - float sun; - if (m_scene.RegionInfo.RegionSettings.UseEstateSun) - { - sun = (float)m_scene.RegionInfo.EstateSettings.SunPosition; - if (m_scene.RegionInfo.EstateSettings.UseGlobalTime) - { - sun = m_scene.EventManager.GetCurrentTimeAsSunLindenHour() - 6.0f; - } - - // - m_scene.EventManager.TriggerEstateToolsSunUpdate( - m_scene.RegionInfo.RegionHandle, - m_scene.RegionInfo.EstateSettings.FixedSun, - m_scene.RegionInfo.RegionSettings.UseEstateSun, - sun); - } - else - { - // Use the Sun Position from the Region Settings - sun = (float)m_scene.RegionInfo.RegionSettings.SunPosition - 6.0f; - - m_scene.EventManager.TriggerEstateToolsSunUpdate( - m_scene.RegionInfo.RegionHandle, - m_scene.RegionInfo.RegionSettings.FixedSun, - m_scene.RegionInfo.RegionSettings.UseEstateSun, - sun); - } - - - } - - public void changeWaterHeight(float height) { setRegionTerrainSettings(height, @@ -1175,5 +1165,29 @@ namespace OpenSim.Region.CoreModules.World.Estate return false; } + + protected void TriggerRegionInfoChange() + { + ChangeDelegate change = OnRegionInfoChange; + + if (change != null) + change(m_scene.RegionInfo.RegionID); + } + + protected void TriggerEstateInfoChange() + { + ChangeDelegate change = OnEstateInfoChange; + + if (change != null) + change(m_scene.RegionInfo.RegionID); + } + + protected void TriggerEstateMessage(UUID fromID, string fromName, string message) + { + MessageDelegate onmessage = OnEstateMessage; + + if (onmessage != null) + onmessage(m_scene.RegionInfo.RegionID, fromID, fromName, message); + } } } diff --git a/OpenSim/Region/CoreModules/World/Land/LandChannel.cs b/OpenSim/Region/CoreModules/World/Land/LandChannel.cs index 1fbc733704..1ad4db2404 100644 --- a/OpenSim/Region/CoreModules/World/Land/LandChannel.cs +++ b/OpenSim/Region/CoreModules/World/Land/LandChannel.cs @@ -154,6 +154,22 @@ namespace OpenSim.Region.CoreModules.World.Land m_landManagementModule.UpdateLandObject(localID, data); } } + + public void Join(int start_x, int start_y, int end_x, int end_y, UUID attempting_user_id) + { + if (m_landManagementModule != null) + { + m_landManagementModule.Join(start_x, start_y, end_x, end_y, attempting_user_id); + } + } + + public void Subdivide(int start_x, int start_y, int end_x, int end_y, UUID attempting_user_id) + { + if (m_landManagementModule != null) + { + m_landManagementModule.Subdivide(start_x, start_y, end_x, end_y, attempting_user_id); + } + } public void ReturnObjectsInParcel(int localID, uint returnType, UUID[] agentIDs, UUID[] taskIDs, IClientAPI remoteClient) { diff --git a/OpenSim/Region/CoreModules/World/Land/LandManagementModule.cs b/OpenSim/Region/CoreModules/World/Land/LandManagementModule.cs index 5750aa42fc..4ccd0f03cb 100644 --- a/OpenSim/Region/CoreModules/World/Land/LandManagementModule.cs +++ b/OpenSim/Region/CoreModules/World/Land/LandManagementModule.cs @@ -948,6 +948,16 @@ namespace OpenSim.Region.CoreModules.World.Land masterLandObject.SendLandUpdateToAvatarsOverMe(); } + public void Join(int start_x, int start_y, int end_x, int end_y, UUID attempting_user_id) + { + join(start_x, start_y, end_x, end_y, attempting_user_id); + } + + public void Subdivide(int start_x, int start_y, int end_x, int end_y, UUID attempting_user_id) + { + subdivide(start_x, start_y, end_x, end_y, attempting_user_id); + } + #endregion #region Parcel Updating @@ -1144,6 +1154,7 @@ namespace OpenSim.Region.CoreModules.World.Land land.LandData.OwnerID = ownerID; land.LandData.GroupID = UUID.Zero; land.LandData.IsGroupOwned = false; + land.LandData.Flags &= ~(uint) (ParcelFlags.ForSale | ParcelFlags.ForSaleObjects | ParcelFlags.SellParcelObjects | ParcelFlags.ShowDirectory); m_scene.ForEachClient(SendParcelOverlay); land.SendLandUpdateToClient(true, remote_client); @@ -1166,6 +1177,7 @@ namespace OpenSim.Region.CoreModules.World.Land land.LandData.OwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner; land.LandData.GroupID = UUID.Zero; land.LandData.IsGroupOwned = false; + land.LandData.Flags &= ~(uint) (ParcelFlags.ForSale | ParcelFlags.ForSaleObjects | ParcelFlags.SellParcelObjects | ParcelFlags.ShowDirectory); m_scene.ForEachClient(SendParcelOverlay); land.SendLandUpdateToClient(true, remote_client); } @@ -1188,6 +1200,10 @@ namespace OpenSim.Region.CoreModules.World.Land land.LandData.ClaimDate = Util.UnixTimeSinceEpoch(); land.LandData.GroupID = UUID.Zero; land.LandData.IsGroupOwned = false; + land.LandData.SalePrice = 0; + land.LandData.AuthBuyerID = UUID.Zero; + land.LandData.Flags &= ~(uint) (ParcelFlags.ForSale | ParcelFlags.ForSaleObjects | ParcelFlags.SellParcelObjects | ParcelFlags.ShowDirectory); + m_scene.ForEachClient(SendParcelOverlay); land.SendLandUpdateToClient(true, remote_client); } diff --git a/OpenSim/Region/CoreModules/World/Land/LandObject.cs b/OpenSim/Region/CoreModules/World/Land/LandObject.cs index aca551479f..39451421c3 100644 --- a/OpenSim/Region/CoreModules/World/Land/LandObject.cs +++ b/OpenSim/Region/CoreModules/World/Land/LandObject.cs @@ -247,7 +247,7 @@ namespace OpenSim.Region.CoreModules.World.Land newData.ClaimPrice = claimprice; newData.SalePrice = 0; newData.AuthBuyerID = UUID.Zero; - newData.Flags &= ~(uint) (ParcelFlags.ForSale | ParcelFlags.ForSaleObjects | ParcelFlags.SellParcelObjects); + newData.Flags &= ~(uint) (ParcelFlags.ForSale | ParcelFlags.ForSaleObjects | ParcelFlags.SellParcelObjects | ParcelFlags.ShowDirectory); m_scene.LandChannel.UpdateLandObject(LandData.LocalID, newData); SendLandUpdateToAvatarsOverMe(true); @@ -260,6 +260,9 @@ namespace OpenSim.Region.CoreModules.World.Land newData.GroupID = groupID; newData.IsGroupOwned = true; + // Reset show in directory flag on deed + newData.Flags &= ~(uint) (ParcelFlags.ForSale | ParcelFlags.ForSaleObjects | ParcelFlags.SellParcelObjects | ParcelFlags.ShowDirectory); + m_scene.LandChannel.UpdateLandObject(LandData.LocalID, newData); SendLandUpdateToAvatarsOverMe(true); diff --git a/OpenSim/Region/CoreModules/World/Permissions/PermissionsModule.cs b/OpenSim/Region/CoreModules/World/Permissions/PermissionsModule.cs index 01359f0db9..69b247c350 100644 --- a/OpenSim/Region/CoreModules/World/Permissions/PermissionsModule.cs +++ b/OpenSim/Region/CoreModules/World/Permissions/PermissionsModule.cs @@ -1721,7 +1721,7 @@ namespace OpenSim.Region.CoreModules.World.Permissions DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name); if (m_bypassPermissions) return m_bypassPermissionsValue; - return true; + return GenericObjectPermission(userID, objectID, false); } private bool CanDelinkObject(UUID userID, UUID objectID) @@ -1729,7 +1729,7 @@ namespace OpenSim.Region.CoreModules.World.Permissions DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name); if (m_bypassPermissions) return m_bypassPermissionsValue; - return true; + return GenericObjectPermission(userID, objectID, false); } private bool CanBuyLand(UUID userID, ILandObject parcel, Scene scene) @@ -1894,4 +1894,4 @@ namespace OpenSim.Region.CoreModules.World.Permissions return(false); } } -} \ No newline at end of file +} diff --git a/OpenSim/Region/CoreModules/World/WorldMap/MapSearchModule.cs b/OpenSim/Region/CoreModules/World/WorldMap/MapSearchModule.cs index 56b50dc9ca..a1a4f9e125 100644 --- a/OpenSim/Region/CoreModules/World/WorldMap/MapSearchModule.cs +++ b/OpenSim/Region/CoreModules/World/WorldMap/MapSearchModule.cs @@ -135,7 +135,7 @@ namespace OpenSim.Region.CoreModules.World.WorldMap data.Y = 0; blocks.Add(data); - remoteClient.SendMapBlock(blocks, 0); + remoteClient.SendMapBlock(blocks, 2); } private Scene GetClientScene(IClientAPI client) diff --git a/OpenSim/Region/CoreModules/World/WorldMap/WorldMapModule.cs b/OpenSim/Region/CoreModules/World/WorldMap/WorldMapModule.cs index 2b0e83f52f..c6fb18d8f3 100644 --- a/OpenSim/Region/CoreModules/World/WorldMap/WorldMapModule.cs +++ b/OpenSim/Region/CoreModules/World/WorldMap/WorldMapModule.cs @@ -1000,7 +1000,7 @@ namespace OpenSim.Region.CoreModules.World.WorldMap return responsemap; } - public void LazySaveGeneratedMaptile(byte[] data, bool temporary) + public void RegenerateMaptile(byte[] data) { // Overwrites the local Asset cache with new maptile data // Assets are single write, this causes the asset server to ignore this update, @@ -1010,11 +1010,11 @@ namespace OpenSim.Region.CoreModules.World.WorldMap // map tile while protecting the (grid) asset database from bloat caused by a new asset each // time a mapimage is generated! - UUID lastMapRegionUUID = m_scene.RegionInfo.lastMapUUID; + UUID lastMapRegionUUID = m_scene.RegionInfo.RegionSettings.TerrainImageID; int lastMapRefresh = 0; int twoDays = 172800; - int RefreshSeconds = twoDays; +// int RefreshSeconds = twoDays; try { @@ -1030,21 +1030,9 @@ namespace OpenSim.Region.CoreModules.World.WorldMap { } - UUID TerrainImageUUID = UUID.Random(); + m_log.Debug("[MAPTILE]: STORING MAPTILE IMAGE"); - if (lastMapRegionUUID == UUID.Zero || (lastMapRefresh + RefreshSeconds) < Util.UnixTimeSinceEpoch()) - { - m_scene.RegionInfo.SaveLastMapUUID(TerrainImageUUID); - - m_log.Debug("[MAPTILE]: STORING MAPTILE IMAGE"); - } - else - { - TerrainImageUUID = lastMapRegionUUID; - m_log.Debug("[MAPTILE]: REUSING OLD MAPTILE IMAGE ID"); - } - - m_scene.RegionInfo.RegionSettings.TerrainImageID = TerrainImageUUID; + m_scene.RegionInfo.RegionSettings.TerrainImageID = UUID.Random(); AssetBase asset = new AssetBase( m_scene.RegionInfo.RegionSettings.TerrainImageID, @@ -1053,8 +1041,17 @@ namespace OpenSim.Region.CoreModules.World.WorldMap m_scene.RegionInfo.RegionID.ToString()); asset.Data = data; asset.Description = m_scene.RegionInfo.RegionName; - asset.Temporary = temporary; + asset.Temporary = false; + asset.Flags = AssetFlags.Maptile; + + // Store the new one + m_log.DebugFormat("[WORLDMAP]: Storing map tile {0}", asset.ID); m_scene.AssetService.Store(asset); + m_scene.RegionInfo.RegionSettings.Save(); + + // Delete the old one + m_log.DebugFormat("[WORLDMAP]: Deleting old map tile {0}", lastMapRegionUUID); + m_scene.AssetService.Delete(lastMapRegionUUID.ToString()); } private void MakeRootAgent(ScenePresence avatar) diff --git a/OpenSim/Region/DataSnapshot/ObjectSnapshot.cs b/OpenSim/Region/DataSnapshot/ObjectSnapshot.cs index f441aa9a84..6e699025b1 100644 --- a/OpenSim/Region/DataSnapshot/ObjectSnapshot.cs +++ b/OpenSim/Region/DataSnapshot/ObjectSnapshot.cs @@ -69,7 +69,7 @@ namespace OpenSim.Region.DataSnapshot.Providers byte RayEndIsIntersection) { this.Stale = true; }; client.OnLinkObjects += delegate (IClientAPI remoteClient, uint parent, List children) { this.Stale = true; }; - client.OnDelinkObjects += delegate(List primIds) { this.Stale = true; }; + client.OnDelinkObjects += delegate(List primIds, IClientAPI clientApi) { this.Stale = true; }; client.OnGrabUpdate += delegate(UUID objectID, Vector3 offset, Vector3 grapPos, IClientAPI remoteClient, List surfaceArgs) { this.Stale = true; }; client.OnObjectAttach += delegate(IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, diff --git a/OpenSim/Region/Examples/SimpleModule/MyNpcCharacter.cs b/OpenSim/Region/Examples/SimpleModule/MyNpcCharacter.cs index 38e1d117ad..eeb9e31f60 100644 --- a/OpenSim/Region/Examples/SimpleModule/MyNpcCharacter.cs +++ b/OpenSim/Region/Examples/SimpleModule/MyNpcCharacter.cs @@ -464,6 +464,10 @@ namespace OpenSim.Region.Examples.SimpleModule } + public void SendGenericMessage(string method, List message) + { + } + public void SendGenericMessage(string method, List message) { @@ -531,14 +535,6 @@ namespace OpenSim.Region.Examples.SimpleModule { } - public virtual void SendAvatarData(SendAvatarData data) - { - } - - public virtual void SendAvatarTerseUpdate(SendAvatarTerseData data) - { - } - public virtual void SendCoarseLocationUpdate(List users, List CoarseLocations) { } @@ -551,15 +547,15 @@ namespace OpenSim.Region.Examples.SimpleModule { } - public virtual void SendPrimitiveToClient(SendPrimitiveData data) + public void SendAvatarDataImmediate(ISceneEntity avatar) { } - public virtual void SendPrimTerseUpdate(SendPrimitiveTerseData data) + public void SendPrimUpdate(ISceneEntity entity, PrimUpdateFlags updateFlags) { } - public virtual void ReprioritizeUpdates(StateUpdateTypes type, UpdatePriorityHandler handler) + public void ReprioritizeUpdates() { } diff --git a/OpenSim/Region/Framework/Interfaces/IDialogModule.cs b/OpenSim/Region/Framework/Interfaces/IDialogModule.cs index 35b4b63152..be9764a7ea 100644 --- a/OpenSim/Region/Framework/Interfaces/IDialogModule.cs +++ b/OpenSim/Region/Framework/Interfaces/IDialogModule.cs @@ -119,19 +119,6 @@ namespace OpenSim.Region.Framework.Interfaces /// The message being sent to the user void SendNotificationToUsersInRegion(UUID fromAvatarID, string fromAvatarName, string message); - /// - /// Send a notification to all users in the estate. This notification should remain around until the - /// user explicitly dismisses it. - /// - /// - /// On the Linden Labs Second Client (as of 1.21), this is a big blue box message on the upper right of the - /// screen. - /// - /// The user sending the message - /// The name of the user doing the sending - /// The message being sent to the user - void SendNotificationToUsersInEstate(UUID fromAvatarID, string fromAvatarName, string message); - /// /// Send a textbox entry for the client to respond to /// diff --git a/OpenSim/Region/Framework/Interfaces/IEntityInventory.cs b/OpenSim/Region/Framework/Interfaces/IEntityInventory.cs index 2b90960936..fd43923cb3 100644 --- a/OpenSim/Region/Framework/Interfaces/IEntityInventory.cs +++ b/OpenSim/Region/Framework/Interfaces/IEntityInventory.cs @@ -161,6 +161,7 @@ namespace OpenSim.Region.Framework.Interfaces /// in this prim's inventory. /// false if the item did not exist, true if the update occurred successfully bool UpdateInventoryItem(TaskInventoryItem item); + bool UpdateInventoryItem(TaskInventoryItem item, bool fireScriptEvents); /// /// Remove an item from this entity's inventory diff --git a/OpenSim/Region/Framework/Interfaces/IEstateModule.cs b/OpenSim/Region/Framework/Interfaces/IEstateModule.cs index 890fa31df0..c850f7fd81 100644 --- a/OpenSim/Region/Framework/Interfaces/IEstateModule.cs +++ b/OpenSim/Region/Framework/Interfaces/IEstateModule.cs @@ -29,8 +29,15 @@ using OpenMetaverse; namespace OpenSim.Region.Framework.Interfaces { + public delegate void ChangeDelegate(UUID regionID); + public delegate void MessageDelegate(UUID regionID, UUID fromID, string fromName, string message); + public interface IEstateModule : IRegionModule { + event ChangeDelegate OnRegionInfoChange; + event ChangeDelegate OnEstateInfoChange; + event MessageDelegate OnEstateMessage; + uint GetRegionFlags(); bool IsManager(UUID avatarID); diff --git a/OpenSim/Region/Framework/Interfaces/IInventoryAccessModule.cs b/OpenSim/Region/Framework/Interfaces/IInventoryAccessModule.cs index 81852583c6..97f4188751 100644 --- a/OpenSim/Region/Framework/Interfaces/IInventoryAccessModule.cs +++ b/OpenSim/Region/Framework/Interfaces/IInventoryAccessModule.cs @@ -38,7 +38,7 @@ namespace OpenSim.Region.Framework.Interfaces public interface IInventoryAccessModule { UUID CapsUpdateInventoryItemAsset(IClientAPI remoteClient, UUID itemID, byte[] data); - UUID DeleteToInventory(DeRezAction action, UUID folderID, SceneObjectGroup objectGroup, IClientAPI remoteClient); + UUID DeleteToInventory(DeRezAction action, UUID folderID, List objectGroups, IClientAPI remoteClient); SceneObjectGroup RezObject(IClientAPI remoteClient, UUID itemID, Vector3 RayEnd, Vector3 RayStart, UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection, bool RezSelected, bool RemoveItem, UUID fromTaskID, bool attachment); diff --git a/OpenSim/Region/Framework/Interfaces/ILandChannel.cs b/OpenSim/Region/Framework/Interfaces/ILandChannel.cs index f71e31dcfa..20b8ab6b6d 100644 --- a/OpenSim/Region/Framework/Interfaces/ILandChannel.cs +++ b/OpenSim/Region/Framework/Interfaces/ILandChannel.cs @@ -76,5 +76,8 @@ namespace OpenSim.Region.Framework.Interfaces void setParcelObjectMaxOverride(overrideParcelMaxPrimCountDelegate overrideDel); void setSimulatorObjectMaxOverride(overrideSimulatorMaxPrimCountDelegate overrideDel); void SetParcelOtherCleanTime(IClientAPI remoteClient, int localID, int otherCleanTime); + + void Join(int start_x, int start_y, int end_x, int end_y, UUID attempting_user_id); + void Subdivide(int start_x, int start_y, int end_x, int end_y, UUID attempting_user_id); } } diff --git a/OpenSim/Region/Framework/Interfaces/IRegionModule.cs b/OpenSim/Region/Framework/Interfaces/IRegionModule.cs index 8eb906c7f8..e25a6e86dd 100644 --- a/OpenSim/Region/Framework/Interfaces/IRegionModule.cs +++ b/OpenSim/Region/Framework/Interfaces/IRegionModule.cs @@ -30,6 +30,9 @@ using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.Framework.Interfaces { + /// + /// DEPRECATED! Use INonSharedRegionModule or ISharedRegionModule instead + /// public interface IRegionModule { void Initialise(Scene scene, IConfigSource source); diff --git a/OpenSim/Region/Framework/Interfaces/IWorldMapModule.cs b/OpenSim/Region/Framework/Interfaces/IWorldMapModule.cs index de1bcd4382..ac6afed9ce 100644 --- a/OpenSim/Region/Framework/Interfaces/IWorldMapModule.cs +++ b/OpenSim/Region/Framework/Interfaces/IWorldMapModule.cs @@ -29,6 +29,6 @@ namespace OpenSim.Region.Framework.Interfaces { public interface IWorldMapModule { - void LazySaveGeneratedMaptile(byte[] data, bool temporary); + void RegenerateMaptile(byte[] data); } } diff --git a/OpenSim/Region/Framework/Scenes/AsyncSceneObjectGroupDeleter.cs b/OpenSim/Region/Framework/Scenes/AsyncSceneObjectGroupDeleter.cs index c08b961373..241cac0f11 100644 --- a/OpenSim/Region/Framework/Scenes/AsyncSceneObjectGroupDeleter.cs +++ b/OpenSim/Region/Framework/Scenes/AsyncSceneObjectGroupDeleter.cs @@ -40,7 +40,7 @@ namespace OpenSim.Region.Framework.Scenes { public DeRezAction action; public IClientAPI remoteClient; - public SceneObjectGroup objectGroup; + public List objectGroups; public UUID folderID; public bool permissionToDelete; } @@ -75,7 +75,7 @@ namespace OpenSim.Region.Framework.Scenes /// Delete the given object from the scene /// public void DeleteToInventory(DeRezAction action, UUID folderID, - SceneObjectGroup objectGroup, IClientAPI remoteClient, + List objectGroups, IClientAPI remoteClient, bool permissionToDelete) { if (Enabled) @@ -87,7 +87,7 @@ namespace OpenSim.Region.Framework.Scenes DeleteToInventoryHolder dtis = new DeleteToInventoryHolder(); dtis.action = action; dtis.folderID = folderID; - dtis.objectGroup = objectGroup; + dtis.objectGroups = objectGroups; dtis.remoteClient = remoteClient; dtis.permissionToDelete = permissionToDelete; @@ -103,7 +103,10 @@ namespace OpenSim.Region.Framework.Scenes // This is not ideal since the object will still be available for manipulation when it should be, but it's // better than losing the object for now. if (permissionToDelete) - objectGroup.DeleteGroup(false); + { + foreach (SceneObjectGroup g in objectGroups) + g.DeleteGroup(false); + } } private void InventoryRunDeleteTimer(object sender, ElapsedEventArgs e) @@ -140,9 +143,12 @@ namespace OpenSim.Region.Framework.Scenes { IInventoryAccessModule invAccess = m_scene.RequestModuleInterface(); if (invAccess != null) - invAccess.DeleteToInventory(x.action, x.folderID, x.objectGroup, x.remoteClient); + invAccess.DeleteToInventory(x.action, x.folderID, x.objectGroups, x.remoteClient); if (x.permissionToDelete) - m_scene.DeleteSceneObject(x.objectGroup, false); + { + foreach (SceneObjectGroup g in x.objectGroups) + m_scene.DeleteSceneObject(g, false); + } } catch (Exception e) { diff --git a/OpenSim/Region/Framework/Scenes/EntityBase.cs b/OpenSim/Region/Framework/Scenes/EntityBase.cs index 1c76c546e5..4e25c468c0 100644 --- a/OpenSim/Region/Framework/Scenes/EntityBase.cs +++ b/OpenSim/Region/Framework/Scenes/EntityBase.cs @@ -28,11 +28,12 @@ using System; using System.Runtime.Serialization; using System.Security.Permissions; +using OpenSim.Framework; using OpenMetaverse; namespace OpenSim.Region.Framework.Scenes { - public abstract class EntityBase + public abstract class EntityBase : ISceneEntity { /// /// The scene to which this entity belongs diff --git a/OpenSim/Region/Framework/Scenes/Prioritizer.cs b/OpenSim/Region/Framework/Scenes/Prioritizer.cs new file mode 100644 index 0000000000..1eb0c286e8 --- /dev/null +++ b/OpenSim/Region/Framework/Scenes/Prioritizer.cs @@ -0,0 +1,191 @@ +using System; +using System.Collections.Generic; +using log4net; +using Nini.Config; +using OpenSim.Framework; +using OpenMetaverse; +using OpenSim.Region.Physics.Manager; + +/* + * Steps to add a new prioritization policy: + * + * - Add a new value to the UpdatePrioritizationSchemes enum. + * - Specify this new value in the [InterestManagement] section of your + * OpenSim.ini. The name in the config file must match the enum value name + * (although it is not case sensitive). + * - Write a new GetPriorityBy*() method in this class. + * - Add a new entry to the switch statement in GetUpdatePriority() that calls + * your method. + */ + +namespace OpenSim.Region.Framework.Scenes +{ + public enum UpdatePrioritizationSchemes + { + Time = 0, + Distance = 1, + SimpleAngularDistance = 2, + FrontBack = 3, + BestAvatarResponsiveness = 4, + } + + public class Prioritizer + { + private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + + private Scene m_scene; + + public Prioritizer(Scene scene) + { + m_scene = scene; + } + + public double GetUpdatePriority(IClientAPI client, ISceneEntity entity) + { + switch (m_scene.UpdatePrioritizationScheme) + { + case UpdatePrioritizationSchemes.Time: + return GetPriorityByTime(); + case UpdatePrioritizationSchemes.Distance: + return GetPriorityByDistance(client, entity); + case UpdatePrioritizationSchemes.SimpleAngularDistance: + return GetPriorityByDistance(client, entity); // TODO: Reimplement SimpleAngularDistance + case UpdatePrioritizationSchemes.FrontBack: + return GetPriorityByFrontBack(client, entity); + case UpdatePrioritizationSchemes.BestAvatarResponsiveness: + return GetPriorityByBestAvatarResponsiveness(client, entity); + default: + throw new InvalidOperationException("UpdatePrioritizationScheme not defined."); + } + } + + private double GetPriorityByTime() + { + return DateTime.UtcNow.ToOADate(); + } + + private double GetPriorityByDistance(IClientAPI client, ISceneEntity entity) + { + ScenePresence presence = m_scene.GetScenePresence(client.AgentId); + if (presence != null) + { + // If this is an update for our own avatar give it the highest priority + if (presence == entity) + return 0.0; + + // Use the camera position for local agents and avatar position for remote agents + Vector3 presencePos = (presence.IsChildAgent) ? + presence.AbsolutePosition : + presence.CameraPosition; + + // Use group position for child prims + Vector3 entityPos; + if (entity is SceneObjectPart) + entityPos = m_scene.GetGroupByPrim(entity.LocalId).AbsolutePosition; + else + entityPos = entity.AbsolutePosition; + + return Vector3.DistanceSquared(presencePos, entityPos); + } + + return double.NaN; + } + + private double GetPriorityByFrontBack(IClientAPI client, ISceneEntity entity) + { + ScenePresence presence = m_scene.GetScenePresence(client.AgentId); + if (presence != null) + { + // If this is an update for our own avatar give it the highest priority + if (presence == entity) + return 0.0; + + // Use group position for child prims + Vector3 entityPos = entity.AbsolutePosition; + if (entity is SceneObjectPart) + entityPos = m_scene.GetGroupByPrim(entity.LocalId).AbsolutePosition; + else + entityPos = entity.AbsolutePosition; + + if (!presence.IsChildAgent) + { + // Root agent. Use distance from camera and a priority decrease for objects behind us + Vector3 camPosition = presence.CameraPosition; + Vector3 camAtAxis = presence.CameraAtAxis; + + // Distance + double priority = Vector3.DistanceSquared(camPosition, entityPos); + + // Plane equation + float d = -Vector3.Dot(camPosition, camAtAxis); + float p = Vector3.Dot(camAtAxis, entityPos) + d; + if (p < 0.0f) priority *= 2.0; + + return priority; + } + else + { + // Child agent. Use the normal distance method + Vector3 presencePos = presence.AbsolutePosition; + + return Vector3.DistanceSquared(presencePos, entityPos); + } + } + + return double.NaN; + } + + private double GetPriorityByBestAvatarResponsiveness(IClientAPI client, ISceneEntity entity) + { + ScenePresence presence = m_scene.GetScenePresence(client.AgentId); + if (presence != null) + { + // If this is an update for our own avatar give it the highest priority + if (presence == entity) + return 0.0; + + // Use group position for child prims + Vector3 entityPos = entity.AbsolutePosition; + if (entity is SceneObjectPart) + entityPos = m_scene.GetGroupByPrim(entity.LocalId).AbsolutePosition; + else + entityPos = entity.AbsolutePosition; + + if (!presence.IsChildAgent) + { + if (entity is ScenePresence) + return 1.0; + + // Root agent. Use distance from camera and a priority decrease for objects behind us + Vector3 camPosition = presence.CameraPosition; + Vector3 camAtAxis = presence.CameraAtAxis; + + // Distance + double priority = Vector3.DistanceSquared(camPosition, entityPos); + + // Plane equation + float d = -Vector3.Dot(camPosition, camAtAxis); + float p = Vector3.Dot(camAtAxis, entityPos) + d; + if (p < 0.0f) priority *= 2.0; + + if (entity is SceneObjectPart) + { + PhysicsActor physActor = ((SceneObjectPart)entity).ParentGroup.RootPart.PhysActor; + if (physActor == null || !physActor.IsPhysical) + priority+=100; + } + return priority; + } + else + { + // Child agent. Use the normal distance method + Vector3 presencePos = presence.AbsolutePosition; + + return Vector3.DistanceSquared(presencePos, entityPos); + } + } + + return double.NaN; + } + } +} diff --git a/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs b/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs index 15b523095f..cc7b6485f7 100644 --- a/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs +++ b/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs @@ -382,29 +382,31 @@ namespace OpenSim.Region.Framework.Scenes itemCopy.InvType = item.InvType; itemCopy.Folder = recipientFolderId; - if (Permissions.PropagatePermissions()) + if (Permissions.PropagatePermissions() && recipient != senderId) { + // First, make sore base is limited to the next perms + itemCopy.BasePermissions = item.BasePermissions & item.NextPermissions; + // By default, current equals base + itemCopy.CurrentPermissions = itemCopy.BasePermissions; + + // If this is an object, replace current perms + // with folded perms if (item.InvType == (int)InventoryType.Object) { - itemCopy.BasePermissions &= ~(uint)(PermissionMask.Copy | PermissionMask.Modify | PermissionMask.Transfer); - itemCopy.BasePermissions |= (item.CurrentPermissions & 7) << 13; - } - else - { - itemCopy.BasePermissions = item.BasePermissions & item.NextPermissions; + itemCopy.CurrentPermissions &= ~(uint)(PermissionMask.Copy | PermissionMask.Modify | PermissionMask.Transfer); + itemCopy.CurrentPermissions |= (item.CurrentPermissions & 7) << 13; } - itemCopy.CurrentPermissions = itemCopy.BasePermissions; - if ((item.CurrentPermissions & 8) != 0) // Propagate slam bit - { - itemCopy.BasePermissions &= item.NextPermissions; - itemCopy.CurrentPermissions = itemCopy.BasePermissions; - itemCopy.CurrentPermissions |= 8; - } + // Ensure there is no escalation + itemCopy.CurrentPermissions &= item.NextPermissions; + + // Need slam bit on xfer + itemCopy.CurrentPermissions |= 8; itemCopy.NextPermissions = item.NextPermissions; - itemCopy.EveryOnePermissions = item.EveryOnePermissions & item.NextPermissions; - itemCopy.GroupPermissions = item.GroupPermissions & item.NextPermissions; + + itemCopy.EveryOnePermissions = 0; + itemCopy.GroupPermissions = 0; } else { @@ -415,6 +417,25 @@ namespace OpenSim.Region.Framework.Scenes itemCopy.BasePermissions = item.BasePermissions; } + if (itemCopy.Folder == UUID.Zero) + { + InventoryFolderBase folder = InventoryService.GetFolderForType(recipient, (AssetType)itemCopy.AssetType); + + if (folder != null) + { + itemCopy.Folder = folder.ID; + } + else + { + InventoryFolderBase root = InventoryService.GetRootFolder(recipient); + + if (root != null) + itemCopy.Folder = root.ID; + else + return null; // No destination + } + } + itemCopy.GroupID = UUID.Zero; itemCopy.GroupOwned = false; itemCopy.Flags = item.Flags; @@ -876,12 +897,12 @@ namespace OpenSim.Region.Framework.Scenes if ((part.OwnerID != destAgent) && Permissions.PropagatePermissions()) { + agentItem.BasePermissions = taskItem.BasePermissions & taskItem.NextPermissions; if (taskItem.InvType == (int)InventoryType.Object) - agentItem.BasePermissions = taskItem.BasePermissions & ((taskItem.CurrentPermissions & 7) << 13); - else - agentItem.BasePermissions = taskItem.BasePermissions; - agentItem.BasePermissions &= taskItem.NextPermissions; - agentItem.CurrentPermissions = agentItem.BasePermissions | 8; + agentItem.CurrentPermissions = agentItem.BasePermissions & ((taskItem.CurrentPermissions & 7) << 13); + agentItem.CurrentPermissions = agentItem.BasePermissions ; + + agentItem.CurrentPermissions |= 8; agentItem.NextPermissions = taskItem.NextPermissions; agentItem.EveryOnePermissions = taskItem.EveryonePermissions & taskItem.NextPermissions; agentItem.GroupPermissions = taskItem.GroupPermissions & taskItem.NextPermissions; @@ -1135,6 +1156,21 @@ namespace OpenSim.Region.Framework.Scenes if (folder == null) return; + // TODO: This code for looking in the folder for the library should be folded somewhere else + // so that this class doesn't have to know the details (and so that multiple libraries, etc. + // can be handled transparently). + InventoryFolderImpl fold = null; + if (LibraryService != null && LibraryService.LibraryRootFolder != null) + { + if ((fold = LibraryService.LibraryRootFolder.FindFolder(folder.ID)) != null) + { + client.SendInventoryFolderDetails( + fold.Owner, folder.ID, fold.RequestListOfItems(), + fold.RequestListOfFolders(), fold.Version, fetchFolders, fetchItems); + return; + } + } + // Fetch the folder contents InventoryCollection contents = InventoryService.GetFolderContent(client.AgentId, folder.ID); @@ -1145,7 +1181,7 @@ namespace OpenSim.Region.Framework.Scenes //m_log.DebugFormat("[AGENT INVENTORY]: Sending inventory folder contents ({0} nodes) for \"{1}\" to {2} {3}", // contents.Folders.Count + contents.Items.Count, containingFolder.Name, client.FirstName, client.LastName); - if (containingFolder != null) + if (containingFolder != null && containingFolder != null) client.SendInventoryFolderDetails(client.AgentId, folder.ID, contents.Items, contents.Folders, containingFolder.Version, fetchFolders, fetchItems); } @@ -1495,79 +1531,101 @@ namespace OpenSim.Region.Framework.Scenes public virtual void DeRezObject(IClientAPI remoteClient, uint localID, UUID groupID, DeRezAction action, UUID destinationID) { - SceneObjectPart part = GetSceneObjectPart(localID); - if (part == null) - return; + DeRezObjects(remoteClient, new List() { localID} , groupID, action, destinationID); + } - if (part.ParentGroup == null || part.ParentGroup.IsDeleted) - return; + public virtual void DeRezObjects(IClientAPI remoteClient, List localIDs, + UUID groupID, DeRezAction action, UUID destinationID) + { + // First, see of we can perform the requested action and + // build a list of eligible objects + List deleteIDs = new List(); + List deleteGroups = new List(); - // Can't delete child prims - if (part != part.ParentGroup.RootPart) - return; + // Start with true for both, then remove the flags if objects + // that we can't derez are part of the selection + bool permissionToTake = true; + bool permissionToTakeCopy = true; + bool permissionToDelete = true; - SceneObjectGroup grp = part.ParentGroup; - - //force a database backup/update on this SceneObjectGroup - //So that we know the database is upto date, for when deleting the object from it - ForceSceneObjectBackup(grp); - - bool permissionToTake = false; - bool permissionToDelete = false; - - if (action == DeRezAction.SaveToExistingUserInventoryItem) + foreach (uint localID in localIDs) { - if (grp.OwnerID == remoteClient.AgentId && grp.RootPart.FromUserInventoryItemID != UUID.Zero) - { - permissionToTake = true; + // Invalid id + SceneObjectPart part = GetSceneObjectPart(localID); + if (part == null) + continue; + + // Already deleted by someone else + if (part.ParentGroup == null || part.ParentGroup.IsDeleted) + continue; + + // Can't delete child prims + if (part != part.ParentGroup.RootPart) + continue; + + SceneObjectGroup grp = part.ParentGroup; + + deleteIDs.Add(localID); + deleteGroups.Add(grp); + + // Force a database backup/update on this SceneObjectGroup + // So that we know the database is upto date, + // for when deleting the object from it + ForceSceneObjectBackup(grp); + + if (!Permissions.CanTakeCopyObject(grp.UUID, remoteClient.AgentId)) + permissionToTakeCopy = false; + if (!Permissions.CanTakeObject(grp.UUID, remoteClient.AgentId)) + permissionToTake = false; + + if (!Permissions.CanDeleteObject(grp.UUID, remoteClient.AgentId)) permissionToDelete = false; - } - } - else if (action == DeRezAction.TakeCopy) - { - permissionToTake = - Permissions.CanTakeCopyObject( - grp.UUID, - remoteClient.AgentId); - } - else if (action == DeRezAction.GodTakeCopy) - { - permissionToTake = - Permissions.IsGod( - remoteClient.AgentId); - } - else if (action == DeRezAction.Take) - { - permissionToTake = - Permissions.CanTakeObject( - grp.UUID, - remoteClient.AgentId); - //If they can take, they can delete! - permissionToDelete = permissionToTake; } - else if (action == DeRezAction.Delete) + + // Handle god perms + if (Permissions.IsGod(remoteClient.AgentId)) { - permissionToTake = - Permissions.CanDeleteObject( - grp.UUID, - remoteClient.AgentId); - permissionToDelete = permissionToTake; + permissionToTake = true; + permissionToTakeCopy = true; + permissionToDelete = true; } - else if (action == DeRezAction.Return) + + // If we're re-saving, we don't even want to delete + if (action == DeRezAction.SaveToExistingUserInventoryItem) + permissionToDelete = false; + + // if we want to take a copy,, we also don't want to delete + // Note: after this point, the permissionToTakeCopy flag + // becomes irrelevant. It already includes the permissionToTake + // permission and after excluding no copy items here, we can + // just use that. + if (action == DeRezAction.TakeCopy) + { + // If we don't have permission, stop right here + if (!permissionToTakeCopy) + return; + + // Don't delete + permissionToDelete = false; + } + + if (action == DeRezAction.Return) { if (remoteClient != null) { - permissionToTake = - Permissions.CanReturnObjects( + if (Permissions.CanReturnObjects( null, remoteClient.AgentId, - new List() {grp}); - permissionToDelete = permissionToTake; - - if (permissionToDelete) + deleteGroups)) { - AddReturn(grp.OwnerID, grp.Name, grp.AbsolutePosition, "parcel owner return"); + permissionToTake = true; + permissionToDelete = true; + + foreach (SceneObjectGroup g in deleteGroups) + { + AddReturn(g.OwnerID, g.Name, g.AbsolutePosition, "parcel owner return"); + } } } else // Auto return passes through here with null agent @@ -1576,22 +1634,17 @@ namespace OpenSim.Region.Framework.Scenes permissionToDelete = true; } } - else - { - m_log.DebugFormat( - "[AGENT INVENTORY]: Ignoring unexpected derez action {0} for {1}", action, remoteClient.Name); - return; - } if (permissionToTake) { m_asyncSceneObjectDeleter.DeleteToInventory( - action, destinationID, grp, remoteClient, + action, destinationID, deleteGroups, remoteClient, permissionToDelete); } else if (permissionToDelete) { - DeleteSceneObject(grp, false); + foreach (SceneObjectGroup g in deleteGroups) + DeleteSceneObject(g, false); } } @@ -1941,5 +1994,73 @@ namespace OpenSim.Region.Framework.Scenes part.GetProperties(remoteClient); } } + + public void DelinkObjects(List primIds, IClientAPI client) + { + List parts = new List(); + + foreach (uint localID in primIds) + { + SceneObjectPart part = GetSceneObjectPart(localID); + + if (part == null) + continue; + + if (Permissions.CanDelinkObject(client.AgentId, part.ParentGroup.RootPart.UUID)) + parts.Add(part); + } + + m_sceneGraph.DelinkObjects(parts); + } + + public void LinkObjects(IClientAPI client, uint parentPrimId, List childPrimIds) + { + List owners = new List(); + + List children = new List(); + SceneObjectPart root = GetSceneObjectPart(parentPrimId); + + if (root == null) + { + m_log.DebugFormat("[LINK]: Can't find linkset root prim {0{", parentPrimId); + return; + } + + if (!Permissions.CanLinkObject(client.AgentId, root.ParentGroup.RootPart.UUID)) + { + m_log.DebugFormat("[LINK]: Refusing link. No permissions on root prim"); + return; + } + + foreach (uint localID in childPrimIds) + { + SceneObjectPart part = GetSceneObjectPart(localID); + + if (part == null) + continue; + + if (!owners.Contains(part.OwnerID)) + owners.Add(part.OwnerID); + + if (Permissions.CanLinkObject(client.AgentId, part.ParentGroup.RootPart.UUID)) + children.Add(part); + } + + // Must be all one owner + // + if (owners.Count > 1) + { + m_log.DebugFormat("[LINK]: Refusing link. Too many owners"); + return; + } + + if (children.Count == 0) + { + m_log.DebugFormat("[LINK]: Refusing link. No permissions to link any of the children"); + return; + } + + m_sceneGraph.LinkObjects(root, children); + } } } diff --git a/OpenSim/Region/Framework/Scenes/Scene.PacketHandlers.cs b/OpenSim/Region/Framework/Scenes/Scene.PacketHandlers.cs index bc1023075d..e25b1f1503 100644 --- a/OpenSim/Region/Framework/Scenes/Scene.PacketHandlers.cs +++ b/OpenSim/Region/Framework/Scenes/Scene.PacketHandlers.cs @@ -513,8 +513,8 @@ namespace OpenSim.Region.Framework.Scenes { // FIXME MAYBE: We're not handling sortOrder! - // TODO: This code for looking in the folder for the library should be folded back into the - // CachedUserInfo so that this class doesn't have to know the details (and so that multiple libraries, etc. + // TODO: This code for looking in the folder for the library should be folded somewhere else + // so that this class doesn't have to know the details (and so that multiple libraries, etc. // can be handled transparently). InventoryFolderImpl fold = null; if (LibraryService != null && LibraryService.LibraryRootFolder != null) diff --git a/OpenSim/Region/Framework/Scenes/Scene.cs b/OpenSim/Region/Framework/Scenes/Scene.cs index 12defd6858..18fff3d4b7 100644 --- a/OpenSim/Region/Framework/Scenes/Scene.cs +++ b/OpenSim/Region/Framework/Scenes/Scene.cs @@ -58,13 +58,6 @@ namespace OpenSim.Region.Framework.Scenes public partial class Scene : SceneBase { - public enum UpdatePrioritizationSchemes { - Time = 0, - Distance = 1, - SimpleAngularDistance = 2, - FrontBack = 3, - } - public delegate void SynchronizeSceneHandler(Scene scene); public SynchronizeSceneHandler SynchronizeScene = null; @@ -304,7 +297,18 @@ namespace OpenSim.Region.Framework.Scenes return m_AvatarService; } } - + + protected IGridUserService m_GridUserService; + public IGridUserService GridUserService + { + get + { + if (m_GridUserService == null) + m_GridUserService = RequestModuleInterface(); + return m_GridUserService; + } + } + protected IXMLRPC m_xmlrpcModule; protected IWorldComm m_worldCommModule; public IAttachmentsModule AttachmentsModule { get; set; } @@ -404,12 +408,6 @@ namespace OpenSim.Region.Framework.Scenes private int m_lastUpdate; private bool m_firstHeartbeat = true; - private UpdatePrioritizationSchemes m_update_prioritization_scheme = UpdatePrioritizationSchemes.Time; - private bool m_reprioritization_enabled = true; - private double m_reprioritization_interval = 5000.0; - private double m_root_reprioritization_distance = 10.0; - private double m_child_reprioritization_distance = 20.0; - private object m_deleting_scene_object = new object(); // the minimum time that must elapse before a changed object will be considered for persisted @@ -417,15 +415,21 @@ namespace OpenSim.Region.Framework.Scenes // the maximum time that must elapse before a changed object will be considered for persisted public long m_persistAfter = DEFAULT_MAX_TIME_FOR_PERSISTENCE * 10000000L; + private UpdatePrioritizationSchemes m_priorityScheme = UpdatePrioritizationSchemes.Time; + private bool m_reprioritizationEnabled = true; + private double m_reprioritizationInterval = 5000.0; + private double m_rootReprioritizationDistance = 10.0; + private double m_childReprioritizationDistance = 20.0; + #endregion #region Properties - public UpdatePrioritizationSchemes UpdatePrioritizationScheme { get { return this.m_update_prioritization_scheme; } } - public bool IsReprioritizationEnabled { get { return m_reprioritization_enabled; } } - public double ReprioritizationInterval { get { return m_reprioritization_interval; } } - public double RootReprioritizationDistance { get { return m_root_reprioritization_distance; } } - public double ChildReprioritizationDistance { get { return m_child_reprioritization_distance; } } + public UpdatePrioritizationSchemes UpdatePrioritizationScheme { get { return m_priorityScheme; } } + public bool IsReprioritizationEnabled { get { return m_reprioritizationEnabled; } } + public double ReprioritizationInterval { get { return m_reprioritizationInterval; } } + public double RootReprioritizationDistance { get { return m_rootReprioritizationDistance; } } + public double ChildReprioritizationDistance { get { return m_childReprioritizationDistance; } } public AgentCircuitManager AuthenticateHandler { @@ -627,6 +631,8 @@ namespace OpenSim.Region.Framework.Scenes m_asyncSceneObjectDeleter = new AsyncSceneObjectGroupDeleter(this); m_asyncSceneObjectDeleter.Enabled = true; + #region Region Settings + // Load region settings m_regInfo.RegionSettings = m_storageManager.DataStore.LoadRegionSettings(m_regInfo.RegionID); if (m_storageManager.EstateDataStore != null) @@ -673,6 +679,12 @@ namespace OpenSim.Region.Framework.Scenes } } + #endregion Region Settings + + MainConsole.Instance.Commands.AddCommand("region", false, "reload estate", + "reload estate", + "Reload the estate data", HandleReloadEstate); + //Bind Storage Manager functions to some land manager functions for this scene EventManager.OnLandObjectAdded += new EventManager.LandObjectAdded(m_storageManager.DataStore.StoreLandObject); @@ -713,6 +725,8 @@ namespace OpenSim.Region.Framework.Scenes m_simulatorVersion = simulatorVersion + " (" + Util.GetRuntimeInformation() + ")"; + #region Region Config + try { // Region config overrides global config @@ -771,38 +785,6 @@ namespace OpenSim.Region.Framework.Scenes m_strictAccessControl = startupConfig.GetBoolean("StrictAccessControl", m_strictAccessControl); - IConfig interest_management_config = m_config.Configs["InterestManagement"]; - if (interest_management_config != null) - { - string update_prioritization_scheme = interest_management_config.GetString("UpdatePrioritizationScheme", "Time").Trim().ToLower(); - switch (update_prioritization_scheme) - { - case "time": - m_update_prioritization_scheme = UpdatePrioritizationSchemes.Time; - break; - case "distance": - m_update_prioritization_scheme = UpdatePrioritizationSchemes.Distance; - break; - case "simpleangulardistance": - m_update_prioritization_scheme = UpdatePrioritizationSchemes.SimpleAngularDistance; - break; - case "frontback": - m_update_prioritization_scheme = UpdatePrioritizationSchemes.FrontBack; - break; - default: - m_log.Warn("[SCENE]: UpdatePrioritizationScheme was not recognized, setting to default settomg of Time"); - m_update_prioritization_scheme = UpdatePrioritizationSchemes.Time; - break; - } - - m_reprioritization_enabled = interest_management_config.GetBoolean("ReprioritizationEnabled", true); - m_reprioritization_interval = interest_management_config.GetDouble("ReprioritizationInterval", 5000.0); - m_root_reprioritization_distance = interest_management_config.GetDouble("RootReprioritizationDistance", 10.0); - m_child_reprioritization_distance = interest_management_config.GetDouble("ChildReprioritizationDistance", 20.0); - } - - m_log.Info("[SCENE]: Using the " + m_update_prioritization_scheme + " prioritization scheme"); - #region BinaryStats try @@ -839,6 +821,38 @@ namespace OpenSim.Region.Framework.Scenes { m_log.Warn("[SCENE]: Failed to load StartupConfig"); } + + #endregion Region Config + + #region Interest Management + + if (m_config != null) + { + IConfig interestConfig = m_config.Configs["InterestManagement"]; + if (interestConfig != null) + { + string update_prioritization_scheme = interestConfig.GetString("UpdatePrioritizationScheme", "Time").Trim().ToLower(); + + try + { + m_priorityScheme = (UpdatePrioritizationSchemes)Enum.Parse(typeof(UpdatePrioritizationSchemes), update_prioritization_scheme, true); + } + catch (Exception) + { + m_log.Warn("[PRIORITIZER]: UpdatePrioritizationScheme was not recognized, setting to default prioritizer Time"); + m_priorityScheme = UpdatePrioritizationSchemes.Time; + } + + m_reprioritizationEnabled = interestConfig.GetBoolean("ReprioritizationEnabled", true); + m_reprioritizationInterval = interestConfig.GetDouble("ReprioritizationInterval", 5000.0); + m_rootReprioritizationDistance = interestConfig.GetDouble("RootReprioritizationDistance", 10.0); + m_childReprioritizationDistance = interestConfig.GetDouble("ChildReprioritizationDistance", 20.0); + } + } + + m_log.Info("[SCENE]: Using the " + m_priorityScheme + " prioritization scheme"); + + #endregion Interest Management } /// @@ -1336,8 +1350,8 @@ namespace OpenSim.Region.Framework.Scenes if (defaultRegions != null && defaultRegions.Count >= 1) home = defaultRegions[0]; - if (PresenceService != null && home != null) - PresenceService.SetHomeLocation(account.PrincipalID.ToString(), home.RegionID, new Vector3(128, 128, 0), new Vector3(0, 1, 0)); + if (GridUserService != null && home != null) + GridUserService.SetHome(account.PrincipalID.ToString(), home.RegionID, new Vector3(128, 128, 0), new Vector3(0, 1, 0)); else m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to set home for account {0} {1}.", first, last); @@ -1915,7 +1929,7 @@ namespace OpenSim.Region.Framework.Scenes /// /// Create a terrain texture for this scene /// - public void CreateTerrainTexture(bool temporary) + public void CreateTerrainTexture() { //create a texture asset of the terrain IMapImageGenerator terrain = RequestModuleInterface(); @@ -1933,7 +1947,9 @@ namespace OpenSim.Region.Framework.Scenes IWorldMapModule mapModule = RequestModuleInterface(); if (mapModule != null) - mapModule.LazySaveGeneratedMaptile(data, temporary); + mapModule.RegenerateMaptile(data); + else + m_log.DebugFormat("[SCENE]: MapModule is null, can't save maptile"); } } @@ -2212,7 +2228,7 @@ namespace OpenSim.Region.Framework.Scenes } /// - /// Delete every object from the scene + /// Delete every object from the scene. This does not include attachments worn by avatars. /// public void DeleteAllSceneObjects() { @@ -2223,7 +2239,11 @@ namespace OpenSim.Region.Framework.Scenes foreach (EntityBase e in entities) { if (e is SceneObjectGroup) - DeleteSceneObject((SceneObjectGroup)e, false); + { + SceneObjectGroup sog = (SceneObjectGroup)e; + if (!sog.IsAttachment) + DeleteSceneObject((SceneObjectGroup)e, false); + } } } } @@ -2729,34 +2749,23 @@ namespace OpenSim.Region.Framework.Scenes AgentCircuitData aCircuit = m_authenticateHandler.GetAgentCircuitData(client.CircuitCode); // Do the verification here - System.Net.EndPoint ep = client.GetClientEP(); + System.Net.IPEndPoint ep = (System.Net.IPEndPoint)client.GetClientEP(); if (aCircuit != null) { - if ((aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaLogin) != 0) + if (!VerifyClient(aCircuit, ep, out vialogin)) { - m_log.DebugFormat("[Scene]: Incoming client {0} {1} in region {2} via Login", aCircuit.firstname, aCircuit.lastname, RegionInfo.RegionName); - vialogin = true; - IUserAgentVerificationModule userVerification = RequestModuleInterface(); - if (userVerification != null && ep != null) + // uh-oh, this is fishy + m_log.WarnFormat("[Scene]: Agent {0} with session {1} connecting with unidentified end point {2}. Refusing service.", + client.AgentId, client.SessionId, ep.ToString()); + try { - if (!userVerification.VerifyClient(aCircuit, ep.ToString())) - { - // uh-oh, this is fishy - m_log.WarnFormat("[Scene]: Agent {0} with session {1} connecting with unidentified end point {2}. Refusing service.", - client.AgentId, client.SessionId, ep.ToString()); - try - { - client.Close(); - } - catch (Exception e) - { - m_log.DebugFormat("[Scene]: Exception while closing aborted client: {0}", e.StackTrace); - } - return; - } - else - m_log.DebugFormat("[Scene]: User Client Verification for {0} {1} returned true", aCircuit.firstname, aCircuit.lastname); + client.Close(); } + catch (Exception e) + { + m_log.DebugFormat("[Scene]: Exception while closing aborted client: {0}", e.StackTrace); + } + return; } } @@ -2782,7 +2791,65 @@ namespace OpenSim.Region.Framework.Scenes EventManager.TriggerOnClientLogin(client); } - + private bool VerifyClient(AgentCircuitData aCircuit, System.Net.IPEndPoint ep, out bool vialogin) + { + vialogin = false; + + // Do the verification here + if ((aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaLogin) != 0) + { + m_log.DebugFormat("[Scene]: Incoming client {0} {1} in region {2} via Login", aCircuit.firstname, aCircuit.lastname, RegionInfo.RegionName); + vialogin = true; + IUserAgentVerificationModule userVerification = RequestModuleInterface(); + if (userVerification != null && ep != null) + { + if (!userVerification.VerifyClient(aCircuit, ep.Address.ToString())) + { + // uh-oh, this is fishy + m_log.DebugFormat("[Scene]: User Client Verification for {0} {1} in {2} returned false", aCircuit.firstname, aCircuit.lastname, RegionInfo.RegionName); + return false; + } + else + m_log.DebugFormat("[Scene]: User Client Verification for {0} {1} in {2} returned true", aCircuit.firstname, aCircuit.lastname, RegionInfo.RegionName); + } + } + + return true; + } + + // Called by Caps, on the first HTTP contact from the client + public override bool CheckClient(UUID agentID, System.Net.IPEndPoint ep) + { + AgentCircuitData aCircuit = m_authenticateHandler.GetAgentCircuitData(agentID); + if (aCircuit != null) + { + bool vialogin = false; + if (!VerifyClient(aCircuit, ep, out vialogin)) + { + // if it doesn't pass, we remove the agentcircuitdata altogether + // and the scene presence and the client, if they exist + try + { + ScenePresence sp = GetScenePresence(agentID); + if (sp != null) + sp.ControllingClient.Close(); + + // BANG! SLASH! + m_authenticateHandler.RemoveCircuit(agentID); + + return false; + } + catch (Exception e) + { + m_log.DebugFormat("[Scene]: Exception while closing aborted client: {0}", e.StackTrace); + } + } + else + return true; + } + + return false; + } /// /// Register for events from the client @@ -2838,8 +2905,8 @@ namespace OpenSim.Region.Framework.Scenes client.OnObjectName += m_sceneGraph.PrimName; client.OnObjectClickAction += m_sceneGraph.PrimClickAction; client.OnObjectMaterial += m_sceneGraph.PrimMaterial; - client.OnLinkObjects += m_sceneGraph.LinkObjects; - client.OnDelinkObjects += m_sceneGraph.DelinkObjects; + client.OnLinkObjects += LinkObjects; + client.OnDelinkObjects += DelinkObjects; client.OnObjectDuplicate += m_sceneGraph.DuplicateObject; client.OnObjectDuplicateOnRay += doObjectDuplicateOnRay; client.OnUpdatePrimFlags += m_sceneGraph.UpdatePrimFlags; @@ -2995,8 +3062,8 @@ namespace OpenSim.Region.Framework.Scenes client.OnObjectName -= m_sceneGraph.PrimName; client.OnObjectClickAction -= m_sceneGraph.PrimClickAction; client.OnObjectMaterial -= m_sceneGraph.PrimMaterial; - client.OnLinkObjects -= m_sceneGraph.LinkObjects; - client.OnDelinkObjects -= m_sceneGraph.DelinkObjects; + client.OnLinkObjects -= LinkObjects; + client.OnDelinkObjects -= DelinkObjects; client.OnObjectDuplicate -= m_sceneGraph.DuplicateObject; client.OnObjectDuplicateOnRay -= doObjectDuplicateOnRay; client.OnUpdatePrimFlags -= m_sceneGraph.UpdatePrimFlags; @@ -3208,7 +3275,7 @@ namespace OpenSim.Region.Framework.Scenes /// public virtual void SetHomeRezPoint(IClientAPI remoteClient, ulong regionHandle, Vector3 position, Vector3 lookAt, uint flags) { - if (PresenceService.SetHomeLocation(remoteClient.AgentId.ToString(), RegionInfo.RegionID, position, lookAt)) + if (GridUserService != null && GridUserService.SetHome(remoteClient.AgentId.ToString(), RegionInfo.RegionID, position, lookAt)) // FUBAR ALERT: this needs to be "Home position set." so the viewer saves a home-screenshot. m_dialogModule.SendAlertToUser(remoteClient, "Home position set."); else @@ -3421,7 +3488,6 @@ namespace OpenSim.Region.Framework.Scenes /// public void RegisterCommsEvents() { - m_sceneGridService.OnExpectUser += HandleNewUserConnection; m_sceneGridService.OnAvatarCrossingIntoRegion += AgentCrossing; m_sceneGridService.OnCloseAgentConnection += IncomingCloseAgent; //m_eventManager.OnRegionUp += OtherRegionUp; @@ -3442,7 +3508,6 @@ namespace OpenSim.Region.Framework.Scenes //m_sceneGridService.OnRemoveKnownRegionFromAvatar -= HandleRemoveKnownRegionsFromAvatar; //m_sceneGridService.OnChildAgentUpdate -= IncomingChildAgentDataUpdate; //m_eventManager.OnRegionUp -= OtherRegionUp; - m_sceneGridService.OnExpectUser -= HandleNewUserConnection; m_sceneGridService.OnAvatarCrossingIntoRegion -= AgentCrossing; m_sceneGridService.OnCloseAgentConnection -= IncomingCloseAgent; m_sceneGridService.OnGetLandData -= GetLandData; @@ -3454,22 +3519,6 @@ namespace OpenSim.Region.Framework.Scenes m_log.WarnFormat("[SCENE]: Deregister from grid failed for region {0}", m_regInfo.RegionName); } - /// - /// A handler for the SceneCommunicationService event, to match that events return type of void. - /// Use NewUserConnection() directly if possible so the return type can refuse connections. - /// At the moment nothing actually seems to use this event, - /// as everything is switching to calling the NewUserConnection method directly. - /// - /// Now obsoleting this because it doesn't handle teleportFlags propertly - /// - /// - /// - [Obsolete("Please call NewUserConnection directly.")] - public void HandleNewUserConnection(AgentCircuitData agent) - { - string reason; - NewUserConnection(agent, 0, out reason); - } /// /// Do the work necessary to initiate a new user connection for a particular scene. @@ -3531,13 +3580,22 @@ namespace OpenSim.Region.Framework.Scenes ScenePresence sp = GetScenePresence(agent.AgentID); if (sp != null) { - m_log.DebugFormat( - "[SCENE]: Adjusting known seeds for existing agent {0} in {1}", - agent.AgentID, RegionInfo.RegionName); + if (sp.IsChildAgent) + { + m_log.DebugFormat( + "[SCENE]: Adjusting known seeds for existing agent {0} in {1}", + agent.AgentID, RegionInfo.RegionName); - sp.AdjustKnownSeeds(); + sp.AdjustKnownSeeds(); - return true; + return true; + } + else + { + // We have a zombie from a crashed session. Kill it. + m_log.DebugFormat("[SCENE]: Zombie scene presence detected for {0} in {1}", agent.AgentID, RegionInfo.RegionName); + sp.ControllingClient.Close(); + } } CapsModule.AddCapsHandler(agent.AgentID); @@ -3669,7 +3727,7 @@ namespace OpenSim.Region.Framework.Scenes OpenSim.Services.Interfaces.PresenceInfo pinfo = presence.GetAgent(agent.SessionID); - if (pinfo == null || (pinfo != null && pinfo.Online == false)) + if (pinfo == null) { reason = String.Format("Failed to verify user {0} {1}, access denied to region {2}.", agent.firstname, agent.lastname, RegionInfo.RegionName); return false; @@ -4658,6 +4716,7 @@ namespace OpenSim.Region.Framework.Scenes foreach (SceneObjectPart child in partList) { child.Inventory.ChangeInventoryOwner(remoteClient.AgentId); + child.TriggerScriptChangedEvent(Changed.OWNER); child.ApplyNextOwnerPermissions(); } } @@ -4667,6 +4726,8 @@ namespace OpenSim.Region.Framework.Scenes group.HasGroupChanged = true; part.GetProperties(remoteClient); + part.TriggerScriptChangedEvent(Changed.OWNER); + group.ResumeScripts(); part.ScheduleFullUpdate(); break; @@ -5208,5 +5269,105 @@ namespace OpenSim.Region.Framework.Scenes { return new Vector3(x, y, GetGroundHeight(x, y)); } + + public List GetEstateRegions(int estateID) + { + if (m_storageManager.EstateDataStore == null) + return new List(); + + return m_storageManager.EstateDataStore.GetRegions(estateID); + } + + public void ReloadEstateData() + { + m_regInfo.EstateSettings = m_storageManager.EstateDataStore.LoadEstateSettings(m_regInfo.RegionID, false); + + TriggerEstateSunUpdate(); + } + + public void TriggerEstateSunUpdate() + { + float sun; + if (RegionInfo.RegionSettings.UseEstateSun) + { + sun = (float)RegionInfo.EstateSettings.SunPosition; + if (RegionInfo.EstateSettings.UseGlobalTime) + { + sun = EventManager.GetCurrentTimeAsSunLindenHour() - 6.0f; + } + + // + EventManager.TriggerEstateToolsSunUpdate( + RegionInfo.RegionHandle, + RegionInfo.EstateSettings.FixedSun, + RegionInfo.RegionSettings.UseEstateSun, + sun); + } + else + { + // Use the Sun Position from the Region Settings + sun = (float)RegionInfo.RegionSettings.SunPosition - 6.0f; + + EventManager.TriggerEstateToolsSunUpdate( + RegionInfo.RegionHandle, + RegionInfo.RegionSettings.FixedSun, + RegionInfo.RegionSettings.UseEstateSun, + sun); + } + } + + private void HandleReloadEstate(string module, string[] cmd) + { + if (MainConsole.Instance.ConsoleScene == null || + (MainConsole.Instance.ConsoleScene is Scene && + (Scene)MainConsole.Instance.ConsoleScene == this)) + { + ReloadEstateData(); + } + } + + public Vector3[] GetCombinedBoundingBox(List objects, out float minX, out float maxX, out float minY, out float maxY, out float minZ, out float maxZ) + { + minX = 256; + maxX = -256; + minY = 256; + maxY = -256; + minZ = 8192; + maxZ = -256; + + List offsets = new List(); + + foreach (SceneObjectGroup g in objects) + { + float ominX, ominY, ominZ, omaxX, omaxY, omaxZ; + + g.GetAxisAlignedBoundingBoxRaw(out ominX, out omaxX, out ominY, out omaxY, out ominZ, out omaxZ); + + if (minX > ominX) + minX = ominX; + if (minY > ominY) + minY = ominY; + if (minZ > ominZ) + minZ = ominZ; + if (maxX < omaxX) + maxX = omaxX; + if (maxY < omaxY) + maxY = omaxY; + if (maxZ < omaxZ) + maxZ = omaxZ; + } + + foreach (SceneObjectGroup g in objects) + { + Vector3 vec = g.AbsolutePosition; + vec.X -= minX; + vec.Y -= minY; + vec.Z -= minZ; + + offsets.Add(vec); + } + + return offsets.ToArray(); + } } } diff --git a/OpenSim/Region/Framework/Scenes/SceneBase.cs b/OpenSim/Region/Framework/Scenes/SceneBase.cs index 3218dadc24..ee17fbf8ed 100644 --- a/OpenSim/Region/Framework/Scenes/SceneBase.cs +++ b/OpenSim/Region/Framework/Scenes/SceneBase.cs @@ -376,6 +376,8 @@ namespace OpenSim.Region.Framework.Scenes /// public void RegisterModuleInterface(M mod) { + m_log.DebugFormat("[SCENE BASE]: Registering interface {0}", typeof(M)); + List l = null; if (!ModuleInterfaces.TryGetValue(typeof(M), out l)) { @@ -498,7 +500,30 @@ namespace OpenSim.Region.Framework.Scenes } } + /// + /// Call this from a region module to add a command to the OpenSim console. + /// + /// + /// + /// + /// + /// public void AddCommand(object mod, string command, string shorthelp, string longhelp, CommandDelegate callback) + { + AddCommand(mod, command, shorthelp, longhelp, string.Empty, callback); + } + + /// + /// Call this from a region module to add a command to the OpenSim console. + /// + /// + /// + /// + /// + /// + /// + public void AddCommand( + object mod, string command, string shorthelp, string longhelp, string descriptivehelp, CommandDelegate callback) { if (MainConsole.Instance == null) return; @@ -523,7 +548,8 @@ namespace OpenSim.Region.Framework.Scenes else throw new Exception("AddCommand module parameter must be IRegionModule or IRegionModuleBase"); } - MainConsole.Instance.Commands.AddCommand(modulename, shared, command, shorthelp, longhelp, callback); + MainConsole.Instance.Commands.AddCommand( + modulename, shared, command, shorthelp, longhelp, descriptivehelp, callback); } public virtual ISceneObject DeserializeObject(string representation) @@ -536,5 +562,6 @@ namespace OpenSim.Region.Framework.Scenes get { return false; } } + public abstract bool CheckClient(UUID agentID, System.Net.IPEndPoint ep); } } diff --git a/OpenSim/Region/Framework/Scenes/SceneGraph.cs b/OpenSim/Region/Framework/Scenes/SceneGraph.cs index 1e360ad957..0abcbca89e 100644 --- a/OpenSim/Region/Framework/Scenes/SceneGraph.cs +++ b/OpenSim/Region/Framework/Scenes/SceneGraph.cs @@ -70,7 +70,7 @@ namespace OpenSim.Region.Framework.Scenes protected object m_presenceLock = new object(); protected Dictionary m_scenePresenceMap = new Dictionary(); - protected ScenePresence[] m_scenePresenceArray = new ScenePresence[0]; + protected List m_scenePresenceArray = new List(); // SceneObjects is not currently populated or used. //public Dictionary SceneObjects; @@ -136,9 +136,9 @@ namespace OpenSim.Region.Framework.Scenes lock (m_presenceLock) { Dictionary newmap = new Dictionary(); - ScenePresence[] newarray = new ScenePresence[0]; + List newlist = new List(); m_scenePresenceMap = newmap; - m_scenePresenceArray = newarray; + m_scenePresenceArray = newlist; } lock (m_dictionary_lock) @@ -278,61 +278,64 @@ namespace OpenSim.Region.Framework.Scenes if (sceneObject == null || sceneObject.RootPart == null || sceneObject.RootPart.UUID == UUID.Zero) return false; - bool alreadyExisted = false; - - if (m_parentScene.m_clampPrimSize) - { - foreach (SceneObjectPart part in sceneObject.Children.Values) - { - Vector3 scale = part.Shape.Scale; - - if (scale.X > m_parentScene.m_maxNonphys) - scale.X = m_parentScene.m_maxNonphys; - if (scale.Y > m_parentScene.m_maxNonphys) - scale.Y = m_parentScene.m_maxNonphys; - if (scale.Z > m_parentScene.m_maxNonphys) - scale.Z = m_parentScene.m_maxNonphys; - - part.Shape.Scale = scale; - } - } - - sceneObject.AttachToScene(m_parentScene); - - if (sendClientUpdates) - sceneObject.ScheduleGroupForFullUpdate(); - lock (sceneObject) - { - if (!Entities.ContainsKey(sceneObject.UUID)) + { + if (Entities.ContainsKey(sceneObject.UUID)) { - Entities.Add(sceneObject); - m_numPrim += sceneObject.Children.Count; - - if (attachToBackup) - sceneObject.AttachToBackup(); - - if (OnObjectCreate != null) - OnObjectCreate(sceneObject); - - lock (m_dictionary_lock) +// m_log.WarnFormat( +// "[SCENE GRAPH]: Scene object {0} {1} was already in region {2} on add request", +// sceneObject.Name, sceneObject.UUID, m_parentScene.RegionInfo.RegionName); + return false; + } + +// m_log.DebugFormat( +// "[SCENE GRAPH]: Adding object {0} {1} to region {2}", +// sceneObject.Name, sceneObject.UUID, m_parentScene.RegionInfo.RegionName); + + if (m_parentScene.m_clampPrimSize) + { + foreach (SceneObjectPart part in sceneObject.Children.Values) { - SceneObjectGroupsByFullID[sceneObject.UUID] = sceneObject; - SceneObjectGroupsByLocalID[sceneObject.LocalId] = sceneObject; - foreach (SceneObjectPart part in sceneObject.Children.Values) - { - SceneObjectGroupsByFullID[part.UUID] = sceneObject; - SceneObjectGroupsByLocalID[part.LocalId] = sceneObject; - } + Vector3 scale = part.Shape.Scale; + + if (scale.X > m_parentScene.m_maxNonphys) + scale.X = m_parentScene.m_maxNonphys; + if (scale.Y > m_parentScene.m_maxNonphys) + scale.Y = m_parentScene.m_maxNonphys; + if (scale.Z > m_parentScene.m_maxNonphys) + scale.Z = m_parentScene.m_maxNonphys; + + part.Shape.Scale = scale; } } - else + + sceneObject.AttachToScene(m_parentScene); + + if (sendClientUpdates) + sceneObject.ScheduleGroupForFullUpdate(); + + Entities.Add(sceneObject); + m_numPrim += sceneObject.Children.Count; + + if (attachToBackup) + sceneObject.AttachToBackup(); + + if (OnObjectCreate != null) + OnObjectCreate(sceneObject); + + lock (m_dictionary_lock) { - alreadyExisted = true; + SceneObjectGroupsByFullID[sceneObject.UUID] = sceneObject; + SceneObjectGroupsByLocalID[sceneObject.LocalId] = sceneObject; + foreach (SceneObjectPart part in sceneObject.Children.Values) + { + SceneObjectGroupsByFullID[part.UUID] = sceneObject; + SceneObjectGroupsByLocalID[part.LocalId] = sceneObject; + } } } - return alreadyExisted; + return true; } /// @@ -523,37 +526,27 @@ namespace OpenSim.Region.Framework.Scenes lock (m_presenceLock) { - // We are going to swap the map and array references with modified copies - Dictionary newmap; - ScenePresence[] newarray; - if (m_scenePresenceMap.ContainsKey(presence.UUID)) + Dictionary newmap = new Dictionary(m_scenePresenceMap); + List newlist = new List(m_scenePresenceArray); + + if (!newmap.ContainsKey(presence.UUID)) { - // copy the map and update the presence reference - newmap = new Dictionary(m_scenePresenceMap); - m_scenePresenceMap[presence.UUID] = presence; - // copy the array and update the presence reference - newarray = new ScenePresence[m_scenePresenceArray.Length]; - for(int i = 0; i < m_scenePresenceArray.Length; ++i) - { - if(m_scenePresenceArray[i].UUID == presence.UUID) - newarray[i] = presence; - else - newarray[i] = m_scenePresenceArray[i]; - } + newmap.Add(presence.UUID, presence); + newlist.Add(presence); } else { - // copy the map and add the new presence reference - newmap = new Dictionary(m_scenePresenceMap); + // Remember the old presene reference from the dictionary + ScenePresence oldref = newmap[presence.UUID]; + // Replace the presence reference in the dictionary with the new value newmap[presence.UUID] = presence; - // Copy the array and add the new presence reference - int oldLength = m_scenePresenceArray.Length; - newarray = new ScenePresence[oldLength+1]; - Array.Copy(m_scenePresenceArray, newarray, oldLength); - newarray[oldLength] = presence; + // Find the index in the list where the old ref was stored and update the reference + newlist[newlist.IndexOf(oldref)] = presence; } + + // Swap out the dictionary and list with new references m_scenePresenceMap = newmap; - m_scenePresenceArray = newarray; + m_scenePresenceArray = newlist; } } @@ -571,28 +564,19 @@ namespace OpenSim.Region.Framework.Scenes lock (m_presenceLock) { - // Copy the map Dictionary newmap = new Dictionary(m_scenePresenceMap); + List newlist = new List(m_scenePresenceArray); + + // Remember the old presence reference from the dictionary + ScenePresence oldref = newmap[agentID]; // Remove the presence reference from the dictionary if (newmap.Remove(agentID)) { - // Copy all of the elements from the previous array - // into the new array except the removed element - int oldLength = m_scenePresenceArray.Length; - ScenePresence[] newarray = new ScenePresence[oldLength - 1]; - int j = 0; - for (int i = 0; i < oldLength; ++i) - { - ScenePresence presence = m_scenePresenceArray[i]; - if (presence.UUID != agentID) - { - newarray[j] = presence; - ++j; - } - } + // Find the index in the list where the old ref was stored and remove the reference + newlist.RemoveAt(newlist.IndexOf(oldref)); // Swap out the dictionary and list with new references m_scenePresenceMap = newmap; - m_scenePresenceArray = newarray; + m_scenePresenceArray = newlist; } else { @@ -717,7 +701,7 @@ namespace OpenSim.Region.Framework.Scenes /// pass a delegate to ForEachScenePresence. /// /// - private ScenePresence[] GetScenePresences() + private List GetScenePresences() { return m_scenePresenceArray; } @@ -743,11 +727,11 @@ namespace OpenSim.Region.Framework.Scenes /// null if the presence was not found protected internal ScenePresence GetScenePresence(string firstName, string lastName) { - ScenePresence[] presences = GetScenePresences(); - for(int i = 0; i < presences.Length; ++i) + List presences = GetScenePresences(); + foreach (ScenePresence presence in presences) { - if (presences[i].Firstname == firstName && presences[i].Lastname == lastName) - return presences[i]; + if (presence.Firstname == firstName && presence.Lastname == lastName) + return presence; } return null; } @@ -759,12 +743,10 @@ namespace OpenSim.Region.Framework.Scenes /// null if the presence was not found protected internal ScenePresence GetScenePresence(uint localID) { - ScenePresence[] presences = GetScenePresences(); - for (int i = 0; i < presences.Length; ++i) - { - if (presences[i].LocalId == localID) - return presences[i]; - } + List presences = GetScenePresences(); + foreach (ScenePresence presence in presences) + if (presence.LocalId == localID) + return presence; return null; } @@ -778,12 +760,11 @@ namespace OpenSim.Region.Framework.Scenes protected internal bool TryGetAvatarByName(string name, out ScenePresence avatar) { avatar = null; - ScenePresence[] presences = GetScenePresences(); - for(int i = 0; i < presences.Length; ++i ) + foreach (ScenePresence presence in GetScenePresences()) { - if (String.Compare(name, presences[i].ControllingClient.Name, true) == 0) + if (String.Compare(name, presence.ControllingClient.Name, true) == 0) { - avatar = presences[i]; + avatar = presence; break; } } @@ -1050,13 +1031,12 @@ namespace OpenSim.Region.Framework.Scenes Parallel.ForEach(GetScenePresences(), protectedAction); */ // For now, perform actions serially - ScenePresence[] presences = GetScenePresences(); - for(int i = 0; i < presences.Length; ++i) + List presences = GetScenePresences(); + foreach (ScenePresence sp in presences) { - ScenePresence presence = presences[i]; try { - action(presence); + action(sp); } catch (Exception e) { @@ -1478,20 +1458,21 @@ namespace OpenSim.Region.Framework.Scenes /// /// /// - protected internal void LinkObjects(IClientAPI client, uint parentPrimId, List childPrimIds) + protected internal void LinkObjects(SceneObjectPart root, List children) { Monitor.Enter(m_updateLock); try { - SceneObjectGroup parentGroup = GetGroupByPrim(parentPrimId); + SceneObjectGroup parentGroup = root.ParentGroup; List childGroups = new List(); if (parentGroup != null) { // We do this in reverse to get the link order of the prims correct - for (int i = childPrimIds.Count - 1; i >= 0; i--) + for (int i = children.Count - 1; i >= 0; i--) { - SceneObjectGroup child = GetGroupByPrim(childPrimIds[i]); + SceneObjectGroup child = children[i].ParentGroup; + if (child != null) { // Make sure no child prim is set for sale @@ -1519,22 +1500,11 @@ namespace OpenSim.Region.Framework.Scenes // We need to explicitly resend the newly link prim's object properties since no other actions // occur on link to invoke this elsewhere (such as object selection) - parentGroup.RootPart.AddFlag(PrimFlags.CreateSelected); + parentGroup.RootPart.CreateSelected = true; parentGroup.TriggerScriptChangedEvent(Changed.LINK); parentGroup.HasGroupChanged = true; parentGroup.ScheduleGroupForFullUpdate(); -// if (client != null) -// { -// parentGroup.GetProperties(client); -// } -// else -// { -// foreach (ScenePresence p in GetScenePresences()) -// { -// parentGroup.GetProperties(p.ControllingClient); -// } -// } } finally { @@ -1546,12 +1516,7 @@ namespace OpenSim.Region.Framework.Scenes /// Delink a linkset /// /// - protected internal void DelinkObjects(List primIds) - { - DelinkObjects(primIds, true); - } - - protected internal void DelinkObjects(List primIds, bool sendEvents) + protected internal void DelinkObjects(List prims) { Monitor.Enter(m_updateLock); try @@ -1561,9 +1526,8 @@ namespace OpenSim.Region.Framework.Scenes List affectedGroups = new List(); // Look them all up in one go, since that is comparatively expensive // - foreach (uint primID in primIds) + foreach (SceneObjectPart part in prims) { - SceneObjectPart part = m_parentScene.GetSceneObjectPart(primID); if (part != null) { if (part.ParentGroup.Children.Count != 1) // Skip single @@ -1578,17 +1542,13 @@ namespace OpenSim.Region.Framework.Scenes affectedGroups.Add(group); } } - else - { - m_log.ErrorFormat("Viewer requested unlink of nonexistent part {0}", primID); - } } foreach (SceneObjectPart child in childParts) { // Unlink all child parts from their groups // - child.ParentGroup.DelinkFromGroup(child, sendEvents); + child.ParentGroup.DelinkFromGroup(child, true); } foreach (SceneObjectPart root in rootParts) @@ -1643,12 +1603,9 @@ namespace OpenSim.Region.Framework.Scenes List linkIDs = new List(); foreach (SceneObjectPart newChild in newSet) - { newChild.UpdateFlag = 0; - linkIDs.Add(newChild.LocalId); - } - LinkObjects(null, newRoot.LocalId, linkIDs); + LinkObjects(newRoot, newSet); if (!affectedGroups.Contains(newRoot.ParentGroup)) affectedGroups.Add(newRoot.ParentGroup); } diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs b/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs index 2b8a1daea3..144fdf4ce6 100644 --- a/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs +++ b/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs @@ -652,10 +652,16 @@ namespace OpenSim.Region.Framework.Scenes /// offsetHeight is the offset in the Z axis from the centre of the bounding box to the centre of the root prim /// /// - public Vector3 GetAxisAlignedBoundingBox(out float offsetHeight) + public void GetAxisAlignedBoundingBoxRaw(out float minX, out float maxX, out float minY, out float maxY, out float minZ, out float maxZ) { - float maxX = -256f, maxY = -256f, maxZ = -256f, minX = 256f, minY = 256f, minZ = 256f; - lock (m_parts) + maxX = -256f; + maxY = -256f; + maxZ = -256f; + minX = 256f; + minY = 256f; + minZ = 8192f; + + lock(m_parts); { foreach (SceneObjectPart part in m_parts.Values) { @@ -888,7 +894,18 @@ namespace OpenSim.Region.Framework.Scenes minZ = backBottomLeft.Z; } } + } + public Vector3 GetAxisAlignedBoundingBox(out float offsetHeight) + { + float minX; + float maxX; + float minY; + float maxY; + float minZ; + float maxZ; + + GetAxisAlignedBoundingBoxRaw(out minX, out maxX, out minY, out maxY, out minZ, out maxZ); Vector3 boundingBox = new Vector3(maxX - minX, maxY - minY, maxZ - minZ); offsetHeight = 0; @@ -2260,7 +2277,7 @@ namespace OpenSim.Region.Framework.Scenes linkPart.LinkNum = 2; linkPart.SetParent(this); - linkPart.AddFlag(PrimFlags.CreateSelected); + linkPart.CreateSelected = true; //if (linkPart.PhysActor != null) //{ @@ -3608,106 +3625,7 @@ namespace OpenSim.Region.Framework.Scenes SetFromItemID(uuid); } - #endregion - public double GetUpdatePriority(IClientAPI client) - { - switch (Scene.UpdatePrioritizationScheme) - { - case Scene.UpdatePrioritizationSchemes.Time: - return GetPriorityByTime(); - case Scene.UpdatePrioritizationSchemes.Distance: - return GetPriorityByDistance(client); - case Scene.UpdatePrioritizationSchemes.SimpleAngularDistance: - return GetPriorityBySimpleAngularDistance(client); - case Scenes.Scene.UpdatePrioritizationSchemes.FrontBack: - return GetPriorityByFrontBack(client); - default: - throw new InvalidOperationException("UpdatePrioritizationScheme not defined"); - } - } - - private double GetPriorityByTime() - { - return DateTime.Now.ToOADate(); - } - - private double GetPriorityByDistance(IClientAPI client) - { - ScenePresence presence = Scene.GetScenePresence(client.AgentId); - if (presence != null) - { - return GetPriorityByDistance((presence.IsChildAgent) ? - presence.AbsolutePosition : presence.CameraPosition); - } - return double.NaN; - } - - private double GetPriorityBySimpleAngularDistance(IClientAPI client) - { - ScenePresence presence = Scene.GetScenePresence(client.AgentId); - if (presence != null) - { - return GetPriorityBySimpleAngularDistance((presence.IsChildAgent) ? - presence.AbsolutePosition : presence.CameraPosition); - } - return double.NaN; - } - - private double GetPriorityByFrontBack(IClientAPI client) - { - ScenePresence presence = Scene.GetScenePresence(client.AgentId); - if (presence != null) - { - return GetPriorityByFrontBack(presence.CameraPosition, presence.CameraAtAxis); - } - return double.NaN; - } - - public double GetPriorityByDistance(Vector3 position) - { - return Vector3.Distance(AbsolutePosition, position); - } - - public double GetPriorityBySimpleAngularDistance(Vector3 position) - { - double distance = Vector3.Distance(position, AbsolutePosition); - if (distance >= double.Epsilon) - { - float height; - Vector3 box = GetAxisAlignedBoundingBox(out height); - - double angle = box.X / distance; - double max = angle; - - angle = box.Y / distance; - if (max < angle) - max = angle; - - angle = box.Z / distance; - if (max < angle) - max = angle; - - return -max; - } - else - return double.MinValue; - } - - public double GetPriorityByFrontBack(Vector3 camPosition, Vector3 camAtAxis) - { - // Distance - double priority = Vector3.Distance(camPosition, AbsolutePosition); - - // Scale - //priority -= GroupScale().Length(); - - // Plane equation - float d = -Vector3.Dot(camPosition, camAtAxis); - float p = Vector3.Dot(camAtAxis, AbsolutePosition) + d; - if (p < 0.0f) priority *= 2.0f; - - return priority; - } + #endregion } } diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs b/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs index 17b6f56826..2d5b38f13b 100644 --- a/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs +++ b/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs @@ -104,7 +104,7 @@ namespace OpenSim.Region.Framework.Scenes #endregion Enumerations - public class SceneObjectPart : IScriptHost + public class SceneObjectPart : IScriptHost, ISceneEntity { /// /// Denote all sides of the prim @@ -387,7 +387,7 @@ namespace OpenSim.Region.Framework.Scenes // the prim into an agent inventory (Linden client reports that the "Object not found for drop" in its log _flags = 0; - _flags |= PrimFlags.CreateSelected; + CreateSelected = true; TrimPermissions(); //m_undo = new UndoStack(ParentGroup.GetSceneMaxUndo()); @@ -417,6 +417,7 @@ namespace OpenSim.Region.Framework.Scenes private PrimFlags _flags = 0; private DateTime m_expires; private DateTime m_rezzed; + private bool m_createSelected = false; public UUID CreatorID { @@ -712,6 +713,24 @@ namespace OpenSim.Region.Framework.Scenes } } + public Vector3 RelativePosition + { + get + { + if (IsRoot) + { + if (IsAttachment) + return AttachedPos; + else + return AbsolutePosition; + } + else + { + return OffsetPosition; + } + } + } + public Quaternion RotationOffset { get @@ -949,6 +968,13 @@ namespace OpenSim.Region.Framework.Scenes set { m_updateFlag = value; } } + [XmlIgnore] + public bool CreateSelected + { + get { return m_createSelected; } + set { m_createSelected = value; } + } + #endregion //--------------- @@ -973,7 +999,6 @@ namespace OpenSim.Region.Framework.Scenes get { return AggregateScriptEvents; } } - public Quaternion SitTargetOrientation { get { return m_sitTargetOrientation; } @@ -1261,13 +1286,16 @@ namespace OpenSim.Region.Framework.Scenes { m_parentGroup.Scene.ForEachScenePresence(delegate(ScenePresence avatar) { - avatar.SceneViewer.QueuePartForUpdate(this); + AddFullUpdateToAvatar(avatar); }); // REGION SYNC if (m_parentGroup.Scene.IsSyncedServer()) m_parentGroup.Scene.RegionSyncServerModule.QueuePartForUpdate(this); } + /// + /// Tell the scene presence that it should send updates for this part to its client + /// public void AddFullUpdateToAvatar(ScenePresence presence) { presence.SceneViewer.QueuePartForUpdate(this); @@ -1288,7 +1316,7 @@ namespace OpenSim.Region.Framework.Scenes { m_parentGroup.Scene.ForEachScenePresence(delegate(ScenePresence avatar) { - avatar.SceneViewer.QueuePartForUpdate(this); + AddTerseUpdateToAvatar(avatar); }); // REGION SYNC if (m_parentGroup.Scene.IsSyncedServer()) @@ -2931,11 +2959,7 @@ namespace OpenSim.Region.Framework.Scenes //if (LocalId != ParentGroup.RootPart.LocalId) //isattachment = ParentGroup.RootPart.IsAttachment; - byte[] color = new byte[] {m_color.R, m_color.G, m_color.B, m_color.A}; - remoteClient.SendPrimitiveToClient(new SendPrimitiveData(m_regionHandle, m_parentGroup.GetTimeDilation(), LocalId, m_shape, - lPos, Velocity, Acceleration, RotationOffset, AngularVelocity, clientFlags, m_uuid, _ownerID, - m_text, color, _parentID, m_particleSystem, m_clickAction, (byte)m_material, m_TextureAnimation, IsAttachment, - AttachmentPoint,FromItemID, Sound, SoundGain, SoundFlags, SoundRadius, ParentGroup.GetUpdatePriority(remoteClient))); + remoteClient.SendPrimUpdate(this, PrimUpdateFlags.FullUpdate); } /// @@ -3472,7 +3496,7 @@ namespace OpenSim.Region.Framework.Scenes /// public void SetText(string text, Vector3 color, double alpha) { - Color = Color.FromArgb(0xff - (int) (alpha*0xff), + Color = Color.FromArgb((int) (alpha*0xff), (int) (color.X*0xff), (int) (color.Y*0xff), (int) (color.Z*0xff)); @@ -4646,11 +4670,7 @@ namespace OpenSim.Region.Framework.Scenes // Causes this thread to dig into the Client Thread Data. // Remember your locking here! - remoteClient.SendPrimTerseUpdate(new SendPrimitiveTerseData(m_regionHandle, - m_parentGroup.GetTimeDilation(), LocalId, lPos, - RotationOffset, Velocity, Acceleration, - AngularVelocity, FromItemID, - OwnerID, (int)AttachmentPoint, null, ParentGroup.GetUpdatePriority(remoteClient))); + remoteClient.SendPrimUpdate(this, PrimUpdateFlags.Position | PrimUpdateFlags.Rotation | PrimUpdateFlags.Velocity | PrimUpdateFlags.Acceleration | PrimUpdateFlags.AngularVelocity); } public void AddScriptLPS(int count) @@ -4700,7 +4720,8 @@ namespace OpenSim.Region.Framework.Scenes public Color4 GetTextColor() { - return new Color4((byte)Color.R, (byte)Color.G, (byte)Color.B, (byte)(0xFF - Color.A)); + Color color = Color; + return new Color4(color.R, color.G, color.B, (byte)(0xFF - color.A)); } } } diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs b/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs index 3b1b567557..8b83b0660c 100644 --- a/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs +++ b/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs @@ -609,43 +609,50 @@ namespace OpenSim.Region.Framework.Scenes /// false if the item did not exist, true if the update occurred successfully public bool UpdateInventoryItem(TaskInventoryItem item) { - lock (m_items) + return UpdateInventoryItem(item, true); + } + + public bool UpdateInventoryItem(TaskInventoryItem item, bool fireScriptEvents) + { + lock(m_items) { if (m_items.ContainsKey(item.ItemID)) { - item.ParentID = m_part.UUID; - item.ParentPartID = m_part.UUID; - item.Flags = m_items[item.ItemID].Flags; - - // If group permissions have been set on, check that the groupID is up to date in case it has - // changed since permissions were last set. - if (item.GroupPermissions != (uint)PermissionMask.None) - item.GroupID = m_part.GroupID; - - if (item.AssetID == UUID.Zero) + if (m_items.ContainsKey(item.ItemID)) { - item.AssetID = m_items[item.ItemID].AssetID; + item.ParentID = m_part.UUID; + item.ParentPartID = m_part.UUID; + item.Flags = m_items[item.ItemID].Flags; + + // If group permissions have been set on, check that the groupID is up to date in case it has + // changed since permissions were last set. + if (item.GroupPermissions != (uint)PermissionMask.None) + item.GroupID = m_part.GroupID; + + if (item.AssetID == UUID.Zero) + { + item.AssetID = m_items[item.ItemID].AssetID; + } + m_items[item.ItemID] = item; + m_inventorySerial++; + if (fireScriptEvents) + m_part.TriggerScriptChangedEvent(Changed.INVENTORY); + HasInventoryChanged = true; + m_part.ParentGroup.HasGroupChanged = true; + return true; + } + else + { + m_log.ErrorFormat( + "[PRIM INVENTORY]: " + + "Tried to retrieve item ID {0} from prim {1}, {2} at {3} in {4} but the item does not exist in this inventory", + item.ItemID, m_part.Name, m_part.UUID, + m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName); } - m_items[item.ItemID] = item; - m_inventorySerial++; - m_part.TriggerScriptChangedEvent(Changed.INVENTORY); - HasInventoryChanged = true; - m_part.ParentGroup.HasGroupChanged = true; - - return true; - } - else - { - m_log.ErrorFormat( - "[PRIM INVENTORY]: " + - "Tried to retrieve item ID {0} from prim {1}, {2} at {3} in {4} but the item does not exist in this inventory", - item.ItemID, m_part.Name, m_part.UUID, - m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName); } + return false; } - - return false; } /// @@ -948,10 +955,9 @@ namespace OpenSim.Region.Framework.Scenes item.CurrentPermissions &= item.NextPermissions; item.BasePermissions &= item.NextPermissions; item.EveryonePermissions &= item.NextPermissions; + item.OwnerChanged = true; } } - - m_part.TriggerScriptChangedEvent(Changed.OWNER); } public void ApplyGodPermissions(uint perms) @@ -1035,7 +1041,6 @@ namespace OpenSim.Region.Framework.Scenes if (engines == null) return; - lock (m_items) { foreach (TaskInventoryItem item in m_items.Values) @@ -1045,7 +1050,12 @@ namespace OpenSim.Region.Framework.Scenes foreach (IScriptModule engine in engines) { if (engine != null) + { + if (item.OwnerChanged) + engine.PostScriptEvent(item.ItemID, "changed", new Object[] { (int)Changed.OWNER }); + item.OwnerChanged = false; engine.ResumeScript(item.ItemID); + } } } } diff --git a/OpenSim/Region/Framework/Scenes/ScenePresence.cs b/OpenSim/Region/Framework/Scenes/ScenePresence.cs index d751036603..ec607abc9d 100644 --- a/OpenSim/Region/Framework/Scenes/ScenePresence.cs +++ b/OpenSim/Region/Framework/Scenes/ScenePresence.cs @@ -67,7 +67,7 @@ namespace OpenSim.Region.Framework.Scenes public delegate void SendCourseLocationsMethod(UUID scene, ScenePresence presence); - public class ScenePresence : EntityBase + public class ScenePresence : EntityBase, ISceneEntity { // ~ScenePresence() // { @@ -218,7 +218,6 @@ namespace OpenSim.Region.Framework.Scenes private bool m_followCamAuto; private int m_movementUpdateCount; - private const int NumMovementsBetweenRayCast = 5; private bool CameraConstraintActive; @@ -491,6 +490,12 @@ namespace OpenSim.Region.Framework.Scenes } } + public Vector3 OffsetPosition + { + get { return m_pos; } + set { m_pos = value; } + } + /// /// Current velocity of the avatar. /// @@ -663,6 +668,11 @@ namespace OpenSim.Region.Framework.Scenes set { m_flyDisabled = value; } } + public string Viewer + { + get { return m_scene.AuthenticateHandler.GetAgentCircuitData(ControllingClient.CircuitCode).Viewer; } + } + #endregion #region Constructor(s) @@ -797,15 +807,6 @@ namespace OpenSim.Region.Framework.Scenes #endregion - /// - /// Add the part to the queue of parts for which we need to send an update to the client - /// - /// - public void QueuePartForUpdate(SceneObjectPart part) - { - m_sceneViewer.QueuePartForUpdate(part); - } - public uint GenerateClientFlags(UUID ObjectID) { return m_scene.Permissions.GenerateClientFlags(m_uuid, ObjectID); @@ -1055,8 +1056,9 @@ namespace OpenSim.Region.Framework.Scenes AbsolutePosition = AbsolutePosition + new Vector3(0f, 0f, (1.56f / 6f)); } - ControllingClient.SendAvatarTerseUpdate(new SendAvatarTerseData(m_rootRegionHandle, (ushort)(m_scene.TimeDilation * ushort.MaxValue), LocalId, - AbsolutePosition, Velocity, Vector3.Zero, m_bodyRot, new Vector4(0,0,1,AbsolutePosition.Z - 0.5f), m_uuid, null, GetUpdatePriority(ControllingClient))); + ControllingClient.SendPrimUpdate(this, PrimUpdateFlags.Position); + //ControllingClient.SendAvatarTerseUpdate(new SendAvatarTerseData(m_rootRegionHandle, (ushort)(m_scene.TimeDilation * ushort.MaxValue), LocalId, + // AbsolutePosition, Velocity, Vector3.Zero, m_bodyRot, new Vector4(0,0,1,AbsolutePosition.Z - 0.5f), m_uuid, null, GetUpdatePriority(ControllingClient))); } public void AddNeighbourRegion(ulong regionHandle, string cap) @@ -1357,8 +1359,7 @@ namespace OpenSim.Region.Framework.Scenes // Setting parent ID would fix this, if we knew what value // to use. Or we could add a m_isSitting variable. //Animator.TrySetMovementAnimation("SIT_GROUND_CONSTRAINED"); - SitGround = true; - + SitGround = true; } // In the future, these values might need to go global. @@ -1375,7 +1376,7 @@ namespace OpenSim.Region.Framework.Scenes bool update_movementflag = false; - if (m_allowMovement) + if (m_allowMovement && !SitGround) { if (agentData.UseClientAgentPosition) { @@ -1717,8 +1718,7 @@ namespace OpenSim.Region.Framework.Scenes /// public void StandUp() { - if (SitGround) - SitGround = false; + SitGround = false; if (m_parentID != 0) { @@ -2416,8 +2416,7 @@ namespace OpenSim.Region.Framework.Scenes //m_log.DebugFormat("[SCENEPRESENCE]: TerseUpdate: Pos={0} Rot={1} Vel={2}", m_pos, m_bodyRot, m_velocity); - remoteClient.SendAvatarTerseUpdate(new SendAvatarTerseData(m_rootRegionHandle, (ushort)(m_scene.TimeDilation * ushort.MaxValue), LocalId, - pos, velocity, Vector3.Zero, m_bodyRot, CollisionPlane, m_uuid, null, GetUpdatePriority(remoteClient))); + remoteClient.SendPrimUpdate(this, PrimUpdateFlags.Position | PrimUpdateFlags.Rotation | PrimUpdateFlags.Velocity | PrimUpdateFlags.Acceleration | PrimUpdateFlags.AngularVelocity); m_scene.StatsReporter.AddAgentTime(Util.EnvironmentTickCountSubtract(m_perfMonMS)); m_scene.StatsReporter.AddAgentUpdates(1); @@ -2504,9 +2503,7 @@ namespace OpenSim.Region.Framework.Scenes Vector3 pos = m_pos; pos.Z += m_appearance.HipOffset; - remoteAvatar.m_controllingClient.SendAvatarData(new SendAvatarData(m_regionInfo.RegionHandle, m_firstname, m_lastname, m_grouptitle, m_uuid, - LocalId, pos, m_appearance.Texture.GetBytes(), - m_parentID, m_bodyRot)); + remoteAvatar.m_controllingClient.SendAvatarDataImmediate(this); m_scene.StatsReporter.AddAgentUpdates(1); } @@ -2574,8 +2571,7 @@ namespace OpenSim.Region.Framework.Scenes Vector3 pos = m_pos; pos.Z += m_appearance.HipOffset; - m_controllingClient.SendAvatarData(new SendAvatarData(m_regionInfo.RegionHandle, m_firstname, m_lastname, m_grouptitle, m_uuid, LocalId, - pos, m_appearance.Texture.GetBytes(), m_parentID, m_bodyRot)); + m_controllingClient.SendAvatarDataImmediate(this); SendInitialFullUpdateToAllClients(); SendAppearanceToAllOtherAgents(); @@ -2703,9 +2699,7 @@ namespace OpenSim.Region.Framework.Scenes Vector3 pos = m_pos; pos.Z += m_appearance.HipOffset; - m_controllingClient.SendAvatarData(new SendAvatarData(m_regionInfo.RegionHandle, m_firstname, m_lastname, m_grouptitle, m_uuid, LocalId, - pos, m_appearance.Texture.GetBytes(), m_parentID, m_bodyRot)); - + m_controllingClient.SendAvatarDataImmediate(this); } public void SetWearable(int wearableId, AvatarWearable wearable) @@ -3841,123 +3835,9 @@ namespace OpenSim.Region.Framework.Scenes } } - public double GetUpdatePriority(IClientAPI client) - { - switch (Scene.UpdatePrioritizationScheme) - { - case Scene.UpdatePrioritizationSchemes.Time: - return GetPriorityByTime(); - case Scene.UpdatePrioritizationSchemes.Distance: - return GetPriorityByDistance(client); - case Scene.UpdatePrioritizationSchemes.SimpleAngularDistance: - return GetPriorityByDistance(client); - case Scenes.Scene.UpdatePrioritizationSchemes.FrontBack: - return GetPriorityByFrontBack(client); - default: - throw new InvalidOperationException("UpdatePrioritizationScheme not defined."); - } - } - - private double GetPriorityByTime() - { - return DateTime.Now.ToOADate(); - } - - private double GetPriorityByDistance(IClientAPI client) - { - ScenePresence presence = Scene.GetScenePresence(client.AgentId); - if (presence != null) - { - return GetPriorityByDistance((presence.IsChildAgent) ? - presence.AbsolutePosition : presence.CameraPosition); - } - return double.NaN; - } - - private double GetPriorityByFrontBack(IClientAPI client) - { - ScenePresence presence = Scene.GetScenePresence(client.AgentId); - if (presence != null) - { - return GetPriorityByFrontBack(presence.CameraPosition, presence.CameraAtAxis); - } - return double.NaN; - } - - private double GetPriorityByDistance(Vector3 position) - { - return Vector3.Distance(AbsolutePosition, position); - } - - private double GetPriorityByFrontBack(Vector3 camPosition, Vector3 camAtAxis) - { - // Distance - double priority = Vector3.Distance(camPosition, AbsolutePosition); - - // Plane equation - float d = -Vector3.Dot(camPosition, camAtAxis); - float p = Vector3.Dot(camAtAxis, AbsolutePosition) + d; - if (p < 0.0f) priority *= 2.0f; - - return priority; - } - - private double GetSOGUpdatePriority(SceneObjectGroup sog) - { - switch (Scene.UpdatePrioritizationScheme) - { - case Scene.UpdatePrioritizationSchemes.Time: - throw new InvalidOperationException("UpdatePrioritizationScheme for time not supported for reprioritization"); - case Scene.UpdatePrioritizationSchemes.Distance: - return sog.GetPriorityByDistance((IsChildAgent) ? AbsolutePosition : CameraPosition); - case Scene.UpdatePrioritizationSchemes.SimpleAngularDistance: - return sog.GetPriorityBySimpleAngularDistance((IsChildAgent) ? AbsolutePosition : CameraPosition); - case Scenes.Scene.UpdatePrioritizationSchemes.FrontBack: - return sog.GetPriorityByFrontBack(CameraPosition, CameraAtAxis); - default: - throw new InvalidOperationException("UpdatePrioritizationScheme not defined"); - } - } - - private double UpdatePriority(UpdatePriorityData data) - { - EntityBase entity; - SceneObjectGroup group; - - if (Scene.Entities.TryGetValue(data.localID, out entity)) - { - group = entity as SceneObjectGroup; - if (group != null) - return GetSOGUpdatePriority(group); - - ScenePresence presence = entity as ScenePresence; - if (presence == null) - throw new InvalidOperationException("entity found is neither SceneObjectGroup nor ScenePresence"); - switch (Scene.UpdatePrioritizationScheme) - { - case Scene.UpdatePrioritizationSchemes.Time: - throw new InvalidOperationException("UpdatePrioritization for time not supported for reprioritization"); - case Scene.UpdatePrioritizationSchemes.Distance: - case Scene.UpdatePrioritizationSchemes.SimpleAngularDistance: - return GetPriorityByDistance((IsChildAgent) ? AbsolutePosition : CameraPosition); - case Scenes.Scene.UpdatePrioritizationSchemes.FrontBack: - return GetPriorityByFrontBack(CameraPosition, CameraAtAxis); - default: - throw new InvalidOperationException("UpdatePrioritizationScheme not defined"); - } - } - else - { - group = Scene.GetGroupByPrim(data.localID); - if (group != null) - return GetSOGUpdatePriority(group); - } - return double.NaN; - } - private void ReprioritizeUpdates() { - if (Scene.IsReprioritizationEnabled && Scene.UpdatePrioritizationScheme != Scene.UpdatePrioritizationSchemes.Time) + if (Scene.IsReprioritizationEnabled && Scene.UpdatePrioritizationScheme != UpdatePrioritizationSchemes.Time) { lock (m_reprioritization_timer) { @@ -3971,7 +3851,7 @@ namespace OpenSim.Region.Framework.Scenes private void Reprioritize(object sender, ElapsedEventArgs e) { - m_controllingClient.ReprioritizeUpdates(StateUpdateTypes.All, UpdatePriority); + m_controllingClient.ReprioritizeUpdates(); lock (m_reprioritization_timer) { diff --git a/OpenSim/Region/Framework/Scenes/SceneViewer.cs b/OpenSim/Region/Framework/Scenes/SceneViewer.cs index c6cf4ccf39..f478a4a770 100644 --- a/OpenSim/Region/Framework/Scenes/SceneViewer.cs +++ b/OpenSim/Region/Framework/Scenes/SceneViewer.cs @@ -73,96 +73,105 @@ namespace OpenSim.Region.Framework.Scenes { m_pendingObjects = new Queue(); - foreach (EntityBase e in m_presence.Scene.Entities) + lock(m_pendingObjects) { - if (e is SceneObjectGroup) - m_pendingObjects.Enqueue((SceneObjectGroup)e); + foreach (EntityBase e in m_presence.Scene.Entities) + { + if (e != null && e is SceneObjectGroup) + m_pendingObjects.Enqueue((SceneObjectGroup)e); + } } } } - while (m_pendingObjects != null && m_pendingObjects.Count > 0) + lock(m_pendingObjects) { - SceneObjectGroup g = m_pendingObjects.Dequeue(); - - // This is where we should check for draw distance - // do culling and stuff. Problem with that is that until - // we recheck in movement, that won't work right. - // So it's not implemented now. - // - - // Don't even queue if we have sent this one - // - if (!m_updateTimes.ContainsKey(g.UUID)) - g.ScheduleFullUpdateToAvatar(m_presence); - } - - while (m_partsUpdateQueue.Count > 0) - { - SceneObjectPart part = m_partsUpdateQueue.Dequeue(); - - if (part.ParentGroup == null || part.ParentGroup.IsDeleted) - continue; - - if (m_updateTimes.ContainsKey(part.UUID)) + while (m_pendingObjects != null && m_pendingObjects.Count > 0) { - ScenePartUpdate update = m_updateTimes[part.UUID]; + SceneObjectGroup g = m_pendingObjects.Dequeue(); + // Yes, this can really happen + if (g == null) + continue; - // We deal with the possibility that two updates occur at - // the same unix time at the update point itself. + // This is where we should check for draw distance + // do culling and stuff. Problem with that is that until + // we recheck in movement, that won't work right. + // So it's not implemented now. + // - if ((update.LastFullUpdateTime < part.TimeStampFull) || - part.IsAttachment) + // Don't even queue if we have sent this one + // + if (!m_updateTimes.ContainsKey(g.UUID)) + g.ScheduleFullUpdateToAvatar(m_presence); + } + + while (m_partsUpdateQueue.Count > 0) + { + SceneObjectPart part = m_partsUpdateQueue.Dequeue(); + + if (part.ParentGroup == null || part.ParentGroup.IsDeleted) + continue; + + if (m_updateTimes.ContainsKey(part.UUID)) { -// m_log.DebugFormat( -// "[SCENE PRESENCE]: Fully updating prim {0}, {1} - part timestamp {2}", -// part.Name, part.UUID, part.TimeStampFull); + ScenePartUpdate update = m_updateTimes[part.UUID]; + + // We deal with the possibility that two updates occur at + // the same unix time at the update point itself. + + if ((update.LastFullUpdateTime < part.TimeStampFull) || + part.IsAttachment) + { + // m_log.DebugFormat( + // "[SCENE PRESENCE]: Fully updating prim {0}, {1} - part timestamp {2}", + // part.Name, part.UUID, part.TimeStampFull); + + part.SendFullUpdate(m_presence.ControllingClient, + m_presence.GenerateClientFlags(part.UUID)); + + // We'll update to the part's timestamp rather than + // the current time to avoid the race condition + // whereby the next tick occurs while we are doing + // this update. If this happened, then subsequent + // updates which occurred on the same tick or the + // next tick of the last update would be ignored. + + update.LastFullUpdateTime = part.TimeStampFull; + + } + else if (update.LastTerseUpdateTime <= part.TimeStampTerse) + { + // m_log.DebugFormat( + // "[SCENE PRESENCE]: Tersely updating prim {0}, {1} - part timestamp {2}", + // part.Name, part.UUID, part.TimeStampTerse); + + part.SendTerseUpdateToClient(m_presence.ControllingClient); + + update.LastTerseUpdateTime = part.TimeStampTerse; + } + } + else + { + //never been sent to client before so do full update + ScenePartUpdate update = new ScenePartUpdate(); + update.FullID = part.UUID; + update.LastFullUpdateTime = part.TimeStampFull; + m_updateTimes.Add(part.UUID, update); + + // Attachment handling + // + if (part.ParentGroup.RootPart.Shape.PCode == 9 && part.ParentGroup.RootPart.Shape.State != 0) + { + if (part != part.ParentGroup.RootPart) + continue; + + part.ParentGroup.SendFullUpdateToClient(m_presence.ControllingClient); + continue; + } part.SendFullUpdate(m_presence.ControllingClient, - m_presence.GenerateClientFlags(part.UUID)); - - // We'll update to the part's timestamp rather than - // the current time to avoid the race condition - // whereby the next tick occurs while we are doing - // this update. If this happened, then subsequent - // updates which occurred on the same tick or the - // next tick of the last update would be ignored. - - update.LastFullUpdateTime = part.TimeStampFull; - + m_presence.GenerateClientFlags(part.UUID)); } - else if (update.LastTerseUpdateTime <= part.TimeStampTerse) - { -// m_log.DebugFormat( -// "[SCENE PRESENCE]: Tersely updating prim {0}, {1} - part timestamp {2}", -// part.Name, part.UUID, part.TimeStampTerse); - - part.SendTerseUpdateToClient(m_presence.ControllingClient); - - update.LastTerseUpdateTime = part.TimeStampTerse; - } - } - else - { - //never been sent to client before so do full update - ScenePartUpdate update = new ScenePartUpdate(); - update.FullID = part.UUID; - update.LastFullUpdateTime = part.TimeStampFull; - m_updateTimes.Add(part.UUID, update); - - // Attachment handling - // - if (part.ParentGroup.RootPart.Shape.PCode == 9 && part.ParentGroup.RootPart.Shape.State != 0) - { - if (part != part.ParentGroup.RootPart) - continue; - - part.ParentGroup.SendFullUpdateToClient(m_presence.ControllingClient); - continue; - } - - part.SendFullUpdate(m_presence.ControllingClient, - m_presence.GenerateClientFlags(part.UUID)); } } } diff --git a/OpenSim/Region/Framework/Scenes/Tests/SceneBaseTests.cs b/OpenSim/Region/Framework/Scenes/Tests/SceneBaseTests.cs index dd9f8f6654..42587c1116 100644 --- a/OpenSim/Region/Framework/Scenes/Tests/SceneBaseTests.cs +++ b/OpenSim/Region/Framework/Scenes/Tests/SceneBaseTests.cs @@ -70,6 +70,11 @@ namespace OpenSim.Region.Framework.Scenes.Tests { throw new NotImplementedException(); } + + public override bool CheckClient(UUID agentID, System.Net.IPEndPoint ep) + { + throw new NotImplementedException(); + } } [Test] diff --git a/OpenSim/Region/Framework/Scenes/Tests/SceneObjectBasicTests.cs b/OpenSim/Region/Framework/Scenes/Tests/SceneObjectBasicTests.cs index 78f2ae3aa1..4baa22c0fb 100644 --- a/OpenSim/Region/Framework/Scenes/Tests/SceneObjectBasicTests.cs +++ b/OpenSim/Region/Framework/Scenes/Tests/SceneObjectBasicTests.cs @@ -49,18 +49,62 @@ namespace OpenSim.Region.Framework.Scenes.Tests /// /// Test adding an object to a scene. /// - [Test, LongRunning] + [Test] public void TestAddSceneObject() { TestHelper.InMethod(); Scene scene = SceneSetupHelpers.SetupScene(); - SceneObjectPart part = SceneSetupHelpers.AddSceneObject(scene); - SceneObjectPart retrievedPart = scene.GetSceneObjectPart(part.LocalId); + + string objName = "obj1"; + UUID objUuid = new UUID("00000000-0000-0000-0000-000000000001"); + + SceneObjectPart part + = new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero) + { Name = objName, UUID = objUuid }; + + Assert.That(scene.AddNewSceneObject(new SceneObjectGroup(part), false), Is.True); + + SceneObjectPart retrievedPart = scene.GetSceneObjectPart(objUuid); //m_log.Debug("retrievedPart : {0}", retrievedPart); // If the parts have the same UUID then we will consider them as one and the same - Assert.That(retrievedPart.UUID, Is.EqualTo(part.UUID)); + Assert.That(retrievedPart.Name, Is.EqualTo(objName)); + Assert.That(retrievedPart.UUID, Is.EqualTo(objUuid)); + } + + [Test] + /// + /// It shouldn't be possible to add a scene object if one with that uuid already exists in the scene. + /// + public void TestAddExistingSceneObjectUuid() + { + TestHelper.InMethod(); + + Scene scene = SceneSetupHelpers.SetupScene(); + + string obj1Name = "Alfred"; + string obj2Name = "Betty"; + UUID objUuid = new UUID("00000000-0000-0000-0000-000000000001"); + + SceneObjectPart part1 + = new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero) + { Name = obj1Name, UUID = objUuid }; + + Assert.That(scene.AddNewSceneObject(new SceneObjectGroup(part1), false), Is.True); + + SceneObjectPart part2 + = new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero) + { Name = obj2Name, UUID = objUuid }; + + Assert.That(scene.AddNewSceneObject(new SceneObjectGroup(part2), false), Is.False); + + SceneObjectPart retrievedPart = scene.GetSceneObjectPart(objUuid); + + //m_log.Debug("retrievedPart : {0}", retrievedPart); + // If the parts have the same UUID then we will consider them as one and the same + Assert.That(retrievedPart.Name, Is.EqualTo(obj1Name)); + Assert.That(retrievedPart.UUID, Is.EqualTo(objUuid)); } /// diff --git a/OpenSim/Region/Framework/Scenes/Tests/UuidGathererTests.cs b/OpenSim/Region/Framework/Scenes/Tests/UuidGathererTests.cs index 8b80ebe3dc..5e6124b4f9 100644 --- a/OpenSim/Region/Framework/Scenes/Tests/UuidGathererTests.cs +++ b/OpenSim/Region/Framework/Scenes/Tests/UuidGathererTests.cs @@ -58,7 +58,8 @@ namespace OpenSim.Region.Framework.Scenes.Tests TestHelper.InMethod(); UUID corruptAssetUuid = UUID.Parse("00000000-0000-0000-0000-000000000666"); - AssetBase corruptAsset = AssetHelpers.CreateAsset(corruptAssetUuid, "CORRUPT ASSET", UUID.Zero); + AssetBase corruptAsset + = AssetHelpers.CreateAsset(corruptAssetUuid, AssetType.Notecard, "CORRUPT ASSET", UUID.Zero); m_assetService.Store(corruptAsset); IDictionary foundAssetUuids = new Dictionary(); diff --git a/OpenSim/Region/Framework/Scenes/UuidGatherer.cs b/OpenSim/Region/Framework/Scenes/UuidGatherer.cs index 0ec3cc3c73..e3965ce978 100644 --- a/OpenSim/Region/Framework/Scenes/UuidGatherer.cs +++ b/OpenSim/Region/Framework/Scenes/UuidGatherer.cs @@ -123,8 +123,8 @@ namespace OpenSim.Region.Framework.Scenes foreach (SceneObjectPart part in sceneObject.GetParts()) { - //m_log.DebugFormat( - // "[ARCHIVER]: Getting part {0}, {1} for object {2}", part.Name, part.UUID, sceneObject.UUID); +// m_log.DebugFormat( +// "[ARCHIVER]: Getting part {0}, {1} for object {2}", part.Name, part.UUID, sceneObject.UUID); try { @@ -155,7 +155,9 @@ namespace OpenSim.Region.Framework.Scenes // Now analyze this prim's inventory items to preserve all the uuids that they reference foreach (TaskInventoryItem tii in taskDictionary.Values) { - //m_log.DebugFormat("[ARCHIVER]: Analysing item asset type {0}", tii.Type); +// m_log.DebugFormat( +// "[ARCHIVER]: Analysing item {0} asset type {1} in {2} {3}", +// tii.Name, tii.Type, part.Name, part.UUID); if (!assetUuids.ContainsKey(tii.AssetID)) GatherAssetUuids(tii.AssetID, (AssetType)tii.Type, assetUuids); diff --git a/OpenSim/Region/OptionalModules/Agent/InternetRelayClientView/Server/IRCClientView.cs b/OpenSim/Region/OptionalModules/Agent/InternetRelayClientView/Server/IRCClientView.cs index 488daf8355..039bedbf67 100644 --- a/OpenSim/Region/OptionalModules/Agent/InternetRelayClientView/Server/IRCClientView.cs +++ b/OpenSim/Region/OptionalModules/Agent/InternetRelayClientView/Server/IRCClientView.cs @@ -968,6 +968,11 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server // TODO } + public void SendGenericMessage(string method, List message) + { + + } + public void SendGenericMessage(string method, List message) { @@ -1048,16 +1053,6 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server } - public void SendAvatarData(SendAvatarData data) - { - - } - - public void SendAvatarTerseUpdate(SendAvatarTerseData data) - { - - } - public void SendCoarseLocationUpdate(List users, List CoarseLocations) { @@ -1068,22 +1063,22 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server } - public void SetChildAgentThrottle(byte[] throttle) + public void SendAvatarDataImmediate(ISceneEntity avatar) { - + } - public void SendPrimitiveToClient(SendPrimitiveData data) + public void SendPrimUpdate(ISceneEntity entity, PrimUpdateFlags updateFlags) { - + } - public void SendPrimTerseUpdate(SendPrimitiveTerseData data) + public void ReprioritizeUpdates() { - + } - public void ReprioritizeUpdates(StateUpdateTypes type, UpdatePriorityHandler handler) + public void FlushPrimUpdates() { } @@ -1093,11 +1088,6 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server } - public void FlushPrimUpdates() - { - - } - public void SendInventoryItemDetails(UUID ownerID, InventoryItemBase item) { @@ -1423,6 +1413,11 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server } + public virtual void SetChildAgentThrottle(byte[] throttle) + { + + } + public byte[] GetThrottlesPacked(float multiplier) { return new byte[0]; diff --git a/OpenSim/Region/OptionalModules/Scripting/Minimodule/Interfaces/IInventoryItem.cs b/OpenSim/Region/OptionalModules/Scripting/Minimodule/Interfaces/IInventoryItem.cs index 5fac189d09..16cd7e454e 100644 --- a/OpenSim/Region/OptionalModules/Scripting/Minimodule/Interfaces/IInventoryItem.cs +++ b/OpenSim/Region/OptionalModules/Scripting/Minimodule/Interfaces/IInventoryItem.cs @@ -39,6 +39,6 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule { int Type { get; } UUID AssetID { get; } - T RetreiveAsset() where T : Asset, new(); + T RetrieveAsset() where T : Asset, new(); } } diff --git a/OpenSim/Region/OptionalModules/Scripting/Minimodule/Interfaces/IObject.cs b/OpenSim/Region/OptionalModules/Scripting/Minimodule/Interfaces/IObject.cs index 30580e7919..e189489d75 100644 --- a/OpenSim/Region/OptionalModules/Scripting/Minimodule/Interfaces/IObject.cs +++ b/OpenSim/Region/OptionalModules/Scripting/Minimodule/Interfaces/IObject.cs @@ -97,6 +97,16 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule /// String Description { get; set; } + /// + /// Returns the UUID of the Owner of the Object. + /// + UUID OwnerId { get; } + + /// + /// Returns the UUID of the Creator of the Object. + /// + UUID CreatorId { get; } + /// /// Returns the root object of a linkset. If this object is the root, it will return itself. /// @@ -179,9 +189,25 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule /// /// The message to send to the user void Say(string msg); - + + /// + /// Causes the object to speak to on a specific channel, + /// equivilent to LSL/OSSL llSay + /// + /// The message to send to the user + /// The channel on which to send the message void Say(string msg,int channel); + /// + /// Opens a Dialog Panel in the Users Viewer, + /// equivilent to LSL/OSSL llDialog + /// + /// The UUID of the Avatar to which the Dialog should be send + /// The Message to display at the top of the Dialog + /// The Strings that act as label/value of the Bottons in the Dialog + /// The channel on which to send the response + void Dialog(UUID avatar, string message, string[] buttons, int chat_channel); + //// /// Grants access to the objects inventory /// diff --git a/OpenSim/Region/OptionalModules/Scripting/Minimodule/InventoryItem.cs b/OpenSim/Region/OptionalModules/Scripting/Minimodule/InventoryItem.cs index 5bf29d710c..bf85cbcff5 100644 --- a/OpenSim/Region/OptionalModules/Scripting/Minimodule/InventoryItem.cs +++ b/OpenSim/Region/OptionalModules/Scripting/Minimodule/InventoryItem.cs @@ -39,11 +39,11 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule public class InventoryItem : IInventoryItem { TaskInventoryItem m_privateItem; - Scene m_rootSceene; + Scene m_rootScene; public InventoryItem(Scene rootScene, TaskInventoryItem internalItem) { - m_rootSceene = rootScene; + m_rootScene = rootScene; m_privateItem = internalItem; } @@ -82,9 +82,9 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule public UUID AssetID { get { return m_privateItem.AssetID; } } // This method exposes OpenSim/OpenMetaverse internals and needs to be replaced with a IAsset specific to MRM. - public T RetreiveAsset() where T : OpenMetaverse.Assets.Asset, new() + public T RetrieveAsset() where T : OpenMetaverse.Assets.Asset, new() { - AssetBase a = m_rootSceene.AssetService.Get(AssetID.ToString()); + AssetBase a = m_rootScene.AssetService.Get(AssetID.ToString()); T result = new T(); if ((sbyte)result.AssetType != a.Type) diff --git a/OpenSim/Region/OptionalModules/Scripting/Minimodule/SOPObject.cs b/OpenSim/Region/OptionalModules/Scripting/Minimodule/SOPObject.cs index 5bfe4bedce..96cccb77d0 100644 --- a/OpenSim/Region/OptionalModules/Scripting/Minimodule/SOPObject.cs +++ b/OpenSim/Region/OptionalModules/Scripting/Minimodule/SOPObject.cs @@ -31,6 +31,7 @@ using System.Security; using OpenMetaverse; using OpenMetaverse.Packets; using OpenSim.Framework; +using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.OptionalModules.Scripting.Minimodule.Object; using OpenSim.Region.Physics.Manager; @@ -169,6 +170,16 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule } } + public UUID OwnerId + { + get { return GetSOP().OwnerID;} + } + + public UUID CreatorId + { + get { return GetSOP().CreatorID;} + } + public IObject[] Children { get @@ -392,7 +403,48 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule SceneObjectPart sop = GetSOP(); m_rootScene.SimChat(Utils.StringToBytes(msg), ChatTypeEnum.Say,channel, sop.AbsolutePosition, sop.Name, sop.UUID, false); } - + + public void Dialog(UUID avatar, string message, string[] buttons, int chat_channel) + { + if (!CanEdit()) + return; + + IDialogModule dm = m_rootScene.RequestModuleInterface(); + + if (dm == null) + return; + + if (buttons.Length < 1) + { + Say("ERROR: No less than 1 button can be shown",2147483647); + return; + } + if (buttons.Length > 12) + { + Say("ERROR: No more than 12 buttons can be shown",2147483647); + return; + } + + foreach(string button in buttons) + { + if (button == String.Empty) + { + Say("ERROR: button label cannot be blank",2147483647); + return; + } + if (button.Length > 24) + { + Say("ERROR: button label cannot be longer than 24 characters",2147483647); + return; + } + } + + dm.SendDialogToUser( + avatar, GetSOP().Name, GetSOP().UUID, GetSOP().OwnerID, + message, new UUID("00000000-0000-2222-3333-100000001000"), chat_channel, buttons); + + } + #endregion diff --git a/OpenSim/Region/OptionalModules/Scripting/RegionReadyModule/RegionReadyModule.cs b/OpenSim/Region/OptionalModules/Scripting/RegionReadyModule/RegionReadyModule.cs index c653e98401..672109b773 100644 --- a/OpenSim/Region/OptionalModules/Scripting/RegionReadyModule/RegionReadyModule.cs +++ b/OpenSim/Region/OptionalModules/Scripting/RegionReadyModule/RegionReadyModule.cs @@ -146,6 +146,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.RegionReady c.Position = new Vector3(((int)Constants.RegionSize * 0.5f), ((int)Constants.RegionSize * 0.5f), 30); c.Sender = null; c.SenderUUID = UUID.Zero; + c.Scene = m_scene; m_log.InfoFormat("[RegionReady]: Region \"{0}\" is ready: \"{1}\" on channel {2}", m_scene.RegionInfo.RegionName, c.Message, m_channelNotify); diff --git a/OpenSim/Region/OptionalModules/World/NPC/NPCAvatar.cs b/OpenSim/Region/OptionalModules/World/NPC/NPCAvatar.cs index b38df5a95e..9ac828b3ff 100644 --- a/OpenSim/Region/OptionalModules/World/NPC/NPCAvatar.cs +++ b/OpenSim/Region/OptionalModules/World/NPC/NPCAvatar.cs @@ -554,6 +554,11 @@ namespace OpenSim.Region.OptionalModules.World.NPC } + public void SendGenericMessage(string method, List message) + { + + } + public void SendGenericMessage(string method, List message) { @@ -621,14 +626,6 @@ namespace OpenSim.Region.OptionalModules.World.NPC { } - public virtual void SendAvatarData(SendAvatarData data) - { - } - - public virtual void SendAvatarTerseUpdate(SendAvatarTerseData data) - { - } - public virtual void SendCoarseLocationUpdate(List users, List CoarseLocations) { } @@ -641,15 +638,15 @@ namespace OpenSim.Region.OptionalModules.World.NPC { } - public virtual void SendPrimitiveToClient(SendPrimitiveData data) + public void SendAvatarDataImmediate(ISceneEntity avatar) { } - public virtual void SendPrimTerseUpdate(SendPrimitiveTerseData data) + public void SendPrimUpdate(ISceneEntity entity, PrimUpdateFlags updateFlags) { } - public virtual void ReprioritizeUpdates(StateUpdateTypes type, UpdatePriorityHandler handler) + public void ReprioritizeUpdates() { } diff --git a/OpenSim/Region/Physics/Meshing/PrimMesher.cs b/OpenSim/Region/Physics/Meshing/PrimMesher.cs index 932943c081..53022ad6b4 100644 --- a/OpenSim/Region/Physics/Meshing/PrimMesher.cs +++ b/OpenSim/Region/Physics/Meshing/PrimMesher.cs @@ -257,7 +257,6 @@ namespace PrimMesher public int uv2; public int uv3; - public Face(int v1, int v2, int v3) { primFace = 0; @@ -630,6 +629,9 @@ namespace PrimMesher internal int numOuterVerts = 0; internal int numHollowVerts = 0; + internal int outerFaceNumber = -1; + internal int hollowFaceNumber = -1; + internal bool calcVertexNormals = false; internal int bottomFaceNumber = 0; internal int numPrimFaces = 0; @@ -936,10 +938,10 @@ namespace PrimMesher if (calcVertexNormals && hasProfileCut) { + int lastOuterVertIndex = this.numOuterVerts - 1; + if (hasHollow) { - int lastOuterVertIndex = this.numOuterVerts - 1; - this.cut1CoordIndices.Add(0); this.cut1CoordIndices.Add(this.coords.Count - 1); @@ -955,6 +957,12 @@ namespace PrimMesher else { + this.cut1CoordIndices.Add(0); + this.cut1CoordIndices.Add(1); + + this.cut2CoordIndices.Add(lastOuterVertIndex); + this.cut2CoordIndices.Add(0); + this.cutNormal1.X = this.vertexNormals[1].Y; this.cutNormal1.Y = -this.vertexNormals[1].X; @@ -979,11 +987,14 @@ namespace PrimMesher // I know it's ugly but so is the whole concept of prim face numbers int faceNum = 1; // start with outer faces + this.outerFaceNumber = faceNum; + int startVert = hasProfileCut && !hasHollow ? 1 : 0; if (startVert > 0) this.faceNumbers.Add(-1); for (int i = 0; i < this.numOuterVerts - 1; i++) - this.faceNumbers.Add(sides < 5 ? faceNum++ : faceNum); + //this.faceNumbers.Add(sides < 5 ? faceNum++ : faceNum); + this.faceNumbers.Add(sides < 5 && i < sides ? faceNum++ : faceNum); //if (!hasHollow && !hasProfileCut) // this.bottomFaceNumber = faceNum++; @@ -993,12 +1004,15 @@ namespace PrimMesher if (sides > 4 && (hasHollow || hasProfileCut)) faceNum++; + if (sides < 5 && (hasHollow || hasProfileCut) && this.numOuterVerts < sides) + faceNum++; + if (hasHollow) { for (int i = 0; i < this.numHollowVerts; i++) this.faceNumbers.Add(faceNum); - faceNum++; + this.hollowFaceNumber = faceNum++; } //if (hasProfileCut || hasHollow) // this.bottomFaceNumber = faceNum++; @@ -1006,11 +1020,11 @@ namespace PrimMesher if (hasHollow && hasProfileCut) this.faceNumbers.Add(faceNum++); + for (int i = 0; i < this.faceNumbers.Count; i++) if (this.faceNumbers[i] == -1) this.faceNumbers[i] = faceNum++; - this.numPrimFaces = faceNum; } @@ -1455,11 +1469,15 @@ namespace PrimMesher public float revolutions = 1.0f; public int stepsPerRevolution = 24; + private int profileOuterFaceNumber = -1; + private int profileHollowFaceNumber = -1; + private bool hasProfileCut = false; private bool hasHollow = false; public bool calcVertexNormals = false; private bool normalsProcessed = false; public bool viewerMode = false; + public bool sphereMode = false; public int numPrimFaces = 0; @@ -1491,10 +1509,35 @@ namespace PrimMesher s += "\nradius...............: " + this.radius.ToString(); s += "\nrevolutions..........: " + this.revolutions.ToString(); s += "\nstepsPerRevolution...: " + this.stepsPerRevolution.ToString(); + s += "\nsphereMode...........: " + this.sphereMode.ToString(); + s += "\nhasProfileCut........: " + this.hasProfileCut.ToString(); + s += "\nhasHollow............: " + this.hasHollow.ToString(); + s += "\nviewerMode...........: " + this.viewerMode.ToString(); return s; } + public int ProfileOuterFaceNumber + { + get { return profileOuterFaceNumber; } + } + + public int ProfileHollowFaceNumber + { + get { return profileHollowFaceNumber; } + } + + public bool HasProfileCut + { + get { return hasProfileCut; } + } + + public bool HasHollow + { + get { return hasHollow; } + } + + /// /// Constructs a PrimMesh object and creates the profile for extrusion. /// @@ -1531,8 +1574,12 @@ namespace PrimMesher if (hollow < 0.0f) this.hollow = 0.0f; - this.hasProfileCut = (this.profileStart > 0.0f || this.profileEnd < 1.0f); - this.hasHollow = (this.hollow > 0.001f); + //if (sphereMode) + // this.hasProfileCut = this.profileEnd - this.profileStart < 0.4999f; + //else + // //this.hasProfileCut = (this.profileStart > 0.0f || this.profileEnd < 1.0f); + // this.hasProfileCut = this.profileEnd - this.profileStart < 0.9999f; + //this.hasHollow = (this.hollow > 0.001f); } /// @@ -1540,6 +1587,8 @@ namespace PrimMesher /// public void Extrude(PathType pathType) { + bool needEndFaces = false; + this.coords = new List(); this.faces = new List(); @@ -1565,6 +1614,12 @@ namespace PrimMesher steps = (int)(steps * 4.5 * length); } + if (sphereMode) + this.hasProfileCut = this.profileEnd - this.profileStart < 0.4999f; + else + //this.hasProfileCut = (this.profileStart > 0.0f || this.profileEnd < 1.0f); + this.hasProfileCut = this.profileEnd - this.profileStart < 0.9999f; + this.hasHollow = (this.hollow > 0.001f); float twistBegin = this.twistBegin / 360.0f * twoPi; float twistEnd = this.twistEnd / 360.0f * twoPi; @@ -1634,6 +1689,32 @@ namespace PrimMesher this.numPrimFaces = profile.numPrimFaces; + //profileOuterFaceNumber = profile.faceNumbers[0]; + //if (!needEndFaces) + // profileOuterFaceNumber--; + //profileOuterFaceNumber = needEndFaces ? 1 : 0; + + + //if (hasHollow) + //{ + // if (needEndFaces) + // profileHollowFaceNumber = profile.faceNumbers[profile.numOuterVerts + 1]; + // else + // profileHollowFaceNumber = profile.faceNumbers[profile.numOuterVerts] - 1; + //} + + + profileOuterFaceNumber = profile.outerFaceNumber; + if (!needEndFaces) + profileOuterFaceNumber--; + + if (hasHollow) + { + profileHollowFaceNumber = profile.hollowFaceNumber; + if (!needEndFaces) + profileHollowFaceNumber--; + } + int cut1Vert = -1; int cut2Vert = -1; if (hasProfileCut) @@ -1673,7 +1754,7 @@ namespace PrimMesher path.Create(pathType, steps); - bool needEndFaces = false; + if (pathType == PathType.Circular) { needEndFaces = false; @@ -1761,7 +1842,7 @@ namespace PrimMesher int startVert = coordsLen + 1; int endVert = this.coords.Count; - if (sides < 5 || this.hasProfileCut || hollow > 0.0f) + if (sides < 5 || this.hasProfileCut || this.hasHollow) startVert--; for (int i = startVert; i < endVert; i++) @@ -1813,11 +1894,13 @@ namespace PrimMesher u1 -= (int)u1; if (u2 < 0.1f) u2 = 1.0f; + //this.profileOuterFaceNumber = primFaceNum; } else if (whichVert > profile.coords.Count - profile.numHollowVerts - 1) { u1 *= 2.0f; u2 *= 2.0f; + //this.profileHollowFaceNumber = primFaceNum; } } diff --git a/OpenSim/Region/Physics/Meshing/SculptMap.cs b/OpenSim/Region/Physics/Meshing/SculptMap.cs new file mode 100644 index 0000000000..d2d71deade --- /dev/null +++ b/OpenSim/Region/Physics/Meshing/SculptMap.cs @@ -0,0 +1,176 @@ +/* + * Copyright (c) Contributors + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +// to build without references to System.Drawing, comment this out +#define SYSTEM_DRAWING + +using System; +using System.Collections.Generic; +using System.Text; + +#if SYSTEM_DRAWING +using System.Drawing; +using System.Drawing.Imaging; + +namespace PrimMesher +{ + public class SculptMap + { + public int width; + public int height; + public byte[] redBytes; + public byte[] greenBytes; + public byte[] blueBytes; + + public SculptMap() + { + } + + public SculptMap(Bitmap bm, int lod) + { + int bmW = bm.Width; + int bmH = bm.Height; + + if (bmW == 0 || bmH == 0) + throw new Exception("SculptMap: bitmap has no data"); + + int numLodPixels = lod * 2 * lod * 2; // (32 * 2)^2 = 64^2 pixels for default sculpt map image + + bool needsScaling = false; + + width = bmW; + height = bmH; + while (width * height > numLodPixels) + { + width >>= 1; + height >>= 1; + needsScaling = true; + } + + + + try + { + if (needsScaling) + bm = ScaleImage(bm, width, height, + System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor); + } + + catch (Exception e) + { + throw new Exception("Exception in ScaleImage(): e: " + e.ToString()); + } + + if (width * height > lod * lod) + { + width >>= 1; + height >>= 1; + } + + int numBytes = (width + 1) * (height + 1); + redBytes = new byte[numBytes]; + greenBytes = new byte[numBytes]; + blueBytes = new byte[numBytes]; + + int byteNdx = 0; + + try + { + for (int y = 0; y <= height; y++) + { + for (int x = 0; x <= width; x++) + { + int bmY = y < height ? y * 2 : y * 2 - 1; + int bmX = x < width ? x * 2 : x * 2 - 1; + Color c = bm.GetPixel(bmX, bmY); + + redBytes[byteNdx] = c.R; + greenBytes[byteNdx] = c.G; + blueBytes[byteNdx] = c.B; + + ++byteNdx; + } + } + } + catch (Exception e) + { + throw new Exception("Caught exception processing byte arrays in SculptMap(): e: " + e.ToString()); + } + + width++; + height++; + } + + public List> ToRows(bool mirror) + { + int numRows = height; + int numCols = width; + + List> rows = new List>(numRows); + + float pixScale = 1.0f / 255; + + int rowNdx, colNdx; + int smNdx = 0; + + for (rowNdx = 0; rowNdx < numRows; rowNdx++) + { + List row = new List(numCols); + for (colNdx = 0; colNdx < numCols; colNdx++) + { + if (mirror) + row.Add(new Coord(-(redBytes[smNdx] * pixScale - 0.5f), (greenBytes[smNdx] * pixScale - 0.5f), blueBytes[smNdx] * pixScale - 0.5f)); + else + row.Add(new Coord(redBytes[smNdx] * pixScale - 0.5f, greenBytes[smNdx] * pixScale - 0.5f, blueBytes[smNdx] * pixScale - 0.5f)); + + ++smNdx; + } + rows.Add(row); + } + return rows; + } + + private Bitmap ScaleImage(Bitmap srcImage, int destWidth, int destHeight, + System.Drawing.Drawing2D.InterpolationMode interpMode) + { + Bitmap scaledImage = new Bitmap(srcImage, destWidth, destHeight); + scaledImage.SetResolution(96.0f, 96.0f); + + Graphics grPhoto = Graphics.FromImage(scaledImage); + grPhoto.InterpolationMode = interpMode; + + grPhoto.DrawImage(srcImage, + new Rectangle(0, 0, destWidth, destHeight), + new Rectangle(0, 0, srcImage.Width, srcImage.Height), + GraphicsUnit.Pixel); + + grPhoto.Dispose(); + return scaledImage; + } + } +} +#endif diff --git a/OpenSim/Region/Physics/Meshing/SculptMesh.cs b/OpenSim/Region/Physics/Meshing/SculptMesh.cs index ebc5be61b1..e58eb896bb 100644 --- a/OpenSim/Region/Physics/Meshing/SculptMesh.cs +++ b/OpenSim/Region/Physics/Meshing/SculptMesh.cs @@ -53,50 +53,6 @@ namespace PrimMesher public enum SculptType { sphere = 1, torus = 2, plane = 3, cylinder = 4 }; #if SYSTEM_DRAWING - private Bitmap ScaleImage(Bitmap srcImage, float scale, bool removeAlpha) - { - int sourceWidth = srcImage.Width; - int sourceHeight = srcImage.Height; - int sourceX = 0; - int sourceY = 0; - - int destX = 0; - int destY = 0; - int destWidth = (int)(srcImage.Width * scale); - int destHeight = (int)(srcImage.Height * scale); - - Bitmap scaledImage; - - if (removeAlpha) - { - if (srcImage.PixelFormat == PixelFormat.Format32bppArgb) - for (int y = 0; y < srcImage.Height; y++) - for (int x = 0; x < srcImage.Width; x++) - { - Color c = srcImage.GetPixel(x, y); - srcImage.SetPixel(x, y, Color.FromArgb(255, c.R, c.G, c.B)); - } - - scaledImage = new Bitmap(destWidth, destHeight, - PixelFormat.Format24bppRgb); - } - else - scaledImage = new Bitmap(srcImage, destWidth, destHeight); - - scaledImage.SetResolution(96.0f, 96.0f); - - Graphics grPhoto = Graphics.FromImage(scaledImage); - grPhoto.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Low; - - grPhoto.DrawImage(srcImage, - new Rectangle(destX, destY, destWidth, destHeight), - new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight), - GraphicsUnit.Pixel); - - grPhoto.Dispose(); - return scaledImage; - } - public SculptMesh SculptMeshFromFile(string fileName, SculptType sculptType, int lod, bool viewerMode) { @@ -106,6 +62,7 @@ namespace PrimMesher return sculptMesh; } + public SculptMesh(string fileName, int sculptType, int lod, int viewerMode, int mirror, int invert) { Bitmap bitmap = (Bitmap)Bitmap.FromFile(fileName); @@ -296,36 +253,53 @@ namespace PrimMesher return rows; } + private List> bitmap2CoordsSampled(Bitmap bitmap, int scale, bool mirror) + { + int numRows = bitmap.Height / scale; + int numCols = bitmap.Width / scale; + List> rows = new List>(numRows); + + float pixScale = 1.0f / 256.0f; + + int imageX, imageY = 0; + + int rowNdx, colNdx; + + for (rowNdx = 0; rowNdx <= numRows; rowNdx++) + { + List row = new List(numCols); + imageY = rowNdx * scale; + if (rowNdx == numRows) imageY--; + for (colNdx = 0; colNdx <= numCols; colNdx++) + { + imageX = colNdx * scale; + if (colNdx == numCols) imageX--; + + Color c = bitmap.GetPixel(imageX, imageY); + if (c.A != 255) + { + bitmap.SetPixel(imageX, imageY, Color.FromArgb(255, c.R, c.G, c.B)); + c = bitmap.GetPixel(imageX, imageY); + } + + if (mirror) + row.Add(new Coord(-(c.R * pixScale - 0.5f), c.G * pixScale - 0.5f, c.B * pixScale - 0.5f)); + else + row.Add(new Coord(c.R * pixScale - 0.5f, c.G * pixScale - 0.5f, c.B * pixScale - 0.5f)); + + } + rows.Add(row); + } + return rows; + } + void _SculptMesh(Bitmap sculptBitmap, SculptType sculptType, int lod, bool viewerMode, bool mirror, bool invert) { - coords = new List(); - faces = new List(); - normals = new List(); - uvs = new List(); - - sculptType = (SculptType)(((int)sculptType) & 0x07); - - if (mirror) - if (sculptType == SculptType.plane) - invert = !invert; - - float sculptBitmapLod = (float)Math.Sqrt(sculptBitmap.Width * sculptBitmap.Height); - - float sourceScaleFactor = (float)(lod) / sculptBitmapLod; - - float fScale = 1.0f / sourceScaleFactor; - - int iScale = (int)fScale; - if (iScale < 1) iScale = 1; - if (iScale > 2 && iScale % 2 == 0) - _SculptMesh(bitmap2Coords(ScaleImage(sculptBitmap, 64.0f / sculptBitmapLod, true), 64 / lod, mirror), sculptType, viewerMode, mirror, invert); - else - _SculptMesh(bitmap2Coords(sculptBitmap, iScale, mirror), sculptType, viewerMode, mirror, invert); + _SculptMesh(new SculptMap(sculptBitmap, lod).ToRows(mirror), sculptType, viewerMode, mirror, invert); } #endif - void _SculptMesh(List> rows, SculptType sculptType, bool viewerMode, bool mirror, bool invert) { coords = new List(); @@ -336,8 +310,7 @@ namespace PrimMesher sculptType = (SculptType)(((int)sculptType) & 0x07); if (mirror) - if (sculptType == SculptType.plane) - invert = !invert; + invert = !invert; viewerFaces = new List(); @@ -349,8 +322,18 @@ namespace PrimMesher if (sculptType != SculptType.plane) { - for (int rowNdx = 0; rowNdx < rows.Count; rowNdx++) - rows[rowNdx].Add(rows[rowNdx][0]); + if (rows.Count % 2 == 0) + { + for (int rowNdx = 0; rowNdx < rows.Count; rowNdx++) + rows[rowNdx].Add(rows[rowNdx][0]); + } + else + { + int lastIndex = rows[0].Count - 1; + + for (int i = 0; i < rows.Count; i++) + rows[i][0] = rows[i][lastIndex]; + } } Coord topPole = rows[0][width / 2]; @@ -358,23 +341,41 @@ namespace PrimMesher if (sculptType == SculptType.sphere) { - int count = rows[0].Count; - List topPoleRow = new List(count); - List bottomPoleRow = new List(count); - - for (int i = 0; i < count; i++) + if (rows.Count % 2 == 0) { - topPoleRow.Add(topPole); - bottomPoleRow.Add(bottomPole); + int count = rows[0].Count; + List topPoleRow = new List(count); + List bottomPoleRow = new List(count); + + for (int i = 0; i < count; i++) + { + topPoleRow.Add(topPole); + bottomPoleRow.Add(bottomPole); + } + rows.Insert(0, topPoleRow); + rows.Add(bottomPoleRow); + } + else + { + int count = rows[0].Count; + + List topPoleRow = rows[0]; + List bottomPoleRow = rows[rows.Count - 1]; + + for (int i = 0; i < count; i++) + { + topPoleRow[i] = topPole; + bottomPoleRow[i] = bottomPole; + } } - rows.Insert(0, topPoleRow); - rows.Add(bottomPoleRow); } - else if (sculptType == SculptType.torus) + + if (sculptType == SculptType.torus) rows.Add(rows[0]); int coordsDown = rows.Count; int coordsAcross = rows[0].Count; + int lastColumn = coordsAcross - 1; float widthUnit = 1.0f / (coordsAcross - 1); float heightUnit = 1.0f / (coordsDown - 1); diff --git a/OpenSim/Region/RegionCombinerModule/RegionCombinerLargeLandChannel.cs b/OpenSim/Region/RegionCombinerModule/RegionCombinerLargeLandChannel.cs index 9da818a7eb..33ff707e9f 100644 --- a/OpenSim/Region/RegionCombinerModule/RegionCombinerLargeLandChannel.cs +++ b/OpenSim/Region/RegionCombinerModule/RegionCombinerLargeLandChannel.cs @@ -140,6 +140,16 @@ public class RegionCombinerLargeLandChannel : ILandChannel RootRegionLandChannel.UpdateLandObject(localID, data); } + public void Join(int start_x, int start_y, int end_x, int end_y, UUID attempting_user_id) + { + RootRegionLandChannel.Join(start_x, start_y, end_x, end_y, attempting_user_id); + } + + public void Subdivide(int start_x, int start_y, int end_x, int end_y, UUID attempting_user_id) + { + RootRegionLandChannel.Subdivide(start_x, start_y, end_x, end_y, attempting_user_id); + } + public void ReturnObjectsInParcel(int localID, uint returnType, UUID[] agentIDs, UUID[] taskIDs, IClientAPI remoteClient) { RootRegionLandChannel.ReturnObjectsInParcel(localID, returnType, agentIDs, taskIDs, remoteClient); diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs index 3ccbb3abc6..6e9a823c87 100644 --- a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs +++ b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs @@ -1890,14 +1890,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api float ground = World.GetGroundHeight((float)targetPos.x, (float)targetPos.y); bool disable_underground_movement = m_ScriptEngine.Config.GetBoolean("DisableUndergroundMovement", true); - if (part.ParentGroup == null) - { - if ((targetPos.z < ground) && disable_underground_movement) - targetPos.z = ground; - LSL_Vector real_vec = SetPosAdjust(currentPos, targetPos); - part.UpdateOffSet(new Vector3((float)real_vec.x, (float)real_vec.y, (float)real_vec.z)); - } - else if (part.ParentGroup.RootPart == part) + if (part.ParentGroup.RootPart == part) { if ((targetPos.z < ground) && disable_underground_movement) targetPos.z = ground; @@ -1907,7 +1900,6 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api } else { - //it's late... i think this is right ? if (llVecDist(new LSL_Vector(0,0,0), targetPos) <= 10.0f) { part.OffsetPosition = new Vector3((float)targetPos.x, (float)targetPos.y, (float)targetPos.z); @@ -3514,7 +3506,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api } parentPrim.TriggerScriptChangedEvent(Changed.LINK); - parentPrim.RootPart.AddFlag(PrimFlags.CreateSelected); + parentPrim.RootPart.CreateSelected = true; parentPrim.HasGroupChanged = true; parentPrim.ScheduleGroupForFullUpdate(); @@ -3892,8 +3884,10 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api UserAccount account = World.UserAccountService.GetUserAccount(World.RegionInfo.ScopeID, uuid); + PresenceInfo pinfo = null; PresenceInfo[] pinfos = World.PresenceService.GetAgents(new string[] { uuid.ToString() }); - PresenceInfo pinfo = PresenceInfo.GetOnlinePresence(pinfos); + if (pinfos != null && pinfos.Length > 0) + pinfo = pinfos[0]; if (pinfo == null) return UUID.Zero.ToString(); @@ -5602,7 +5596,10 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api public LSL_String llGetLandOwnerAt(LSL_Vector pos) { m_host.AddScriptLPS(1); - return World.LandChannel.GetLandObject((float)pos.x, (float)pos.y).LandData.OwnerID.ToString(); + ILandObject land = World.LandChannel.GetLandObject((float)pos.x, (float)pos.y); + if (land == null) + return UUID.Zero.ToString(); + return land.LandData.OwnerID.ToString(); } /// diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/OSSL_Api.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/OSSL_Api.cs index 7e68cc749c..7ada738084 100644 --- a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/OSSL_Api.cs +++ b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/OSSL_Api.cs @@ -105,6 +105,18 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api // modification of user data, or allows the compromise of // sensitive data by design. + class FunctionPerms + { + public List AllowedCreators; + public List AllowedOwners; + + public FunctionPerms() + { + AllowedCreators = new List(); + AllowedOwners = new List(); + } + } + [Serializable] public class OSSL_Api : MarshalByRefObject, IOSSL_Api, IScriptApi { @@ -117,7 +129,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api internal ThreatLevel m_MaxThreatLevel = ThreatLevel.VeryLow; internal float m_ScriptDelayFactor = 1.0f; internal float m_ScriptDistanceFactor = 1.0f; - internal Dictionary > m_FunctionPerms = new Dictionary >(); + internal Dictionary m_FunctionPerms = new Dictionary(); public void Initialize(IScriptEngine ScriptEngine, SceneObjectPart host, uint localID, UUID itemID) { @@ -217,31 +229,33 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api if (!m_FunctionPerms.ContainsKey(function)) { - string perm = m_ScriptEngine.Config.GetString("Allow_" + function, ""); - if (perm == "") + FunctionPerms perms = new FunctionPerms(); + m_FunctionPerms[function] = perms; + + string ownerPerm = m_ScriptEngine.Config.GetString("Allow_" + function, ""); + string creatorPerm = m_ScriptEngine.Config.GetString("Creators_" + function, ""); + if (ownerPerm == "" && creatorPerm == "") { - m_FunctionPerms[function] = null; // a null value is default + // Default behavior + perms.AllowedOwners = null; + perms.AllowedCreators = null; } else { bool allowed; - if (bool.TryParse(perm, out allowed)) + if (bool.TryParse(ownerPerm, out allowed)) { // Boolean given if (allowed) { - m_FunctionPerms[function] = new List(); - m_FunctionPerms[function].Add(UUID.Zero); + // Allow globally + perms.AllowedOwners.Add(UUID.Zero); } - else - m_FunctionPerms[function] = new List(); // Empty list = none } else { - m_FunctionPerms[function] = new List(); - - string[] ids = perm.Split(new char[] {','}); + string[] ids = ownerPerm.Split(new char[] {','}); foreach (string id in ids) { string current = id.Trim(); @@ -250,7 +264,20 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api if (UUID.TryParse(current, out uuid)) { if (uuid != UUID.Zero) - m_FunctionPerms[function].Add(uuid); + perms.AllowedOwners.Add(uuid); + } + } + + ids = creatorPerm.Split(new char[] {','}); + foreach (string id in ids) + { + string current = id.Trim(); + UUID uuid; + + if (UUID.TryParse(current, out uuid)) + { + if (uuid != UUID.Zero) + perms.AllowedCreators.Add(uuid); } } } @@ -266,8 +293,9 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api // // To allow use by anyone, the list contains UUID.Zero // - if (m_FunctionPerms[function] == null) // No list = true + if (m_FunctionPerms[function].AllowedOwners == null) { + // Allow / disallow by threat level if (level > m_MaxThreatLevel) OSSLError( String.Format( @@ -276,12 +304,34 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api } else { - if (!m_FunctionPerms[function].Contains(UUID.Zero)) + if (!m_FunctionPerms[function].AllowedOwners.Contains(UUID.Zero)) { - if (!m_FunctionPerms[function].Contains(m_host.OwnerID)) + // Not anyone. Do detailed checks + if (m_FunctionPerms[function].AllowedOwners.Contains(m_host.OwnerID)) + { + // prim owner is in the list of allowed owners + return; + } + + TaskInventoryItem ti = m_host.Inventory.GetInventoryItem(m_itemID); + if (ti == null) + { OSSLError( - String.Format("{0} permission denied. Prim owner is not in the list of users allowed to execute this function.", + String.Format("{0} permission error. Can't find script in prim inventory.", function)); + } + if (!m_FunctionPerms[function].AllowedCreators.Contains(ti.CreatorID)) + OSSLError( + String.Format("{0} permission denied. Script creator is not in the list of users allowed to execute this function and prim owner also has no permission.", + function)); + if (ti.CreatorID != ti.OwnerID) + { + if ((ti.CurrentPermissions & (uint)PermissionMask.Modify) != 0) + OSSLError( + String.Format("{0} permission denied. Script permissions error.", + function)); + + } } } } @@ -1129,7 +1179,89 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api return 0.0f; } + // Routines for creating and managing parcels programmatically + public void osParcelJoin(LSL_Vector pos1, LSL_Vector pos2) + { + CheckThreatLevel(ThreatLevel.High, "osParcelJoin"); + m_host.AddScriptLPS(1); + int startx = (int)(pos1.x < pos2.x ? pos1.x : pos2.x); + int starty = (int)(pos1.y < pos2.y ? pos1.y : pos2.y); + int endx = (int)(pos1.x > pos2.x ? pos1.x : pos2.x); + int endy = (int)(pos1.y > pos2.y ? pos1.y : pos2.y); + + World.LandChannel.Join(startx,starty,endx,endy,m_host.OwnerID); + } + + public void osParcelSubdivide(LSL_Vector pos1, LSL_Vector pos2) + { + CheckThreatLevel(ThreatLevel.High, "osParcelSubdivide"); + m_host.AddScriptLPS(1); + + int startx = (int)(pos1.x < pos2.x ? pos1.x : pos2.x); + int starty = (int)(pos1.y < pos2.y ? pos1.y : pos2.y); + int endx = (int)(pos1.x > pos2.x ? pos1.x : pos2.x); + int endy = (int)(pos1.y > pos2.y ? pos1.y : pos2.y); + + World.LandChannel.Subdivide(startx,starty,endx,endy,m_host.OwnerID); + } + + public void osParcelSetDetails(LSL_Vector pos, LSL_List rules) + { + CheckThreatLevel(ThreatLevel.High, "osParcelSetDetails"); + m_host.AddScriptLPS(1); + + // Get a reference to the land data and make sure the owner of the script + // can modify it + + ILandObject startLandObject = World.LandChannel.GetLandObject((int)pos.x, (int)pos.y); + if (startLandObject == null) + { + OSSLShoutError("There is no land at that location"); + return; + } + + if (! World.Permissions.CanEditParcel(m_host.OwnerID, startLandObject)) + { + OSSLShoutError("You do not have permission to modify the parcel"); + return; + } + + // Create a new land data object we can modify + LandData newLand = startLandObject.LandData.Copy(); + UUID uuid; + + // Process the rules, not sure what the impact would be of changing owner or group + for (int idx = 0; idx < rules.Length; ) + { + int code = rules.GetLSLIntegerItem(idx++); + string arg = rules.GetLSLStringItem(idx++); + switch (code) + { + case 0: + newLand.Name = arg; + break; + + case 1: + newLand.Description = arg; + break; + + case 2: + CheckThreatLevel(ThreatLevel.VeryHigh, "osParcelSetDetails"); + if (UUID.TryParse(arg , out uuid)) + newLand.OwnerID = uuid; + break; + + case 3: + CheckThreatLevel(ThreatLevel.VeryHigh, "osParcelSetDetails"); + if (UUID.TryParse(arg , out uuid)) + newLand.GroupID = uuid; + break; + } + } + + World.LandChannel.UpdateLandObject(newLand.LocalID,newLand); + } public double osList2Double(LSL_Types.list src, int index) { @@ -2055,4 +2187,4 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api } } } -} \ No newline at end of file +} diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/Plugins/SensorRepeat.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/Plugins/SensorRepeat.cs index 2296379da7..5c2abd5e9d 100644 --- a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/Plugins/SensorRepeat.cs +++ b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/Plugins/SensorRepeat.cs @@ -302,6 +302,15 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api.Plugins float dz; Quaternion q = SensePoint.RotationOffset; + if (SensePoint.ParentGroup.RootPart.IsAttachment) + { + // In attachments, the sensor cone always orients with the + // avatar rotation. This may include a nonzero elevation if + // in mouselook. + + ScenePresence avatar = m_CmdManager.m_ScriptEngine.World.GetScenePresence(SensePoint.ParentGroup.RootPart.AttachedAvatar); + q = avatar.Rotation; + } LSL_Types.Quaternion r = new LSL_Types.Quaternion(q.X, q.Y, q.Z, q.W); LSL_Types.Vector3 forward_dir = (new LSL_Types.Vector3(1, 0, 0) * r); double mag_fwd = LSL_Types.Vector3.Mag(forward_dir); @@ -463,6 +472,10 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api.Plugins sensedEntities.Add(new SensedEntity(dis, presence.UUID)); } } + else + { + sensedEntities.Add(new SensedEntity(dis, presence.UUID)); + } } }); diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Interface/IOSSL_Api.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Interface/IOSSL_Api.cs index 60b8050cd1..7a8f469746 100644 --- a/OpenSim/Region/ScriptEngine/Shared/Api/Interface/IOSSL_Api.cs +++ b/OpenSim/Region/ScriptEngine/Shared/Api/Interface/IOSSL_Api.cs @@ -123,6 +123,10 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api.Interfaces void osWindParamSet(string plugin, string param, float value); float osWindParamGet(string plugin, string param); + // Parcel commands + void osParcelJoin(vector pos1, vector pos2); + void osParcelSubdivide(vector pos1, vector pos2); + void osParcelSetDetails(vector pos, LSL_List rules); string osGetScriptEngineName(); string osGetSimulatorVersion(); diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/LSL_Constants.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/LSL_Constants.cs index ee35fa4b6a..dba6502f4b 100644 --- a/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/LSL_Constants.cs +++ b/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/LSL_Constants.cs @@ -548,5 +548,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase public const int STATS_ACTIVE_SCRIPTS = 19; public const int STATS_SCRIPT_LPS = 20; + public const string URL_REQUEST_GRANTED = "URL_REQUEST_GRANTED"; + public const string URL_REQUEST_DENIED = "URL_REQUEST_DENIED"; } } diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/OSSL_Stub.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/OSSL_Stub.cs index 3870af3213..fd9309aefc 100644 --- a/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/OSSL_Stub.cs +++ b/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/OSSL_Stub.cs @@ -106,6 +106,21 @@ namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase // return m_OSSL_Functions.osWindParamGet(plugin, param); // } + public void osParcelJoin(vector pos1, vector pos2) + { + m_OSSL_Functions.osParcelJoin(pos1,pos2); + } + + public void osParcelSubdivide(vector pos1, vector pos2) + { + m_OSSL_Functions.osParcelSubdivide(pos1, pos2); + } + + public void osParcelSetDetails(vector pos, LSL_List rules) + { + m_OSSL_Functions.osParcelSetDetails(pos,rules); + } + public double osList2Double(LSL_Types.list src, int index) { return m_OSSL_Functions.osList2Double(src, index); diff --git a/OpenSim/Region/ScriptEngine/Shared/CodeTools/Compiler.cs b/OpenSim/Region/ScriptEngine/Shared/CodeTools/Compiler.cs index d8c0ba57a5..cd8c67e601 100644 --- a/OpenSim/Region/ScriptEngine/Shared/CodeTools/Compiler.cs +++ b/OpenSim/Region/ScriptEngine/Shared/CodeTools/Compiler.cs @@ -32,7 +32,7 @@ using System.Globalization; using System.Reflection; using System.IO; using Microsoft.CSharp; -using Microsoft.JScript; +//using Microsoft.JScript; using Microsoft.VisualBasic; using log4net; using OpenSim.Region.Framework.Interfaces; @@ -82,7 +82,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.CodeTools private static CSharpCodeProvider CScodeProvider = new CSharpCodeProvider(); private static VBCodeProvider VBcodeProvider = new VBCodeProvider(); - private static JScriptCodeProvider JScodeProvider = new JScriptCodeProvider(); +// private static JScriptCodeProvider JScodeProvider = new JScriptCodeProvider(); private static CSharpCodeProvider YPcodeProvider = new CSharpCodeProvider(); // YP is translated into CSharp private static YP2CSConverter YP_Converter = new YP2CSConverter(); @@ -261,13 +261,18 @@ namespace OpenSim.Region.ScriptEngine.Shared.CodeTools // } //} - public object GetCompilerOutput(UUID assetID) + public string GetCompilerOutput(string assetID) { return Path.Combine(ScriptEnginesPath, Path.Combine( m_scriptEngine.World.RegionInfo.RegionID.ToString(), FilePrefix + "_compiled_" + assetID + ".dll")); } + public string GetCompilerOutput(UUID assetID) + { + return GetCompilerOutput(assetID.ToString()); + } + /// /// Converts script from LSL to CS and calls CompileFromCSText /// @@ -279,9 +284,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.CodeTools linemap = null; m_warnings.Clear(); - assembly = Path.Combine(ScriptEnginesPath, Path.Combine( - m_scriptEngine.World.RegionInfo.RegionID.ToString(), - FilePrefix + "_compiled_" + asset + ".dll")); + assembly = GetCompilerOutput(asset); if (!Directory.Exists(ScriptEnginesPath)) { @@ -395,9 +398,9 @@ namespace OpenSim.Region.ScriptEngine.Shared.CodeTools case enumCompileType.vb: compileScript = CreateVBCompilerScript(compileScript); break; - case enumCompileType.js: - compileScript = CreateJSCompilerScript(compileScript); - break; +// case enumCompileType.js: +// compileScript = CreateJSCompilerScript(compileScript); +// break; case enumCompileType.yp: compileScript = CreateYPCompilerScript(compileScript); break; @@ -420,16 +423,16 @@ namespace OpenSim.Region.ScriptEngine.Shared.CodeTools } } - private static string CreateJSCompilerScript(string compileScript) - { - compileScript = String.Empty + - "import OpenSim.Region.ScriptEngine.Shared; import System.Collections.Generic;\r\n" + - "package SecondLife {\r\n" + - "class Script extends OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass { \r\n" + - compileScript + - "} }\r\n"; - return compileScript; - } +// private static string CreateJSCompilerScript(string compileScript) +// { +// compileScript = String.Empty + +// "import OpenSim.Region.ScriptEngine.Shared; import System.Collections.Generic;\r\n" + +// "package SecondLife {\r\n" + +// "class Script extends OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass { \r\n" + +// compileScript + +// "} }\r\n"; +// return compileScript; +// } private static string CreateCSCompilerScript(string compileScript) { @@ -580,10 +583,10 @@ namespace OpenSim.Region.ScriptEngine.Shared.CodeTools } } while (!complete); break; - case enumCompileType.js: - results = JScodeProvider.CompileAssemblyFromSource( - parameters, Script); - break; +// case enumCompileType.js: +// results = JScodeProvider.CompileAssemblyFromSource( +// parameters, Script); +// break; case enumCompileType.yp: results = YPcodeProvider.CompileAssemblyFromSource( parameters, Script); diff --git a/OpenSim/Server/Handlers/Asset/AssetServerConnector.cs b/OpenSim/Server/Handlers/Asset/AssetServerConnector.cs index f7eb292091..b6425f4c49 100644 --- a/OpenSim/Server/Handlers/Asset/AssetServerConnector.cs +++ b/OpenSim/Server/Handlers/Asset/AssetServerConnector.cs @@ -59,9 +59,11 @@ namespace OpenSim.Server.Handlers.Asset m_AssetService = ServerUtils.LoadPlugin(assetService, args); + bool allowDelete = serverConfig.GetBoolean("AllowRemoteDelete", false); + server.AddStreamHandler(new AssetServerGetHandler(m_AssetService)); server.AddStreamHandler(new AssetServerPostHandler(m_AssetService)); - server.AddStreamHandler(new AssetServerDeleteHandler(m_AssetService)); + server.AddStreamHandler(new AssetServerDeleteHandler(m_AssetService, allowDelete)); } } } diff --git a/OpenSim/Server/Handlers/Asset/AssetServerDeleteHandler.cs b/OpenSim/Server/Handlers/Asset/AssetServerDeleteHandler.cs index f33bb90fde..8014fb5354 100644 --- a/OpenSim/Server/Handlers/Asset/AssetServerDeleteHandler.cs +++ b/OpenSim/Server/Handlers/Asset/AssetServerDeleteHandler.cs @@ -47,11 +47,13 @@ namespace OpenSim.Server.Handlers.Asset // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IAssetService m_AssetService; + protected bool m_allowDelete; - public AssetServerDeleteHandler(IAssetService service) : + public AssetServerDeleteHandler(IAssetService service, bool allowDelete) : base("DELETE", "/assets") { m_AssetService = service; + m_allowDelete = allowDelete; } public override byte[] Handle(string path, Stream request, @@ -61,9 +63,9 @@ namespace OpenSim.Server.Handlers.Asset string[] p = SplitParams(path); - if (p.Length > 0) + if (p.Length > 0 && m_allowDelete) { - // result = m_AssetService.Delete(p[0]); + result = m_AssetService.Delete(p[0]); } XmlSerializer xs = new XmlSerializer(typeof(bool)); diff --git a/OpenSim/Data/SQLite/Tests/SQLiteEstateTest.cs b/OpenSim/Server/Handlers/GridUser/GridUserServerConnector.cs similarity index 57% rename from OpenSim/Data/SQLite/Tests/SQLiteEstateTest.cs rename to OpenSim/Server/Handlers/GridUser/GridUserServerConnector.cs index 30f66414a9..66f35e3bdc 100644 --- a/OpenSim/Data/SQLite/Tests/SQLiteEstateTest.cs +++ b/OpenSim/Server/Handlers/GridUser/GridUserServerConnector.cs @@ -25,41 +25,37 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -using System.IO; -using NUnit.Framework; -using OpenSim.Data.Tests; -using OpenSim.Tests.Common; +using System; +using Nini.Config; +using OpenSim.Server.Base; +using OpenSim.Services.Interfaces; +using OpenSim.Framework.Servers.HttpServer; +using OpenSim.Server.Handlers.Base; -namespace OpenSim.Data.SQLite.Tests +namespace OpenSim.Server.Handlers.GridUser { - [TestFixture, DatabaseTest] - public class SQLiteEstateTest : BasicEstateTest + public class GridUserServiceConnector : ServiceConnector { - public string file = "regiontest.db"; - public string connect; - - [TestFixtureSetUp] - public void Init() - { - // SQLite doesn't work on power or z linux - if (Directory.Exists("/proc/ppc64") || Directory.Exists("/proc/dasd")) - { - Assert.Ignore(); - } + private IGridUserService m_GridUserService; + private string m_ConfigName = "GridUserService"; - SuperInit(); - file = Path.GetTempFileName() + ".db"; - connect = "URI=file:" + file + ",version=3"; - db = new SQLiteEstateStore(); - db.Initialise(connect); - regionDb = new SQLiteRegionData(); - regionDb.Initialise(connect); - } - - [TestFixtureTearDown] - public void Cleanup() + public GridUserServiceConnector(IConfigSource config, IHttpServer server, string configName) : + base(config, server, configName) { - regionDb.Dispose(); + IConfig serverConfig = config.Configs[m_ConfigName]; + if (serverConfig == null) + throw new Exception(String.Format("No section {0} in config file", m_ConfigName)); + + string service = serverConfig.GetString("LocalServiceModule", + String.Empty); + + if (service == String.Empty) + throw new Exception("No LocalServiceModule in config file"); + + Object[] args = new Object[] { config }; + m_GridUserService = ServerUtils.LoadPlugin(service, args); + + server.AddStreamHandler(new GridUserServerPostHandler(m_GridUserService)); } } } diff --git a/OpenSim/Server/Handlers/GridUser/GridUserServerPostHandler.cs b/OpenSim/Server/Handlers/GridUser/GridUserServerPostHandler.cs new file mode 100644 index 0000000000..f8fa42967f --- /dev/null +++ b/OpenSim/Server/Handlers/GridUser/GridUserServerPostHandler.cs @@ -0,0 +1,278 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using Nini.Config; +using log4net; +using System; +using System.Reflection; +using System.IO; +using System.Net; +using System.Text; +using System.Text.RegularExpressions; +using System.Xml; +using System.Xml.Serialization; +using System.Collections.Generic; +using OpenSim.Server.Base; +using OpenSim.Services.Interfaces; +using OpenSim.Framework; +using OpenSim.Framework.Servers.HttpServer; +using OpenMetaverse; + +namespace OpenSim.Server.Handlers.GridUser +{ + public class GridUserServerPostHandler : BaseStreamHandler + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private IGridUserService m_GridUserService; + + public GridUserServerPostHandler(IGridUserService service) : + base("POST", "/griduser") + { + m_GridUserService = service; + } + + 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 + { + Dictionary request = + ServerUtils.ParseQueryString(body); + + if (!request.ContainsKey("METHOD")) + return FailureResult(); + + method = request["METHOD"].ToString(); + + switch (method) + { + case "loggedin": + return LoggedIn(request); + case "loggedout": + return LoggedOut(request); + case "sethome": + return SetHome(request); + case "setposition": + return SetPosition(request); + case "getgriduserinfo": + return GetGridUserInfo(request); + } + m_log.DebugFormat("[GRID USER HANDLER]: unknown method request: {0}", method); + } + catch (Exception e) + { + m_log.DebugFormat("[GRID USER HANDLER]: Exception in method {0}: {1}", method, e); + } + + return FailureResult(); + + } + + byte[] LoggedIn(Dictionary request) + { + string user = String.Empty; + + if (!request.ContainsKey("UserID")) + return FailureResult(); + + user = request["UserID"].ToString(); + + GridUserInfo guinfo = m_GridUserService.LoggedIn(user); + + Dictionary result = new Dictionary(); + result["result"] = guinfo.ToKeyValuePairs(); + + string xmlString = ServerUtils.BuildXmlResponse(result); + //m_log.DebugFormat("[GRID USER HANDLER]: resp string: {0}", xmlString); + UTF8Encoding encoding = new UTF8Encoding(); + return encoding.GetBytes(xmlString); + + } + + byte[] LoggedOut(Dictionary request) + { + string userID = string.Empty; + UUID regionID = UUID.Zero; + Vector3 position = Vector3.Zero; + Vector3 lookat = Vector3.Zero; + + if (!UnpackArgs(request, out userID, out regionID, out position, out lookat)) + return FailureResult(); + + if (m_GridUserService.LoggedOut(userID, regionID, position, lookat)) + return SuccessResult(); + + return FailureResult(); + } + + byte[] SetHome(Dictionary request) + { + string user = string.Empty; + UUID region = UUID.Zero; + Vector3 position = new Vector3(128, 128, 70); + Vector3 look = Vector3.Zero; + + if (!UnpackArgs(request, out user, out region, out position, out look)) + return FailureResult(); + + if (m_GridUserService.SetHome(user, region, position, look)) + return SuccessResult(); + + return FailureResult(); + } + + byte[] SetPosition(Dictionary request) + { + string user = string.Empty; + UUID region = UUID.Zero; + Vector3 position = new Vector3(128, 128, 70); + Vector3 look = Vector3.Zero; + + if (!request.ContainsKey("UserID") || !request.ContainsKey("RegionID")) + return FailureResult(); + + if (!UnpackArgs(request, out user, out region, out position, out look)) + return FailureResult(); + + if (m_GridUserService.SetLastPosition(user, region, position, look)) + return SuccessResult(); + + return FailureResult(); + } + + byte[] GetGridUserInfo(Dictionary request) + { + string user = String.Empty; + + if (!request.ContainsKey("UserID")) + return FailureResult(); + + user = request["UserID"].ToString(); + + GridUserInfo guinfo = m_GridUserService.GetGridUserInfo(user); + + Dictionary result = new Dictionary(); + result["result"] = guinfo.ToKeyValuePairs(); + + string xmlString = ServerUtils.BuildXmlResponse(result); + //m_log.DebugFormat("[GRID USER HANDLER]: resp string: {0}", xmlString); + UTF8Encoding encoding = new UTF8Encoding(); + return encoding.GetBytes(xmlString); + + } + + private bool UnpackArgs(Dictionary request, out string user, out UUID region, out Vector3 position, out Vector3 lookAt) + { + user = string.Empty; + region = UUID.Zero; + position = new Vector3(128, 128, 70); + lookAt = Vector3.Zero; + + if (!request.ContainsKey("UserID") || !request.ContainsKey("RegionID")) + return false; + + user = request["UserID"].ToString(); + + if (!UUID.TryParse(request["RegionID"].ToString(), out region)) + return false; + + if (request.ContainsKey("Position")) + Vector3.TryParse(request["Position"].ToString(), out position); + + if (request.ContainsKey("LookAt")) + Vector3.TryParse(request["LookAt"].ToString(), out lookAt); + + return true; + } + + + private byte[] SuccessResult() + { + XmlDocument doc = new XmlDocument(); + + XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, + "", ""); + + doc.AppendChild(xmlnode); + + XmlElement rootElement = doc.CreateElement("", "ServerResponse", + ""); + + doc.AppendChild(rootElement); + + XmlElement result = doc.CreateElement("", "result", ""); + result.AppendChild(doc.CreateTextNode("Success")); + + rootElement.AppendChild(result); + + return DocToBytes(doc); + } + + private byte[] FailureResult() + { + XmlDocument doc = new XmlDocument(); + + XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, + "", ""); + + doc.AppendChild(xmlnode); + + XmlElement rootElement = doc.CreateElement("", "ServerResponse", + ""); + + doc.AppendChild(rootElement); + + XmlElement result = doc.CreateElement("", "result", ""); + result.AppendChild(doc.CreateTextNode("Failure")); + + rootElement.AppendChild(result); + + return DocToBytes(doc); + } + + private byte[] DocToBytes(XmlDocument doc) + { + MemoryStream ms = new MemoryStream(); + XmlTextWriter xw = new XmlTextWriter(ms, null); + xw.Formatting = Formatting.Indented; + doc.WriteTo(xw); + xw.Flush(); + + return ms.ToArray(); + } + + + } +} diff --git a/OpenSim/Server/Handlers/Hypergrid/GatekeeperServerConnector.cs b/OpenSim/Server/Handlers/Hypergrid/GatekeeperServerConnector.cs index f2d9321c3f..dcb27257a0 100644 --- a/OpenSim/Server/Handlers/Hypergrid/GatekeeperServerConnector.cs +++ b/OpenSim/Server/Handlers/Hypergrid/GatekeeperServerConnector.cs @@ -70,7 +70,6 @@ namespace OpenSim.Server.Handlers.Hypergrid server.AddXmlRPCHandler("get_region", hghandlers.GetRegion, false); server.AddHTTPHandler("/foreignagent/", new GatekeeperAgentHandler(m_GatekeeperService).Handler); - } public GatekeeperServiceInConnector(IConfigSource config, IHttpServer server) diff --git a/OpenSim/Server/Handlers/Hypergrid/HGInventoryServerInConnector.cs b/OpenSim/Server/Handlers/Hypergrid/HGInventoryServerInConnector.cs deleted file mode 100644 index 41897eb5a2..0000000000 --- a/OpenSim/Server/Handlers/Hypergrid/HGInventoryServerInConnector.cs +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Net; -using System.Reflection; -using log4net; -using Nini.Config; -using Nwc.XmlRpc; -using OpenSim.Server.Base; -using OpenSim.Server.Handlers.Inventory; -using OpenSim.Services.Interfaces; -using OpenSim.Framework; -using OpenSim.Framework.Servers.HttpServer; -using OpenSim.Server.Handlers.Base; -using OpenMetaverse; - -namespace OpenSim.Server.Handlers.Hypergrid -{ - public class HGInventoryServiceInConnector : InventoryServiceInConnector - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - //private static readonly int INVENTORY_DEFAULT_SESSION_TIME = 30; // secs - //private AuthedSessionCache m_session_cache = new AuthedSessionCache(INVENTORY_DEFAULT_SESSION_TIME); - - private IUserAgentService m_UserAgentService; - - public HGInventoryServiceInConnector(IConfigSource config, IHttpServer server, string configName) : - base(config, server, configName) - { - IConfig serverConfig = config.Configs[m_ConfigName]; - if (serverConfig == null) - throw new Exception(String.Format("No section '{0}' in config file", m_ConfigName)); - - string userAgentService = serverConfig.GetString("UserAgentService", string.Empty); - string m_userserver_url = serverConfig.GetString("UserAgentURI", String.Empty); - if (m_userserver_url != string.Empty) - { - Object[] args = new Object[] { m_userserver_url }; - m_UserAgentService = ServerUtils.LoadPlugin(userAgentService, args); - } - - AddHttpHandlers(server); - m_log.Debug("[HG INVENTORY HANDLER]: handlers initialized"); - } - - /// - /// Check that the source of an inventory request for a particular agent is a current session belonging to - /// that agent. - /// - /// - /// - /// - public override bool CheckAuthSession(string session_id, string avatar_id) - { - //m_log.InfoFormat("[HG INVENTORY IN CONNECTOR]: checking authed session {0} {1}", session_id, avatar_id); - // This doesn't work - - // if (m_session_cache.getCachedSession(session_id, avatar_id) == null) - // { - // //cache miss, ask userserver - // m_UserAgentService.VerifyAgent(session_id, ???); - // } - // else - // { - // // cache hits - // m_log.Info("[HG INVENTORY IN CONNECTOR]: got authed session from cache"); - // return true; - // } - - // m_log.Warn("[HG INVENTORY IN CONNECTOR]: unknown session_id, request rejected"); - // return false; - - return true; - } - } -} diff --git a/OpenSim/Server/Handlers/Hypergrid/HomeAgentHandlers.cs b/OpenSim/Server/Handlers/Hypergrid/HomeAgentHandlers.cs index 17d7850666..e50481a259 100644 --- a/OpenSim/Server/Handlers/Hypergrid/HomeAgentHandlers.cs +++ b/OpenSim/Server/Handlers/Hypergrid/HomeAgentHandlers.cs @@ -61,13 +61,13 @@ namespace OpenSim.Server.Handlers.Hypergrid public Hashtable Handler(Hashtable request) { - m_log.Debug("[CONNECTION DEBUGGING]: HomeAgentHandler Called"); - - m_log.Debug("---------------------------"); - m_log.Debug(" >> uri=" + request["uri"]); - m_log.Debug(" >> content-type=" + request["content-type"]); - m_log.Debug(" >> http-method=" + request["http-method"]); - m_log.Debug("---------------------------\n"); +// m_log.Debug("[CONNECTION DEBUGGING]: HomeAgentHandler Called"); +// +// m_log.Debug("---------------------------"); +// m_log.Debug(" >> uri=" + request["uri"]); +// m_log.Debug(" >> content-type=" + request["content-type"]); +// m_log.Debug(" >> http-method=" + request["http-method"]); +// m_log.Debug("---------------------------\n"); Hashtable responsedata = new Hashtable(); responsedata["content_type"] = "text/html"; diff --git a/OpenSim/Server/Handlers/Hypergrid/HypergridHandlers.cs b/OpenSim/Server/Handlers/Hypergrid/HypergridHandlers.cs index 0b65245896..5d03097b32 100644 --- a/OpenSim/Server/Handlers/Hypergrid/HypergridHandlers.cs +++ b/OpenSim/Server/Handlers/Hypergrid/HypergridHandlers.cs @@ -48,6 +48,7 @@ namespace OpenSim.Server.Handlers.Hypergrid public HypergridHandlers(IGatekeeperService gatekeeper) { m_GatekeeperService = gatekeeper; + m_log.DebugFormat("[HYPERGRID HANDLERS]: Active"); } /// @@ -61,6 +62,8 @@ namespace OpenSim.Server.Handlers.Hypergrid //string host = (string)requestData["host"]; //string portstr = (string)requestData["port"]; string name = (string)requestData["region_name"]; + if (name == null) + name = string.Empty; UUID regionID = UUID.Zero; string externalName = string.Empty; diff --git a/OpenSim/Server/Handlers/Inventory/XInventoryInConnector.cs b/OpenSim/Server/Handlers/Inventory/XInventoryInConnector.cs index 34f7dccc4e..b0fee6d4cb 100644 --- a/OpenSim/Server/Handlers/Inventory/XInventoryInConnector.cs +++ b/OpenSim/Server/Handlers/Inventory/XInventoryInConnector.cs @@ -91,7 +91,7 @@ namespace OpenSim.Server.Handlers.Asset sr.Close(); body = body.Trim(); - m_log.DebugFormat("[XXX]: query String: {0}", body); + //m_log.DebugFormat("[XXX]: query String: {0}", body); try { @@ -197,7 +197,7 @@ namespace OpenSim.Server.Handlers.Asset return ms.ToArray(); } - + byte[] HandleCreateUserInventory(Dictionary request) { Dictionary result = new Dictionary(); @@ -211,7 +211,7 @@ namespace OpenSim.Server.Handlers.Asset result["RESULT"] = "False"; string xmlString = ServerUtils.BuildXmlResponse(result); - m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); + //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); UTF8Encoding encoding = new UTF8Encoding(); return encoding.GetBytes(xmlString); } @@ -226,12 +226,20 @@ namespace OpenSim.Server.Handlers.Asset List folders = m_InventoryService.GetInventorySkeleton(new UUID(request["PRINCIPAL"].ToString())); + Dictionary sfolders = new Dictionary(); if (folders != null) + { + int i = 0; foreach (InventoryFolderBase f in folders) - result[f.ID.ToString()] = EncodeFolder(f); + { + sfolders["folder_" + i.ToString()] = EncodeFolder(f); + i++; + } + } + result["FOLDERS"] = sfolders; string xmlString = ServerUtils.BuildXmlResponse(result); - m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); + //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); UTF8Encoding encoding = new UTF8Encoding(); return encoding.GetBytes(xmlString); } @@ -244,10 +252,10 @@ namespace OpenSim.Server.Handlers.Asset UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); InventoryFolderBase rfolder = m_InventoryService.GetRootFolder(principal); if (rfolder != null) - result[rfolder.ID.ToString()] = EncodeFolder(rfolder); + result["folder"] = EncodeFolder(rfolder); string xmlString = ServerUtils.BuildXmlResponse(result); - m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); + //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); UTF8Encoding encoding = new UTF8Encoding(); return encoding.GetBytes(xmlString); } @@ -261,10 +269,10 @@ namespace OpenSim.Server.Handlers.Asset Int32.TryParse(request["TYPE"].ToString(), out type); InventoryFolderBase folder = m_InventoryService.GetFolderForType(principal, (AssetType)type); if (folder != null) - result[folder.ID.ToString()] = EncodeFolder(folder); + result["folder"] = EncodeFolder(folder); string xmlString = ServerUtils.BuildXmlResponse(result); - m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); + //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); UTF8Encoding encoding = new UTF8Encoding(); return encoding.GetBytes(xmlString); } @@ -281,18 +289,26 @@ namespace OpenSim.Server.Handlers.Asset if (icoll != null) { Dictionary folders = new Dictionary(); + int i = 0; foreach (InventoryFolderBase f in icoll.Folders) - folders[f.ID.ToString()] = EncodeFolder(f); + { + folders["folder_" + i.ToString()] = EncodeFolder(f); + i++; + } result["FOLDERS"] = folders; + i = 0; Dictionary items = new Dictionary(); - foreach (InventoryItemBase i in icoll.Items) - items[i.ID.ToString()] = EncodeItem(i); + foreach (InventoryItemBase it in icoll.Items) + { + items["item_" + i.ToString()] = EncodeItem(it); + i++; + } result["ITEMS"] = items; } string xmlString = ServerUtils.BuildXmlResponse(result); - m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); + //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); UTF8Encoding encoding = new UTF8Encoding(); return encoding.GetBytes(xmlString); } @@ -306,12 +322,21 @@ namespace OpenSim.Server.Handlers.Asset UUID.TryParse(request["FOLDER"].ToString(), out folderID); List items = m_InventoryService.GetFolderItems(principal, folderID); + Dictionary sitems = new Dictionary(); + if (items != null) + { + int i = 0; foreach (InventoryItemBase item in items) - result[item.ID.ToString()] = EncodeItem(item); + { + sitems["item_" + i.ToString()] = EncodeItem(item); + i++; + } + } + result["ITEMS"] = sitems; string xmlString = ServerUtils.BuildXmlResponse(result); - m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); + //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); UTF8Encoding encoding = new UTF8Encoding(); return encoding.GetBytes(xmlString); } @@ -481,10 +506,10 @@ namespace OpenSim.Server.Handlers.Asset InventoryItemBase item = new InventoryItemBase(id); item = m_InventoryService.GetItem(item); if (item != null) - result[item.ID.ToString()] = EncodeItem(item); + result["item"] = EncodeItem(item); string xmlString = ServerUtils.BuildXmlResponse(result); - m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); + //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); UTF8Encoding encoding = new UTF8Encoding(); return encoding.GetBytes(xmlString); } @@ -498,10 +523,10 @@ namespace OpenSim.Server.Handlers.Asset InventoryFolderBase folder = new InventoryFolderBase(id); folder = m_InventoryService.GetFolder(folder); if (folder != null) - result[folder.ID.ToString()] = EncodeFolder(folder); + result["folder"] = EncodeFolder(folder); string xmlString = ServerUtils.BuildXmlResponse(result); - m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); + //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); UTF8Encoding encoding = new UTF8Encoding(); return encoding.GetBytes(xmlString); } @@ -513,12 +538,20 @@ namespace OpenSim.Server.Handlers.Asset UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); List gestures = m_InventoryService.GetActiveGestures(principal); + Dictionary items = new Dictionary(); if (gestures != null) + { + int i = 0; foreach (InventoryItemBase item in gestures) - result[item.ID.ToString()] = EncodeItem(item); + { + items["item_" + i.ToString()] = EncodeItem(item); + i++; + } + } + result["ITEMS"] = items; string xmlString = ServerUtils.BuildXmlResponse(result); - m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); + //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); UTF8Encoding encoding = new UTF8Encoding(); return encoding.GetBytes(xmlString); } @@ -535,11 +568,12 @@ namespace OpenSim.Server.Handlers.Asset result["RESULT"] = perms.ToString(); string xmlString = ServerUtils.BuildXmlResponse(result); - m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); + //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); UTF8Encoding encoding = new UTF8Encoding(); return encoding.GetBytes(xmlString); } + private Dictionary EncodeFolder(InventoryFolderBase f) { Dictionary ret = new Dictionary(); @@ -569,7 +603,7 @@ namespace OpenSim.Server.Handlers.Asset ret["Flags"] = item.Flags.ToString(); ret["Folder"] = item.Folder.ToString(); ret["GroupID"] = item.GroupID.ToString(); - ret["GroupedOwned"] = item.GroupOwned.ToString(); + ret["GroupOwned"] = item.GroupOwned.ToString(); ret["GroupPermissions"] = item.GroupPermissions.ToString(); ret["ID"] = item.ID.ToString(); ret["InvType"] = item.InvType.ToString(); @@ -623,5 +657,6 @@ namespace OpenSim.Server.Handlers.Asset return item; } + } } diff --git a/OpenSim/Server/Handlers/Login/LLLoginHandlers.cs b/OpenSim/Server/Handlers/Login/LLLoginHandlers.cs index aaa958b218..c9bf99619f 100644 --- a/OpenSim/Server/Handlers/Login/LLLoginHandlers.cs +++ b/OpenSim/Server/Handlers/Login/LLLoginHandlers.cs @@ -72,6 +72,9 @@ namespace OpenSim.Server.Handlers.Login string last = requestData["last"].ToString(); string passwd = requestData["passwd"].ToString(); string startLocation = string.Empty; + UUID scopeID = UUID.Zero; + if (requestData["scope_id"] != null) + scopeID = new UUID(requestData["scope_id"].ToString()); if (requestData.ContainsKey("start")) startLocation = requestData["start"].ToString(); @@ -83,7 +86,7 @@ namespace OpenSim.Server.Handlers.Login m_log.InfoFormat("[LOGIN]: XMLRPC Login Requested for {0} {1}, starting in {2}, using {3}", first, last, startLocation, clientVersion); LoginResponse reply = null; - reply = m_LocalService.Login(first, last, passwd, startLocation, remoteClient); + reply = m_LocalService.Login(first, last, passwd, startLocation, scopeID, clientVersion, remoteClient); XmlRpcResponse response = new XmlRpcResponse(); response.Value = reply.ToHashtable(); @@ -96,6 +99,43 @@ namespace OpenSim.Server.Handlers.Login } + public XmlRpcResponse HandleXMLRPCSetLoginLevel(XmlRpcRequest request, IPEndPoint remoteClient) + { + Hashtable requestData = (Hashtable)request.Params[0]; + + if (requestData != null) + { + if (requestData.ContainsKey("first") && requestData["first"] != null && + requestData.ContainsKey("last") && requestData["last"] != null && + requestData.ContainsKey("level") && requestData["level"] != null && + requestData.ContainsKey("passwd") && requestData["passwd"] != null) + { + string first = requestData["first"].ToString(); + string last = requestData["last"].ToString(); + string passwd = requestData["passwd"].ToString(); + int level = Int32.Parse(requestData["level"].ToString()); + + m_log.InfoFormat("[LOGIN]: XMLRPC Set Level to {2} Requested by {0} {1}", first, last, level); + + Hashtable reply = m_LocalService.SetLevel(first, last, passwd, level, remoteClient); + + XmlRpcResponse response = new XmlRpcResponse(); + response.Value = reply; + + return response; + + } + } + + XmlRpcResponse failResponse = new XmlRpcResponse(); + Hashtable failHash = new Hashtable(); + failHash["success"] = "false"; + failResponse.Value = failHash; + + return failResponse; + + } + public OSD HandleLLSDLogin(OSD request, IPEndPoint remoteClient) { if (request.Type == OSDType.Map) @@ -109,10 +149,15 @@ namespace OpenSim.Server.Handlers.Login if (map.ContainsKey("start")) startLocation = map["start"].AsString(); + UUID scopeID = UUID.Zero; + + if (map.ContainsKey("scope_id")) + scopeID = new UUID(map["scope_id"].AsString()); + m_log.Info("[LOGIN]: LLSD Login Requested for: '" + map["first"].AsString() + "' '" + map["last"].AsString() + "' / " + startLocation); LoginResponse reply = null; - reply = m_LocalService.Login(map["first"].AsString(), map["last"].AsString(), map["passwd"].AsString(), startLocation, remoteClient); + reply = m_LocalService.Login(map["first"].AsString(), map["last"].AsString(), map["passwd"].AsString(), startLocation, scopeID, String.Empty, remoteClient); return reply.ToOSDMap(); } diff --git a/OpenSim/Server/Handlers/Login/LLLoginServiceInConnector.cs b/OpenSim/Server/Handlers/Login/LLLoginServiceInConnector.cs index e24055b015..67e83924d0 100644 --- a/OpenSim/Server/Handlers/Login/LLLoginServiceInConnector.cs +++ b/OpenSim/Server/Handlers/Login/LLLoginServiceInConnector.cs @@ -88,6 +88,7 @@ namespace OpenSim.Server.Handlers.Login { LLLoginHandlers loginHandlers = new LLLoginHandlers(m_LoginService); server.AddXmlRPCHandler("login_to_simulator", loginHandlers.HandleXMLRPCLogin, false); + server.AddXmlRPCHandler("set_login_level", loginHandlers.HandleXMLRPCSetLoginLevel, false); server.SetDefaultLLSDHandler(loginHandlers.HandleLLSDLogin); } diff --git a/OpenSim/Server/Handlers/Presence/PresenceServerPostHandler.cs b/OpenSim/Server/Handlers/Presence/PresenceServerPostHandler.cs index 4ebf93329c..3104917f83 100644 --- a/OpenSim/Server/Handlers/Presence/PresenceServerPostHandler.cs +++ b/OpenSim/Server/Handlers/Presence/PresenceServerPostHandler.cs @@ -90,8 +90,6 @@ namespace OpenSim.Server.Handlers.Presence return GetAgent(request); case "getagents": return GetAgents(request); - case "sethome": - return SetHome(request); } m_log.DebugFormat("[PRESENCE HANDLER]: unknown method request: {0}", method); } @@ -140,12 +138,7 @@ namespace OpenSim.Server.Handlers.Presence if (!UUID.TryParse(request["SessionID"].ToString(), out session)) return FailureResult(); - if (request.ContainsKey("Position") && request["Position"] != null) - Vector3.TryParse(request["Position"].ToString(), out position); - if (request.ContainsKey("LookAt") && request["Position"] != null) - Vector3.TryParse(request["LookAt"].ToString(), out lookat); - - if (m_PresenceService.LogoutAgent(session, position, lookat)) + if (m_PresenceService.LogoutAgent(session)) return SuccessResult(); return FailureResult(); @@ -171,8 +164,6 @@ namespace OpenSim.Server.Handlers.Presence { UUID session = UUID.Zero; UUID region = UUID.Zero; - Vector3 position = new Vector3(128, 128, 70); - Vector3 look = Vector3.Zero; if (!request.ContainsKey("SessionID") || !request.ContainsKey("RegionID")) return FailureResult(); @@ -183,13 +174,7 @@ namespace OpenSim.Server.Handlers.Presence if (!UUID.TryParse(request["RegionID"].ToString(), out region)) return FailureResult(); - if (request.ContainsKey("position")) - Vector3.TryParse(request["position"].ToString(), out position); - - if (request.ContainsKey("lookAt")) - Vector3.TryParse(request["lookAt"].ToString(), out look); - - if (m_PresenceService.ReportAgent(session, region, position, look)) + if (m_PresenceService.ReportAgent(session, region)) { return SuccessResult(); } @@ -318,31 +303,5 @@ namespace OpenSim.Server.Handlers.Presence return ms.ToArray(); } - byte[] SetHome(Dictionary request) - { - UUID region = UUID.Zero; - Vector3 position = new Vector3(128, 128, 70); - Vector3 look = Vector3.Zero; - - if (!request.ContainsKey("UserID") || !request.ContainsKey("RegionID")) - return FailureResult(); - - string user = request["UserID"].ToString(); - - if (!UUID.TryParse(request["RegionID"].ToString(), out region)) - return FailureResult(); - - if (request.ContainsKey("position")) - Vector3.TryParse(request["position"].ToString(), out position); - - if (request.ContainsKey("lookAt")) - Vector3.TryParse(request["lookAt"].ToString(), out look); - - if (m_PresenceService.SetHomeLocation(user, region, position, look)) - return SuccessResult(); - - return FailureResult(); - } - } } diff --git a/OpenSim/Server/Handlers/Simulation/AgentHandlers.cs b/OpenSim/Server/Handlers/Simulation/AgentHandlers.cs index ab3250d45f..191acc946a 100644 --- a/OpenSim/Server/Handlers/Simulation/AgentHandlers.cs +++ b/OpenSim/Server/Handlers/Simulation/AgentHandlers.cs @@ -61,13 +61,13 @@ namespace OpenSim.Server.Handlers.Simulation public Hashtable Handler(Hashtable request) { - m_log.Debug("[CONNECTION DEBUGGING]: AgentHandler Called"); - - m_log.Debug("---------------------------"); - m_log.Debug(" >> uri=" + request["uri"]); - m_log.Debug(" >> content-type=" + request["content-type"]); - m_log.Debug(" >> http-method=" + request["http-method"]); - m_log.Debug("---------------------------\n"); +// m_log.Debug("[CONNECTION DEBUGGING]: AgentHandler Called"); +// +// m_log.Debug("---------------------------"); +// m_log.Debug(" >> uri=" + request["uri"]); +// m_log.Debug(" >> content-type=" + request["content-type"]); +// m_log.Debug(" >> http-method=" + request["http-method"]); +// m_log.Debug("---------------------------\n"); Hashtable responsedata = new Hashtable(); responsedata["content_type"] = "text/html"; diff --git a/OpenSim/Server/ServerMain.cs b/OpenSim/Server/ServerMain.cs index d3e65a4bdd..9503c4cff6 100644 --- a/OpenSim/Server/ServerMain.cs +++ b/OpenSim/Server/ServerMain.cs @@ -61,7 +61,7 @@ namespace OpenSim.Server string connList = serverConfig.GetString("ServiceConnectors", String.Empty); string[] conns = connList.Split(new char[] {',', ' '}); - int i = 0; +// int i = 0; foreach (string c in conns) { if (c == String.Empty) diff --git a/OpenSim/Services/AssetService/AssetService.cs b/OpenSim/Services/AssetService/AssetService.cs index ed87f3f6fc..470a4ddcc5 100644 --- a/OpenSim/Services/AssetService/AssetService.cs +++ b/OpenSim/Services/AssetService/AssetService.cs @@ -106,7 +106,10 @@ namespace OpenSim.Services.AssetService return null; AssetBase asset = m_Database.GetAsset(assetID); - return asset.Metadata; + if (asset != null) + return asset.Metadata; + + return null; } public byte[] GetData(string id) @@ -153,6 +156,22 @@ namespace OpenSim.Services.AssetService public bool Delete(string id) { + m_log.DebugFormat("[ASSET SERVICE]: Deleting asset {0}", id); + UUID assetID; + if (!UUID.TryParse(id, out assetID)) + return false; + + AssetBase asset = m_Database.GetAsset(assetID); + if (asset == null) + return false; + + if ((int)(asset.Flags & AssetFlags.Maptile) != 0) + { + return m_Database.Delete(id); + } + else + m_log.DebugFormat("[ASSET SERVICE]: Request to delete asset {0}, but flags are not Maptile", id); + return false; } @@ -178,6 +197,7 @@ namespace OpenSim.Services.AssetService MainConsole.Instance.Output(String.Format("Description: {0}", asset.Description)); MainConsole.Instance.Output(String.Format("Type: {0}", asset.Type)); MainConsole.Instance.Output(String.Format("Content-type: {0}", asset.Metadata.ContentType)); + MainConsole.Instance.Output(String.Format("Flags: {0}", asset.Metadata.Flags.ToString())); for (i = 0 ; i < 5 ; i++) { diff --git a/OpenSim/Services/Connectors/Friends/FriendsSimConnector.cs b/OpenSim/Services/Connectors/Friends/FriendsSimConnector.cs index a29ac2887c..d7cb015f6a 100644 --- a/OpenSim/Services/Connectors/Friends/FriendsSimConnector.cs +++ b/OpenSim/Services/Connectors/Friends/FriendsSimConnector.cs @@ -158,7 +158,7 @@ namespace OpenSim.Services.Connectors.Friends } catch (Exception e) { - m_log.DebugFormat("[FRIENDS CONNECTOR]: Exception when contacting remote sim: {0}", e.Message); + m_log.DebugFormat("[FRIENDS CONNECTOR]: Exception when contacting remote sim: {0}", e.ToString()); } return false; diff --git a/OpenSim/Services/Connectors/Grid/GridServiceConnector.cs b/OpenSim/Services/Connectors/Grid/GridServiceConnector.cs index a453d99721..0ec8912abd 100644 --- a/OpenSim/Services/Connectors/Grid/GridServiceConnector.cs +++ b/OpenSim/Services/Connectors/Grid/GridServiceConnector.cs @@ -300,7 +300,7 @@ namespace OpenSim.Services.Connectors if (replyData["result"] is Dictionary) rinfo = new GridRegion((Dictionary)replyData["result"]); else - m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition {0}, {1}-{2} received invalid response", + m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition {0}, {1}-{2} received no region", scopeID, x, y); } else @@ -391,9 +391,6 @@ namespace OpenSim.Services.Connectors GridRegion rinfo = new GridRegion((Dictionary)r); rinfos.Add(rinfo); } - else - m_log.DebugFormat("[GRID CONNECTOR]: GetRegionsByName {0}, {1}, {2} received invalid response", - scopeID, name, maxNumber); } } else diff --git a/OpenSim/Services/Connectors/GridUser/GridUserServiceConnector.cs b/OpenSim/Services/Connectors/GridUser/GridUserServiceConnector.cs index 0e8506706c..600ddfdaf0 100644 --- a/OpenSim/Services/Connectors/GridUser/GridUserServiceConnector.cs +++ b/OpenSim/Services/Connectors/GridUser/GridUserServiceConnector.cs @@ -25,14 +25,206 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +using log4net; using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using Nini.Config; +using OpenSim.Framework; +using OpenSim.Framework.Communications; +using OpenSim.Framework.Servers.HttpServer; +using OpenSim.Services.Interfaces; +using GridRegion = OpenSim.Services.Interfaces.GridRegion; +using OpenSim.Server.Base; +using OpenMetaverse; namespace OpenSim.Services.Connectors { - public class GridUserServiceConnector + public class GridUserServicesConnector : IGridUserService { - public GridUserServiceConnector() + private static readonly ILog m_log = + LogManager.GetLogger( + MethodBase.GetCurrentMethod().DeclaringType); + + private string m_ServerURI = String.Empty; + + public GridUserServicesConnector() { } + + public GridUserServicesConnector(string serverURI) + { + m_ServerURI = serverURI.TrimEnd('/'); + } + + public GridUserServicesConnector(IConfigSource source) + { + Initialise(source); + } + + public virtual void Initialise(IConfigSource source) + { + IConfig gridConfig = source.Configs["GridUserService"]; + if (gridConfig == null) + { + m_log.Error("[GRID USER CONNECTOR]: GridUserService missing from OpenSim.ini"); + throw new Exception("GridUser connector init error"); + } + + string serviceURI = gridConfig.GetString("GridUserServerURI", + String.Empty); + + if (serviceURI == String.Empty) + { + m_log.Error("[GRID USER CONNECTOR]: No Server URI named in section GridUserService"); + throw new Exception("GridUser connector init error"); + } + m_ServerURI = serviceURI; + } + + + #region IGridUserService + + + public GridUserInfo LoggedIn(string userID) + { + Dictionary sendData = new Dictionary(); + //sendData["SCOPEID"] = scopeID.ToString(); + sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); + sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); + sendData["METHOD"] = "loggedin"; + + sendData["UserID"] = userID; + + return Get(sendData); + + } + + public bool LoggedOut(string userID, UUID region, Vector3 position, Vector3 lookat) + { + Dictionary sendData = new Dictionary(); + //sendData["SCOPEID"] = scopeID.ToString(); + sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); + sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); + sendData["METHOD"] = "loggedout"; + + return Set(sendData, userID, region, position, lookat); + } + + public bool SetHome(string userID, UUID regionID, Vector3 position, Vector3 lookAt) + { + Dictionary sendData = new Dictionary(); + //sendData["SCOPEID"] = scopeID.ToString(); + sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); + sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); + sendData["METHOD"] = "sethome"; + + return Set(sendData, userID, regionID, position, lookAt); + } + + public bool SetLastPosition(string userID, UUID regionID, Vector3 position, Vector3 lookAt) + { + Dictionary sendData = new Dictionary(); + //sendData["SCOPEID"] = scopeID.ToString(); + sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); + sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); + sendData["METHOD"] = "setposition"; + + return Set(sendData, userID, regionID, position, lookAt); + } + + public GridUserInfo GetGridUserInfo(string userID) + { + Dictionary sendData = new Dictionary(); + //sendData["SCOPEID"] = scopeID.ToString(); + sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); + sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); + sendData["METHOD"] = "getgriduserinfo"; + + sendData["UserID"] = userID; + + return Get(sendData); + } + + #endregion + + protected bool Set(Dictionary sendData, string userID, UUID regionID, Vector3 position, Vector3 lookAt) + { + sendData["UserID"] = userID; + sendData["RegionID"] = regionID.ToString(); + sendData["Position"] = position.ToString(); + sendData["LookAt"] = lookAt.ToString(); + + string reqString = ServerUtils.BuildQueryString(sendData); + // m_log.DebugFormat("[GRID USER CONNECTOR]: queryString = {0}", reqString); + try + { + string reply = SynchronousRestFormsRequester.MakeRequest("POST", + m_ServerURI + "/griduser", + reqString); + if (reply != string.Empty) + { + Dictionary replyData = ServerUtils.ParseXmlResponse(reply); + + if (replyData.ContainsKey("result")) + { + if (replyData["result"].ToString().ToLower() == "success") + return true; + else + return false; + } + else + m_log.DebugFormat("[GRID USER CONNECTOR]: SetPosition reply data does not contain result field"); + + } + else + m_log.DebugFormat("[GRID USER CONNECTOR]: SetPosition received empty reply"); + } + catch (Exception e) + { + m_log.DebugFormat("[GRID USER CONNECTOR]: Exception when contacting grid user server: {0}", e.Message); + } + + return false; + } + + protected GridUserInfo Get(Dictionary sendData) + { + string reqString = ServerUtils.BuildQueryString(sendData); + // m_log.DebugFormat("[GRID USER CONNECTOR]: queryString = {0}", reqString); + try + { + string reply = SynchronousRestFormsRequester.MakeRequest("POST", + m_ServerURI + "/griduser", + reqString); + if (reply != string.Empty) + { + Dictionary replyData = ServerUtils.ParseXmlResponse(reply); + GridUserInfo guinfo = null; + + if ((replyData != null) && replyData.ContainsKey("result") && (replyData["result"] != null)) + { + if (replyData["result"] is Dictionary) + { + guinfo = new GridUserInfo((Dictionary)replyData["result"]); + } + } + + return guinfo; + + } + else + m_log.DebugFormat("[GRID USER CONNECTOR]: Loggedin received empty reply"); + } + catch (Exception e) + { + m_log.DebugFormat("[GRID USER CONNECTOR]: Exception when contacting grid user server: {0}", e.Message); + } + + return null; + + } + } } diff --git a/OpenSim/Services/Connectors/Hypergrid/UserAgentServiceConnector.cs b/OpenSim/Services/Connectors/Hypergrid/UserAgentServiceConnector.cs index 3e91e3a113..42eca05ec5 100644 --- a/OpenSim/Services/Connectors/Hypergrid/UserAgentServiceConnector.cs +++ b/OpenSim/Services/Connectors/Hypergrid/UserAgentServiceConnector.cs @@ -204,6 +204,11 @@ namespace OpenSim.Services.Connectors.Hypergrid return args; } + public void SetClientToken(UUID sessionID, string token) + { + // no-op + } + public GridRegion GetHomeRegion(UUID userID, out Vector3 position, out Vector3 lookAt) { position = Vector3.UnitY; lookAt = Vector3.UnitY; diff --git a/OpenSim/Services/Connectors/Inventory/XInventoryConnector.cs b/OpenSim/Services/Connectors/Inventory/XInventoryConnector.cs index 0cc1978a0b..e25e7ebd3c 100644 --- a/OpenSim/Services/Connectors/Inventory/XInventoryConnector.cs +++ b/OpenSim/Services/Connectors/Inventory/XInventoryConnector.cs @@ -112,8 +112,15 @@ namespace OpenSim.Services.Connectors List folders = new List(); - foreach (Object o in ret.Values) - folders.Add(BuildFolder((Dictionary)o)); + try + { + foreach (Object o in ret.Values) + folders.Add(BuildFolder((Dictionary)o)); + } + catch (Exception e) + { + m_log.DebugFormat("[XINVENTORY CONNECTOR STUB]: Exception unwrapping folder list: {0}", e.Message); + } return folders; } @@ -130,7 +137,7 @@ namespace OpenSim.Services.Connectors if (ret.Count == 0) return null; - return BuildFolder(ret); + return BuildFolder((Dictionary)ret["folder"]); } public InventoryFolderBase GetFolderForType(UUID principalID, AssetType type) @@ -146,37 +153,45 @@ namespace OpenSim.Services.Connectors if (ret.Count == 0) return null; - return BuildFolder(ret); + return BuildFolder((Dictionary)ret["folder"]); } public InventoryCollection GetFolderContent(UUID principalID, UUID folderID) { - Dictionary ret = MakeRequest("GETFOLDERCONTENT", - new Dictionary { - { "PRINCIPAL", principalID.ToString() }, - { "FOLDER", folderID.ToString() } - }); - - if (ret == null) - return null; - if (ret.Count == 0) - return null; - - InventoryCollection inventory = new InventoryCollection(); - inventory.Folders = new List(); - inventory.Items = new List(); - inventory.UserID = principalID; - Dictionary folders = - (Dictionary)ret["FOLDERS"]; - Dictionary items = - (Dictionary)ret["ITEMS"]; + try + { + Dictionary ret = MakeRequest("GETFOLDERCONTENT", + new Dictionary { + { "PRINCIPAL", principalID.ToString() }, + { "FOLDER", folderID.ToString() } + }); - foreach (Object o in folders.Values) - inventory.Folders.Add(BuildFolder((Dictionary)o)); - foreach (Object o in items.Values) - inventory.Items.Add(BuildItem((Dictionary)o)); + if (ret == null) + return null; + if (ret.Count == 0) + return null; + + + inventory.Folders = new List(); + inventory.Items = new List(); + inventory.UserID = principalID; + + Dictionary folders = + (Dictionary)ret["FOLDERS"]; + Dictionary items = + (Dictionary)ret["ITEMS"]; + + foreach (Object o in folders.Values) // getting the values directly, we don't care about the keys folder_i + inventory.Folders.Add(BuildFolder((Dictionary)o)); + foreach (Object o in items.Values) // getting the values directly, we don't care about the keys item_i + inventory.Items.Add(BuildItem((Dictionary)o)); + } + catch (Exception e) + { + m_log.DebugFormat("[XINVENTORY CONNECTOR STUB]: Exception in GetFolderContent: {0}", e.Message); + } return inventory; } @@ -194,13 +209,12 @@ namespace OpenSim.Services.Connectors if (ret.Count == 0) return null; - - List items = new List(); - - foreach (Object o in ret.Values) - items.Add(BuildItem((Dictionary)o)); + Dictionary items = (Dictionary)ret["ITEMS"]; + List fitems = new List(); + foreach (Object o in items.Values) // getting the values directly, we don't care about the keys item_i + fitems.Add(BuildItem((Dictionary)o)); - return items; + return fitems; } public bool AddFolder(InventoryFolderBase folder) @@ -395,32 +409,50 @@ namespace OpenSim.Services.Connectors public InventoryItemBase GetItem(InventoryItemBase item) { - Dictionary ret = MakeRequest("GETITEM", - new Dictionary { + try + { + Dictionary ret = MakeRequest("GETITEM", + new Dictionary { { "ID", item.ID.ToString() } }); - if (ret == null) - return null; - if (ret.Count == 0) - return null; + if (ret == null) + return null; + if (ret.Count == 0) + return null; - return BuildItem(ret); + return BuildItem((Dictionary)ret["item"]); + } + catch (Exception e) + { + m_log.DebugFormat("[XINVENTORY CONNECTOR STUB]: Exception in GetItem: {0}", e.Message); + } + + return null; } public InventoryFolderBase GetFolder(InventoryFolderBase folder) { - Dictionary ret = MakeRequest("GETFOLDER", - new Dictionary { + try + { + Dictionary ret = MakeRequest("GETFOLDER", + new Dictionary { { "ID", folder.ID.ToString() } }); - if (ret == null) - return null; - if (ret.Count == 0) - return null; + if (ret == null) + return null; + if (ret.Count == 0) + return null; - return BuildFolder(ret); + return BuildFolder((Dictionary)ret["folder"]); + } + catch (Exception e) + { + m_log.DebugFormat("[XINVENTORY CONNECTOR STUB]: Exception in GetFolder: {0}", e.Message); + } + + return null; } public List GetActiveGestures(UUID principalID) @@ -435,8 +467,8 @@ namespace OpenSim.Services.Connectors List items = new List(); - foreach (Object o in ret.Values) - items.Add(BuildItem((Dictionary)o)); + foreach (Object o in ret.Values) // getting the values directly, we don't care about the keys item_i + items.Add(BuildItem((Dictionary)o)); return items; } @@ -493,13 +525,20 @@ namespace OpenSim.Services.Connectors { InventoryFolderBase folder = new InventoryFolderBase(); - folder.ParentID = new UUID(data["ParentID"].ToString()); - folder.Type = short.Parse(data["Type"].ToString()); - folder.Version = ushort.Parse(data["Version"].ToString()); - folder.Name = data["Name"].ToString(); - folder.Owner = new UUID(data["Owner"].ToString()); - folder.ID = new UUID(data["ID"].ToString()); - + try + { + folder.ParentID = new UUID(data["ParentID"].ToString()); + folder.Type = short.Parse(data["Type"].ToString()); + folder.Version = ushort.Parse(data["Version"].ToString()); + folder.Name = data["Name"].ToString(); + folder.Owner = new UUID(data["Owner"].ToString()); + folder.ID = new UUID(data["ID"].ToString()); + } + catch (Exception e) + { + m_log.DebugFormat("[XINVENTORY CONNECTOR STUB]: Exception building folder: {0}", e.Message); + } + return folder; } @@ -507,26 +546,33 @@ namespace OpenSim.Services.Connectors { InventoryItemBase item = new InventoryItemBase(); - item.AssetID = new UUID(data["AssetID"].ToString()); - item.AssetType = int.Parse(data["AssetType"].ToString()); - item.Name = data["Name"].ToString(); - item.Owner = new UUID(data["Owner"].ToString()); - item.ID = new UUID(data["ID"].ToString()); - item.InvType = int.Parse(data["InvType"].ToString()); - item.Folder = new UUID(data["Folder"].ToString()); - item.CreatorId = data["CreatorId"].ToString(); - item.Description = data["Description"].ToString(); - item.NextPermissions = uint.Parse(data["NextPermissions"].ToString()); - item.CurrentPermissions = uint.Parse(data["CurrentPermissions"].ToString()); - item.BasePermissions = uint.Parse(data["BasePermissions"].ToString()); - item.EveryOnePermissions = uint.Parse(data["EveryOnePermissions"].ToString()); - item.GroupPermissions = uint.Parse(data["GroupPermissions"].ToString()); - item.GroupID = new UUID(data["GroupID"].ToString()); - item.GroupOwned = bool.Parse(data["GroupOwned"].ToString()); - item.SalePrice = int.Parse(data["SalePrice"].ToString()); - item.SaleType = byte.Parse(data["SaleType"].ToString()); - item.Flags = uint.Parse(data["Flags"].ToString()); - item.CreationDate = int.Parse(data["CreationDate"].ToString()); + try + { + item.AssetID = new UUID(data["AssetID"].ToString()); + item.AssetType = int.Parse(data["AssetType"].ToString()); + item.Name = data["Name"].ToString(); + item.Owner = new UUID(data["Owner"].ToString()); + item.ID = new UUID(data["ID"].ToString()); + item.InvType = int.Parse(data["InvType"].ToString()); + item.Folder = new UUID(data["Folder"].ToString()); + item.CreatorId = data["CreatorId"].ToString(); + item.Description = data["Description"].ToString(); + item.NextPermissions = uint.Parse(data["NextPermissions"].ToString()); + item.CurrentPermissions = uint.Parse(data["CurrentPermissions"].ToString()); + item.BasePermissions = uint.Parse(data["BasePermissions"].ToString()); + item.EveryOnePermissions = uint.Parse(data["EveryOnePermissions"].ToString()); + item.GroupPermissions = uint.Parse(data["GroupPermissions"].ToString()); + item.GroupID = new UUID(data["GroupID"].ToString()); + item.GroupOwned = bool.Parse(data["GroupOwned"].ToString()); + item.SalePrice = int.Parse(data["SalePrice"].ToString()); + item.SaleType = byte.Parse(data["SaleType"].ToString()); + item.Flags = uint.Parse(data["Flags"].ToString()); + item.CreationDate = int.Parse(data["CreationDate"].ToString()); + } + catch (Exception e) + { + m_log.DebugFormat("[XINVENTORY CONNECTOR STUB]: Exception building item: {0}", e.Message); + } return item; } diff --git a/OpenSim/Services/Connectors/Presence/PresenceServiceConnector.cs b/OpenSim/Services/Connectors/Presence/PresenceServiceConnector.cs index 4dadd9ebb7..41ebeaf05e 100644 --- a/OpenSim/Services/Connectors/Presence/PresenceServiceConnector.cs +++ b/OpenSim/Services/Connectors/Presence/PresenceServiceConnector.cs @@ -132,7 +132,7 @@ namespace OpenSim.Services.Connectors } - public bool LogoutAgent(UUID sessionID, Vector3 position, Vector3 lookat) + public bool LogoutAgent(UUID sessionID) { Dictionary sendData = new Dictionary(); //sendData["SCOPEID"] = scopeID.ToString(); @@ -141,8 +141,6 @@ namespace OpenSim.Services.Connectors sendData["METHOD"] = "logout"; sendData["SessionID"] = sessionID.ToString(); - sendData["Position"] = position.ToString(); - sendData["LookAt"] = lookat.ToString(); string reqString = ServerUtils.BuildQueryString(sendData); // m_log.DebugFormat("[PRESENCE CONNECTOR]: queryString = {0}", reqString); @@ -220,7 +218,7 @@ namespace OpenSim.Services.Connectors return false; } - public bool ReportAgent(UUID sessionID, UUID regionID, Vector3 position, Vector3 lookAt) + public bool ReportAgent(UUID sessionID, UUID regionID) { Dictionary sendData = new Dictionary(); //sendData["SCOPEID"] = scopeID.ToString(); @@ -230,8 +228,6 @@ namespace OpenSim.Services.Connectors sendData["SessionID"] = sessionID.ToString(); sendData["RegionID"] = regionID.ToString(); - sendData["position"] = position.ToString(); - sendData["lookAt"] = lookAt.ToString(); string reqString = ServerUtils.BuildQueryString(sendData); // m_log.DebugFormat("[PRESENCE CONNECTOR]: queryString = {0}", reqString); @@ -329,7 +325,7 @@ namespace OpenSim.Services.Connectors reqString); if (reply == null || (reply != null && reply == string.Empty)) { - m_log.DebugFormat("[PRESENCE CONNECTOR]: GetAgent received null or empty reply"); + m_log.DebugFormat("[PRESENCE CONNECTOR]: GetAgents received null or empty reply"); return null; } } @@ -371,52 +367,6 @@ namespace OpenSim.Services.Connectors } - public bool SetHomeLocation(string userID, UUID regionID, Vector3 position, Vector3 lookAt) - { - Dictionary sendData = new Dictionary(); - //sendData["SCOPEID"] = scopeID.ToString(); - sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); - sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); - sendData["METHOD"] = "sethome"; - - sendData["UserID"] = userID; - sendData["RegionID"] = regionID.ToString(); - sendData["position"] = position.ToString(); - sendData["lookAt"] = lookAt.ToString(); - - string reqString = ServerUtils.BuildQueryString(sendData); - // m_log.DebugFormat("[PRESENCE CONNECTOR]: queryString = {0}", reqString); - try - { - string reply = SynchronousRestFormsRequester.MakeRequest("POST", - m_ServerURI + "/presence", - reqString); - if (reply != string.Empty) - { - Dictionary replyData = ServerUtils.ParseXmlResponse(reply); - - if (replyData.ContainsKey("result")) - { - if (replyData["result"].ToString().ToLower() == "success") - return true; - else - return false; - } - else - m_log.DebugFormat("[PRESENCE CONNECTOR]: SetHomeLocation reply data does not contain result field"); - - } - else - m_log.DebugFormat("[PRESENCE CONNECTOR]: SetHomeLocation received empty reply"); - } - catch (Exception e) - { - m_log.DebugFormat("[PRESENCE CONNECTOR]: Exception when contacting presence server: {0}", e.Message); - } - - return false; - } - #endregion } diff --git a/OpenSim/Services/Connectors/SimianGrid/SimianActivityDetector.cs b/OpenSim/Services/Connectors/SimianGrid/SimianActivityDetector.cs new file mode 100644 index 0000000000..a871d07f16 --- /dev/null +++ b/OpenSim/Services/Connectors/SimianGrid/SimianActivityDetector.cs @@ -0,0 +1,113 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; +using System.Reflection; +using OpenSim.Framework; +using OpenSim.Region.Framework.Scenes; +using OpenSim.Services.Interfaces; +using OpenMetaverse; +using log4net; + +namespace OpenSim.Services.Connectors.SimianGrid +{ + public class SimianActivityDetector + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private SimianPresenceServiceConnector m_GridUserService; + private Scene m_aScene; + + public SimianActivityDetector(SimianPresenceServiceConnector guservice) + { + m_GridUserService = guservice; + m_log.DebugFormat("[SIMIAN ACTIVITY DETECTOR]: Started"); + } + + public void AddRegion(Scene scene) + { + // For now the only events we listen to are these + // But we could trigger the position update more often + scene.EventManager.OnMakeRootAgent += OnMakeRootAgent; + scene.EventManager.OnNewClient += OnNewClient; + scene.EventManager.OnAvatarEnteringNewParcel += OnEnteringNewParcel; + + if (m_aScene == null) + m_aScene = scene; + } + + public void RemoveRegion(Scene scene) + { + scene.EventManager.OnMakeRootAgent -= OnMakeRootAgent; + scene.EventManager.OnNewClient -= OnNewClient; + scene.EventManager.OnAvatarEnteringNewParcel -= OnEnteringNewParcel; + } + + public void OnMakeRootAgent(ScenePresence sp) + { + m_log.DebugFormat("[SIMIAN ACTIVITY DETECTOR]: Detected root presence {0} in {1}", sp.UUID, sp.Scene.RegionInfo.RegionName); + m_GridUserService.SetLastPosition(sp.UUID.ToString(), sp.ControllingClient.SessionId, sp.Scene.RegionInfo.RegionID, sp.AbsolutePosition, sp.Lookat); + } + + public void OnNewClient(IClientAPI client) + { + client.OnConnectionClosed += OnConnectionClose; + } + + public void OnConnectionClose(IClientAPI client) + { + if (client.IsLoggingOut) + { + object sp = null; + Vector3 position = new Vector3(128, 128, 0); + Vector3 lookat = new Vector3(0, 1, 0); + + if (client.Scene.TryGetScenePresence(client.AgentId, out sp)) + { + if (sp is ScenePresence) + { + if (((ScenePresence)sp).IsChildAgent) + return; + + position = ((ScenePresence)sp).AbsolutePosition; + lookat = ((ScenePresence)sp).Lookat; + } + } + + m_log.DebugFormat("[SIMIAN ACTIVITY DETECTOR]: Detected client logout {0} in {1}", client.AgentId, client.Scene.RegionInfo.RegionName); + m_GridUserService.LoggedOut(client.AgentId.ToString(), client.Scene.RegionInfo.RegionID, position, lookat); + } + + } + + void OnEnteringNewParcel(ScenePresence sp, int localLandID, UUID regionID) + { + m_GridUserService.SetLastPosition(sp.UUID.ToString(), sp.ControllingClient.SessionId, sp.Scene.RegionInfo.RegionID, sp.AbsolutePosition, sp.Lookat); + } + } +} diff --git a/OpenSim/Services/Connectors/SimianGrid/SimianAssetServiceConnector.cs b/OpenSim/Services/Connectors/SimianGrid/SimianAssetServiceConnector.cs index 9acbd9a750..83f93aa1df 100644 --- a/OpenSim/Services/Connectors/SimianGrid/SimianAssetServiceConnector.cs +++ b/OpenSim/Services/Connectors/SimianGrid/SimianAssetServiceConnector.cs @@ -303,9 +303,11 @@ namespace OpenSim.Services.Connectors.SimianGrid HttpWebResponse response = MultipartForm.Post(request, postParameters); using (Stream responseStream = response.GetResponseStream()) { + string responseStr = null; + try { - string responseStr = responseStream.GetStreamString(); + responseStr = responseStream.GetStreamString(); OSD responseOSD = OSDParser.Deserialize(responseStr); if (responseOSD.Type == OSDType.Map) { @@ -317,12 +319,15 @@ namespace OpenSim.Services.Connectors.SimianGrid } else { - errorMessage = "Response format was invalid."; + errorMessage = "Response format was invalid:\n" + responseStr; } } - catch + catch (Exception ex) { - errorMessage = "Failed to parse the response."; + if (!String.IsNullOrEmpty(responseStr)) + errorMessage = "Failed to parse the response:\n" + responseStr; + else + errorMessage = "Failed to retrieve the response: " + ex.Message; } } } diff --git a/OpenSim/Services/Connectors/SimianGrid/SimianAuthenticationServiceConnector.cs b/OpenSim/Services/Connectors/SimianGrid/SimianAuthenticationServiceConnector.cs index b19135e0c5..de3ee4ea56 100644 --- a/OpenSim/Services/Connectors/SimianGrid/SimianAuthenticationServiceConnector.cs +++ b/OpenSim/Services/Connectors/SimianGrid/SimianAuthenticationServiceConnector.cs @@ -116,7 +116,7 @@ namespace OpenSim.Services.Connectors.SimianGrid { string credential = identity["Credential"].AsString(); - if (password == credential || "$1$" + Utils.MD5String(password) == credential || Utils.MD5String(password) == credential) + if (password == credential || "$1$" + password == credential || "$1$" + Utils.MD5String(password) == credential || Utils.MD5String(password) == credential) return Authorize(principalID); md5hashFound = true; diff --git a/OpenSim/Services/Connectors/SimianGrid/SimianPresenceServiceConnector.cs b/OpenSim/Services/Connectors/SimianGrid/SimianPresenceServiceConnector.cs index c324272093..6f179317d2 100644 --- a/OpenSim/Services/Connectors/SimianGrid/SimianPresenceServiceConnector.cs +++ b/OpenSim/Services/Connectors/SimianGrid/SimianPresenceServiceConnector.cs @@ -51,13 +51,14 @@ namespace OpenSim.Services.Connectors.SimianGrid /// message routing) to the SimianGrid backend /// [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")] - public class SimianPresenceServiceConnector : IPresenceService, ISharedRegionModule + public class SimianPresenceServiceConnector : IPresenceService, IGridUserService, ISharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private string m_serverUrl = String.Empty; + private SimianActivityDetector m_activityDetector; #region ISharedRegionModule @@ -66,17 +67,16 @@ namespace OpenSim.Services.Connectors.SimianGrid public void PostInitialise() { } public void Close() { } - public SimianPresenceServiceConnector() { } + public SimianPresenceServiceConnector() { m_activityDetector = new SimianActivityDetector(this); } public string Name { get { return "SimianPresenceServiceConnector"; } } public void AddRegion(Scene scene) { if (!String.IsNullOrEmpty(m_serverUrl)) { scene.RegisterModuleInterface(this); + scene.RegisterModuleInterface(this); - scene.EventManager.OnMakeRootAgent += MakeRootAgentHandler; - scene.EventManager.OnNewClient += NewClientHandler; - scene.EventManager.OnSignificantClientMovement += SignificantClientMovementHandler; + m_activityDetector.AddRegion(scene); LogoutRegionAgents(scene.RegionInfo.RegionID); } @@ -86,10 +86,9 @@ namespace OpenSim.Services.Connectors.SimianGrid if (!String.IsNullOrEmpty(m_serverUrl)) { scene.UnregisterModuleInterface(this); + scene.UnregisterModuleInterface(this); - scene.EventManager.OnMakeRootAgent -= MakeRootAgentHandler; - scene.EventManager.OnNewClient -= NewClientHandler; - scene.EventManager.OnSignificantClientMovement -= SignificantClientMovementHandler; + m_activityDetector.RemoveRegion(scene); LogoutRegionAgents(scene.RegionInfo.RegionID); } @@ -151,7 +150,7 @@ namespace OpenSim.Services.Connectors.SimianGrid return success; } - public bool LogoutAgent(UUID sessionID, Vector3 position, Vector3 lookAt) + public bool LogoutAgent(UUID sessionID) { m_log.InfoFormat("[SIMIAN PRESENCE CONNECTOR]: Logout requested for agent with sessionID " + sessionID); @@ -189,26 +188,10 @@ namespace OpenSim.Services.Connectors.SimianGrid return success; } - public bool ReportAgent(UUID sessionID, UUID regionID, Vector3 position, Vector3 lookAt) + public bool ReportAgent(UUID sessionID, UUID regionID) { - //m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Updating session data for agent with sessionID " + sessionID); - - NameValueCollection requestArgs = new NameValueCollection - { - { "RequestMethod", "UpdateSession" }, - { "SessionID", sessionID.ToString() }, - { "SceneID", regionID.ToString() }, - { "ScenePosition", position.ToString() }, - { "SceneLookAt", lookAt.ToString() } - }; - - OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs); - bool success = response["Success"].AsBoolean(); - - if (!success) - m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to update agent session " + sessionID + ": " + response["Message"].AsString()); - - return success; + // Not needed for SimianGrid + return true; } public PresenceInfo GetAgent(UUID sessionID) @@ -261,7 +244,36 @@ namespace OpenSim.Services.Connectors.SimianGrid return presences.ToArray(); } - public bool SetHomeLocation(string userID, UUID regionID, Vector3 position, Vector3 lookAt) + #endregion IPresenceService + + #region IGridUserService + + public GridUserInfo LoggedIn(string userID) + { + // Never implemented at the sim + return null; + } + + public bool LoggedOut(string userID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt) + { + // Save our last position as user data + NameValueCollection requestArgs = new NameValueCollection + { + { "RequestMethod", "AddUserData" }, + { "UserID", userID.ToString() }, + { "LastLocation", SerializeLocation(regionID, lastPosition, lastLookAt) } + }; + + OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs); + bool success = response["Success"].AsBoolean(); + + if (!success) + m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to set last location for " + userID + ": " + response["Message"].AsString()); + + return success; + } + + public bool SetHome(string userID, UUID regionID, Vector3 position, Vector3 lookAt) { m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Setting home location for user " + userID); @@ -281,55 +293,40 @@ namespace OpenSim.Services.Connectors.SimianGrid return success; } - #endregion IPresenceService - - #region Presence Detection - - private void MakeRootAgentHandler(ScenePresence sp) + public bool SetLastPosition(string userID, UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt) { - m_log.DebugFormat("[PRESENCE DETECTOR]: Detected root presence {0} in {1}", sp.UUID, sp.Scene.RegionInfo.RegionName); - - ReportAgent(sp.ControllingClient.SessionId, sp.Scene.RegionInfo.RegionID, sp.AbsolutePosition, sp.Lookat); - SetLastLocation(sp.UUID, sp.Scene.RegionInfo.RegionID, sp.AbsolutePosition, sp.Lookat); + return UpdateSession(sessionID, regionID, lastPosition, lastLookAt); } - private void NewClientHandler(IClientAPI client) + public bool SetLastPosition(string userID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt) { - client.OnConnectionClosed += LogoutHandler; + // Never called + return false; } - private void SignificantClientMovementHandler(IClientAPI client) + public GridUserInfo GetGridUserInfo(string user) { - ScenePresence sp; - if (client.Scene is Scene && ((Scene)client.Scene).TryGetScenePresence(client.AgentId, out sp)) - ReportAgent(sp.ControllingClient.SessionId, sp.Scene.RegionInfo.RegionID, sp.AbsolutePosition, sp.Lookat); - } + m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting session data for agent " + user); - private void LogoutHandler(IClientAPI client) - { - if (client.IsLoggingOut) + UUID userID = new UUID(user); + m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting user data for " + userID); + + NameValueCollection requestArgs = new NameValueCollection { - client.OnConnectionClosed -= LogoutHandler; + { "RequestMethod", "GetUser" }, + { "UserID", userID.ToString() } + }; - object obj; - if (client.Scene.TryGetScenePresence(client.AgentId, out obj) && obj is ScenePresence) - { - // The avatar is still in the scene, we can get the exact logout position - ScenePresence sp = (ScenePresence)obj; - SetLastLocation(client.AgentId, client.Scene.RegionInfo.RegionID, sp.AbsolutePosition, sp.Lookat); - } - else - { - // The avatar was already removed from the scene, store LastLocation using the most recent session data - m_log.Warn("[PRESENCE]: " + client.Name + " has already been removed from the scene, storing approximate LastLocation"); - SetLastLocation(client.SessionId); - } + OSDMap userResponse = WebUtil.PostToService(m_serverUrl, requestArgs); + if (userResponse["Success"].AsBoolean()) + return ResponseToGridUserInfo(userResponse); + else + m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve user data for " + userID + ": " + userResponse["Message"].AsString()); - LogoutAgent(client.SessionId, Vector3.Zero, Vector3.UnitX); - } + return null; } - #endregion Presence Detection + #endregion #region Helpers @@ -402,57 +399,60 @@ namespace OpenSim.Services.Connectors.SimianGrid return presences; } - /// - /// Fetch the last known avatar location with GetSession and persist it - /// as user data with AddUserData - /// - private bool SetLastLocation(UUID sessionID) + private bool UpdateSession(UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt) { + // Save our current location as session data NameValueCollection requestArgs = new NameValueCollection { - { "RequestMethod", "GetSession" }, - { "SessionID", sessionID.ToString() } + { "RequestMethod", "UpdateSession" }, + { "SessionID", sessionID.ToString() }, + { "SceneID", regionID.ToString() }, + { "ScenePosition", lastPosition.ToString() }, + { "SceneLookAt", lastLookAt.ToString() } }; OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs); bool success = response["Success"].AsBoolean(); - if (success) - { - UUID userID = response["UserID"].AsUUID(); - UUID sceneID = response["SceneID"].AsUUID(); - Vector3 position = response["ScenePosition"].AsVector3(); - Vector3 lookAt = response["SceneLookAt"].AsVector3(); - - return SetLastLocation(userID, sceneID, position, lookAt); - } - else - { - m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve presence information for session " + sessionID + - " while saving last location: " + response["Message"].AsString()); - } - - return success; - } - - private bool SetLastLocation(UUID userID, UUID sceneID, Vector3 position, Vector3 lookAt) - { - NameValueCollection requestArgs = new NameValueCollection - { - { "RequestMethod", "AddUserData" }, - { "UserID", userID.ToString() }, - { "LastLocation", SerializeLocation(sceneID, position, lookAt) } - }; - - OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs); - bool success = response["Success"].AsBoolean(); - if (!success) - m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to set last location for " + userID + ": " + response["Message"].AsString()); + m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to update agent session " + sessionID + ": " + response["Message"].AsString()); return success; } + ///// + ///// Fetch the last known avatar location with GetSession and persist it + ///// as user data with AddUserData + ///// + //private bool SetLastLocation(UUID sessionID) + //{ + // NameValueCollection requestArgs = new NameValueCollection + // { + // { "RequestMethod", "GetSession" }, + // { "SessionID", sessionID.ToString() } + // }; + + // OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs); + // bool success = response["Success"].AsBoolean(); + + // if (success) + // { + // UUID userID = response["UserID"].AsUUID(); + // UUID sceneID = response["SceneID"].AsUUID(); + // Vector3 position = response["ScenePosition"].AsVector3(); + // Vector3 lookAt = response["SceneLookAt"].AsVector3(); + + // return SetLastLocation(userID, sceneID, position, lookAt); + // } + // else + // { + // m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve presence information for session " + sessionID + + // " while saving last location: " + response["Message"].AsString()); + // } + + // return success; + //} + private PresenceInfo ResponseToPresenceInfo(OSDMap sessionResponse, OSDMap userResponse) { if (sessionResponse == null) @@ -460,24 +460,37 @@ namespace OpenSim.Services.Connectors.SimianGrid PresenceInfo info = new PresenceInfo(); - info.Online = true; info.UserID = sessionResponse["UserID"].AsUUID().ToString(); info.RegionID = sessionResponse["SceneID"].AsUUID(); - info.Position = sessionResponse["ScenePosition"].AsVector3(); - info.LookAt = sessionResponse["SceneLookAt"].AsVector3(); + return info; + } + + private GridUserInfo ResponseToGridUserInfo(OSDMap userResponse) + { if (userResponse != null && userResponse["User"] is OSDMap) { + + GridUserInfo info = new GridUserInfo(); + + info.Online = true; + info.UserID = userResponse["UserID"].AsUUID().ToString(); + info.LastRegionID = userResponse["SceneID"].AsUUID(); + info.LastPosition = userResponse["ScenePosition"].AsVector3(); + info.LastLookAt = userResponse["SceneLookAt"].AsVector3(); + OSDMap user = (OSDMap)userResponse["User"]; info.Login = user["LastLoginDate"].AsDate(); info.Logout = user["LastLogoutDate"].AsDate(); DeserializeLocation(user["HomeLocation"].AsString(), out info.HomeRegionID, out info.HomePosition, out info.HomeLookAt); + + return info; } - return info; + return null; } - + private string SerializeLocation(UUID regionID, Vector3 position, Vector3 lookAt) { return "{" + String.Format("\"SceneID\":\"{0}\",\"Position\":\"{1}\",\"LookAt\":\"{2}\"", regionID, position, lookAt) + "}"; diff --git a/OpenSim/Services/Connectors/UserAccounts/UserAccountServiceConnector.cs b/OpenSim/Services/Connectors/UserAccounts/UserAccountServiceConnector.cs index 1527db20df..38c191a913 100644 --- a/OpenSim/Services/Connectors/UserAccounts/UserAccountServiceConnector.cs +++ b/OpenSim/Services/Connectors/UserAccounts/UserAccountServiceConnector.cs @@ -113,7 +113,7 @@ namespace OpenSim.Services.Connectors public virtual UserAccount GetUserAccount(UUID scopeID, UUID userID) { - m_log.DebugFormat("[ACCOUNTS CONNECTOR]: GetUSerAccount {0}", userID); + m_log.DebugFormat("[ACCOUNTS CONNECTOR]: GetUserAccount {0}", userID); Dictionary sendData = new Dictionary(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); diff --git a/OpenSim/Services/GridService/GridService.cs b/OpenSim/Services/GridService/GridService.cs index 2faf018e72..7c9864270c 100644 --- a/OpenSim/Services/GridService/GridService.cs +++ b/OpenSim/Services/GridService/GridService.cs @@ -315,6 +315,8 @@ namespace OpenSim.Services.GridService public List GetRegionsByName(UUID scopeID, string name, int maxNumber) { + m_log.DebugFormat("[GRID SERVICE]: GetRegionsByName {0}", name); + List rdatas = m_Database.Get("%" + name + "%", scopeID); int count = 0; @@ -322,6 +324,7 @@ namespace OpenSim.Services.GridService if (rdatas != null) { + m_log.DebugFormat("[GRID SERVICE]: Found {0} regions", rdatas.Count); foreach (RegionData rdata in rdatas) { if (count++ < maxNumber) @@ -329,7 +332,7 @@ namespace OpenSim.Services.GridService } } - if (m_AllowHypergridMapSearch && rdatas == null || (rdatas != null && rdatas.Count == 0) && name.Contains(".")) + if (m_AllowHypergridMapSearch && (rdatas == null || (rdatas != null && rdatas.Count == 0)) && name.Contains(".")) { GridRegion r = m_HypergridLinker.LinkRegion(scopeID, name); if (r != null) @@ -397,6 +400,7 @@ namespace OpenSim.Services.GridService ret.Add(RegionData2RegionInfo(r)); } + m_log.DebugFormat("[GRID SERVICE]: GetDefaultRegions returning {0} regions", ret.Count); return ret; } diff --git a/OpenSim/Services/GridService/HypergridLinker.cs b/OpenSim/Services/GridService/HypergridLinker.cs index 58746d0a1b..af603b23e2 100644 --- a/OpenSim/Services/GridService/HypergridLinker.cs +++ b/OpenSim/Services/GridService/HypergridLinker.cs @@ -79,9 +79,16 @@ namespace OpenSim.Services.GridService m_DefaultRegion = defs[0]; else { - // Best guess, may be totally off - m_DefaultRegion = new GridRegion(1000, 1000); - m_log.WarnFormat("[HYPERGRID LINKER]: This grid does not have a default region. Assuming default coordinates at 1000, 1000."); + // Get any region + defs = m_GridService.GetRegionsByName(m_ScopeID, "", 1); + if (defs != null && defs.Count > 0) + m_DefaultRegion = defs[0]; + else + { + // This shouldn't happen + m_DefaultRegion = new GridRegion(1000, 1000); + m_log.Error("[HYPERGRID LINKER]: Something is wrong with this grid. It has no regions?"); + } } } return m_DefaultRegion; @@ -90,7 +97,7 @@ namespace OpenSim.Services.GridService public HypergridLinker(IConfigSource config, GridService gridService, IRegionData db) { - m_log.DebugFormat("[HYPERGRID LINKER]: Starting..."); + m_log.DebugFormat("[HYPERGRID LINKER]: Starting with db {0}", db.GetType()); m_Database = db; m_GridService = gridService; @@ -196,7 +203,7 @@ namespace OpenSim.Services.GridService public bool TryCreateLink(UUID scopeID, int xloc, int yloc, string externalRegionName, uint externalPort, string externalHostName, out GridRegion regInfo, out string reason) { - m_log.DebugFormat("[HYPERGRID LINKER]: Link to {0}:{1}, in {2}-{3}", externalHostName, externalPort, xloc, yloc); + m_log.DebugFormat("[HYPERGRID LINKER]: Link to {0}:{1}:{2}, in {3}-{4}", externalHostName, externalPort, externalRegionName, xloc, yloc); reason = string.Empty; regInfo = new GridRegion(); @@ -280,29 +287,28 @@ namespace OpenSim.Services.GridService public bool TryUnlinkRegion(string mapName) { + m_log.DebugFormat("[HYPERGRID LINKER]: Request to unlink {0}", mapName); GridRegion regInfo = null; - if (mapName.Contains(":")) - { - string host = "127.0.0.1"; - //string portstr; - //string regionName = ""; - uint port = 9000; - string[] parts = mapName.Split(new char[] { ':' }); - if (parts.Length >= 1) - { - host = parts[0]; - } - foreach (GridRegion r in m_HyperlinkRegions.Values) - if (host.Equals(r.ExternalHostName) && (port == r.HttpPort)) - regInfo = r; - } - else + List regions = m_Database.Get(mapName, m_ScopeID); + if (regions != null && regions.Count > 0) { - foreach (GridRegion r in m_HyperlinkRegions.Values) - if (r.RegionName.Equals(mapName)) - regInfo = r; + OpenSim.Data.RegionFlags rflags = (OpenSim.Data.RegionFlags)Convert.ToInt32(regions[0].Data["flags"]); + if ((rflags & OpenSim.Data.RegionFlags.Hyperlink) != 0) + { + regInfo = new GridRegion(); + regInfo.RegionID = regions[0].RegionID; + regInfo.ScopeID = m_ScopeID; + } } + + //foreach (GridRegion r in m_HyperlinkRegions.Values) + //{ + // m_log.DebugFormat("XXX Comparing {0}:{1} with {2}:{3}", host, port, r.ExternalHostName, r.HttpPort); + // if (host.Equals(r.ExternalHostName) && (port == r.HttpPort)) + // regInfo = r; + //} + if (regInfo != null) { RemoveHyperlinkRegion(regInfo.RegionID); diff --git a/OpenSim/Services/HypergridService/GatekeeperService.cs b/OpenSim/Services/HypergridService/GatekeeperService.cs index 56744b6122..c5cfe75fdf 100644 --- a/OpenSim/Services/HypergridService/GatekeeperService.cs +++ b/OpenSim/Services/HypergridService/GatekeeperService.cs @@ -119,7 +119,8 @@ namespace OpenSim.Services.HypergridService imageURL = string.Empty; reason = string.Empty; - m_log.DebugFormat("[GATEKEEPER SERVICE]: Request to link to {0}", (regionName == string.Empty ? "default region" : regionName)); + + m_log.DebugFormat("[GATEKEEPER SERVICE]: Request to link to {0}", (regionName == string.Empty)? "default region" : regionName); if (!m_AllowTeleportsToAnyRegion || regionName == string.Empty) { List defs = m_GridService.GetDefaultRegions(m_ScopeID); diff --git a/OpenSim/Services/HypergridService/UserAgentService.cs b/OpenSim/Services/HypergridService/UserAgentService.cs index 26f211b5d9..2f1fed40db 100644 --- a/OpenSim/Services/HypergridService/UserAgentService.cs +++ b/OpenSim/Services/HypergridService/UserAgentService.cs @@ -59,7 +59,7 @@ namespace OpenSim.Services.HypergridService static bool m_Initialized = false; - protected static IPresenceService m_PresenceService; + protected static IGridUserService m_GridUserService; protected static IGridService m_GridService; protected static GatekeeperServiceConnector m_GatekeeperConnector; @@ -74,14 +74,14 @@ namespace OpenSim.Services.HypergridService throw new Exception(String.Format("No section UserAgentService in config file")); string gridService = serverConfig.GetString("GridService", String.Empty); - string presenceService = serverConfig.GetString("PresenceService", String.Empty); + string gridUserService = serverConfig.GetString("GridUserService", String.Empty); - if (gridService == string.Empty || presenceService == string.Empty) + if (gridService == string.Empty || gridUserService == string.Empty) throw new Exception(String.Format("Incomplete specifications, UserAgent Service cannot function.")); Object[] args = new Object[] { config }; m_GridService = ServerUtils.LoadPlugin(gridService, args); - m_PresenceService = ServerUtils.LoadPlugin(presenceService, args); + m_GridUserService = ServerUtils.LoadPlugin(gridUserService, args); m_GatekeeperConnector = new GatekeeperServiceConnector(); m_Initialized = true; @@ -95,15 +95,14 @@ namespace OpenSim.Services.HypergridService m_log.DebugFormat("[USER AGENT SERVICE]: Request to get home region of user {0}", userID); GridRegion home = null; - PresenceInfo[] presences = m_PresenceService.GetAgents(new string[] { userID.ToString() }); - if (presences != null && presences.Length > 0) + GridUserInfo uinfo = m_GridUserService.GetGridUserInfo(userID.ToString()); + if (uinfo != null) { - UUID homeID = presences[0].HomeRegionID; - if (homeID != UUID.Zero) + if (uinfo.HomeRegionID != UUID.Zero) { - home = m_GridService.GetRegionByUUID(UUID.Zero, homeID); - position = presences[0].HomePosition; - lookAt = presences[0].HomeLookAt; + home = m_GridService.GetRegionByUUID(UUID.Zero, uinfo.HomeRegionID); + position = uinfo.HomePosition; + lookAt = uinfo.HomeLookAt; } if (home == null) { @@ -149,6 +148,15 @@ namespace OpenSim.Services.HypergridService return true; } + public void SetClientToken(UUID sessionID, string token) + { + if (m_TravelingAgents.ContainsKey(sessionID)) + { + m_log.DebugFormat("[USER AGENT SERVICE]: Setting token {0} for session {1}", token, sessionID); + m_TravelingAgents[sessionID].ClientToken = token; + } + } + TravelingAgentInfo UpdateTravelInfo(AgentCircuitData agentCircuit, GridRegion region) { TravelingAgentInfo travel = new TravelingAgentInfo(); @@ -186,6 +194,10 @@ namespace OpenSim.Services.HypergridService foreach (UUID session in travels) m_TravelingAgents.Remove(session); } + + GridUserInfo guinfo = m_GridUserService.GetGridUserInfo(userID.ToString()); + if (guinfo != null) + m_GridUserService.LoggedOut(userID.ToString(), guinfo.LastRegionID, guinfo.LastPosition, guinfo.LastLookAt); } // We need to prevent foreign users with the same UUID as a local user @@ -200,22 +212,16 @@ namespace OpenSim.Services.HypergridService public bool VerifyClient(UUID sessionID, string token) { - return true; + m_log.DebugFormat("[USER AGENT SERVICE]: Verifying Client session {0} with token {1}", sessionID, token); + //return true; // Commenting this for now until I understand better what part of a sender's // info stays unchanged throughout a session - // - //if (m_TravelingAgents.ContainsKey(sessionID)) - //{ - // // Aquiles heel. Must trust the first grid upon login - // if (m_TravelingAgents[sessionID].ClientToken == string.Empty) - // { - // m_TravelingAgents[sessionID].ClientToken = token; - // return true; - // } - // return m_TravelingAgents[sessionID].ClientToken == token; - //} - //return false; + + if (m_TravelingAgents.ContainsKey(sessionID)) + return m_TravelingAgents[sessionID].ClientToken == token; + + return false; } public bool VerifyAgent(UUID sessionID, string token) diff --git a/OpenSim/Services/Interfaces/IFriendsService.cs b/OpenSim/Services/Interfaces/IFriendsService.cs index 2692c48f39..0ddd5e53a9 100644 --- a/OpenSim/Services/Interfaces/IFriendsService.cs +++ b/OpenSim/Services/Interfaces/IFriendsService.cs @@ -62,7 +62,7 @@ namespace OpenSim.Services.Interfaces public Dictionary ToKeyValuePairs() { Dictionary result = new Dictionary(); - result["PricipalID"] = PrincipalID.ToString(); + result["PrincipalID"] = PrincipalID.ToString(); result["Friend"] = Friend; result["MyFlags"] = MyFlags.ToString(); result["TheirFlags"] = TheirFlags.ToString(); diff --git a/OpenSim/Services/Interfaces/IGatekeeperService.cs b/OpenSim/Services/Interfaces/IGatekeeperService.cs index ca7b9b3324..2d397bc03d 100644 --- a/OpenSim/Services/Interfaces/IGatekeeperService.cs +++ b/OpenSim/Services/Interfaces/IGatekeeperService.cs @@ -49,6 +49,7 @@ namespace OpenSim.Services.Interfaces public interface IUserAgentService { bool LoginAgentToGrid(AgentCircuitData agent, GridRegion gatekeeper, GridRegion finalDestination, out string reason); + void SetClientToken(UUID sessionID, string token); void LogoutAgent(UUID userID, UUID sessionID); GridRegion GetHomeRegion(UUID userID, out Vector3 position, out Vector3 lookAt); diff --git a/OpenSim/Services/Interfaces/IGridUserService.cs b/OpenSim/Services/Interfaces/IGridUserService.cs index a7c2c6f014..e629dffda4 100644 --- a/OpenSim/Services/Interfaces/IGridUserService.cs +++ b/OpenSim/Services/Interfaces/IGridUserService.cs @@ -37,39 +37,79 @@ namespace OpenSim.Services.Interfaces public class GridUserInfo { public string UserID; + public UUID HomeRegionID; public Vector3 HomePosition; public Vector3 HomeLookAt; + public UUID LastRegionID; + public Vector3 LastPosition; + public Vector3 LastLookAt; + + public bool Online; + public DateTime Login; + public DateTime Logout; + public GridUserInfo() {} public GridUserInfo(Dictionary kvp) { if (kvp.ContainsKey("UserID")) UserID = kvp["UserID"].ToString(); + if (kvp.ContainsKey("HomeRegionID")) UUID.TryParse(kvp["HomeRegionID"].ToString(), out HomeRegionID); if (kvp.ContainsKey("HomePosition")) Vector3.TryParse(kvp["HomePosition"].ToString(), out HomePosition); if (kvp.ContainsKey("HomeLookAt")) Vector3.TryParse(kvp["HomeLookAt"].ToString(), out HomeLookAt); + + if (kvp.ContainsKey("LastRegionID")) + UUID.TryParse(kvp["LastRegionID"].ToString(), out HomeRegionID); + if (kvp.ContainsKey("LastPosition")) + Vector3.TryParse(kvp["LastPosition"].ToString(), out LastPosition); + if (kvp.ContainsKey("LastLookAt")) + Vector3.TryParse(kvp["LastLookAt"].ToString(), out LastLookAt); + + if (kvp.ContainsKey("Login")) + DateTime.TryParse(kvp["Login"].ToString(), out Login); + if (kvp.ContainsKey("Logout")) + DateTime.TryParse(kvp["Logout"].ToString(), out Logout); + if (kvp.ContainsKey("Online")) + Boolean.TryParse(kvp["Online"].ToString(), out Online); + } public Dictionary ToKeyValuePairs() { Dictionary result = new Dictionary(); result["UserID"] = UserID; + result["HomeRegionID"] = HomeRegionID.ToString(); result["HomePosition"] = HomePosition.ToString(); result["HomeLookAt"] = HomeLookAt.ToString(); + result["LastRegionID"] = LastRegionID.ToString(); + result["LastPosition"] = LastPosition.ToString(); + result["LastLookAt"] = LastLookAt.ToString(); + + result["Online"] = Online.ToString(); + result["Login"] = Login.ToString(); + result["Logout"] = Logout.ToString(); + + return result; } } public interface IGridUserService { + GridUserInfo LoggedIn(string userID); + bool LoggedOut(string userID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt); + + bool SetHome(string userID, UUID homeID, Vector3 homePosition, Vector3 homeLookAt); + bool SetLastPosition(string userID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt); + GridUserInfo GetGridUserInfo(string userID); - bool StoreGridUserInfo(GridUserInfo info); } } \ No newline at end of file diff --git a/OpenSim/Services/Interfaces/ILoginService.cs b/OpenSim/Services/Interfaces/ILoginService.cs index 24bf342742..9e573393d7 100644 --- a/OpenSim/Services/Interfaces/ILoginService.cs +++ b/OpenSim/Services/Interfaces/ILoginService.cs @@ -31,6 +31,7 @@ using System.Collections.Generic; using System.Net; using OpenMetaverse.StructuredData; +using OpenMetaverse; namespace OpenSim.Services.Interfaces { @@ -46,7 +47,8 @@ namespace OpenSim.Services.Interfaces public interface ILoginService { - LoginResponse Login(string firstName, string lastName, string passwd, string startLocation, IPEndPoint clientIP); + LoginResponse Login(string firstName, string lastName, string passwd, string startLocation, UUID scopeID, string clientVersion, IPEndPoint clientIP); + Hashtable SetLevel(string firstName, string lastName, string passwd, int level, IPEndPoint clientIP); } diff --git a/OpenSim/Services/Interfaces/IPresenceService.cs b/OpenSim/Services/Interfaces/IPresenceService.cs index b4c18592cd..8d583fff73 100644 --- a/OpenSim/Services/Interfaces/IPresenceService.cs +++ b/OpenSim/Services/Interfaces/IPresenceService.cs @@ -36,14 +36,6 @@ namespace OpenSim.Services.Interfaces { public string UserID; public UUID RegionID; - public bool Online; - public DateTime Login; - public DateTime Logout; - public Vector3 Position; - public Vector3 LookAt; - public UUID HomeRegionID; - public Vector3 HomePosition; - public Vector3 HomeLookAt; public PresenceInfo() { @@ -55,23 +47,6 @@ namespace OpenSim.Services.Interfaces UserID = kvp["UserID"].ToString(); if (kvp.ContainsKey("RegionID")) UUID.TryParse(kvp["RegionID"].ToString(), out RegionID); - if (kvp.ContainsKey("login")) - DateTime.TryParse(kvp["login"].ToString(), out Login); - if (kvp.ContainsKey("logout")) - DateTime.TryParse(kvp["logout"].ToString(), out Logout); - if (kvp.ContainsKey("lookAt")) - Vector3.TryParse(kvp["lookAt"].ToString(), out LookAt); - if (kvp.ContainsKey("online")) - Boolean.TryParse(kvp["online"].ToString(), out Online); - if (kvp.ContainsKey("position")) - Vector3.TryParse(kvp["position"].ToString(), out Position); - if (kvp.ContainsKey("HomeRegionID")) - UUID.TryParse(kvp["HomeRegionID"].ToString(), out HomeRegionID); - if (kvp.ContainsKey("HomePosition")) - Vector3.TryParse(kvp["HomePosition"].ToString(), out HomePosition); - if (kvp.ContainsKey("HomeLookAt")) - Vector3.TryParse(kvp["HomeLookAt"].ToString(), out HomeLookAt); - } public Dictionary ToKeyValuePairs() @@ -79,47 +54,18 @@ namespace OpenSim.Services.Interfaces Dictionary result = new Dictionary(); result["UserID"] = UserID; result["RegionID"] = RegionID.ToString(); - result["online"] = Online.ToString(); - result["login"] = Login.ToString(); - result["logout"] = Logout.ToString(); - result["position"] = Position.ToString(); - result["lookAt"] = LookAt.ToString(); - result["HomeRegionID"] = HomeRegionID.ToString(); - result["HomePosition"] = HomePosition.ToString(); - result["HomeLookAt"] = HomeLookAt.ToString(); return result; } - - public static PresenceInfo[] GetOnlinePresences(PresenceInfo[] pinfos) - { - if (pinfos == null) - return null; - - List lst = new List(pinfos); - lst = lst.FindAll(delegate(PresenceInfo each) { return each.Online; }); - - return lst.ToArray(); - } - - public static PresenceInfo GetOnlinePresence(PresenceInfo[] pinfos) - { - pinfos = GetOnlinePresences(pinfos); - if (pinfos != null && pinfos.Length >= 1) - return pinfos[0]; - - return null; - } } public interface IPresenceService { bool LoginAgent(string userID, UUID sessionID, UUID secureSessionID); - bool LogoutAgent(UUID sessionID, Vector3 position, Vector3 lookAt); + bool LogoutAgent(UUID sessionID); bool LogoutRegionAgents(UUID regionID); - bool ReportAgent(UUID sessionID, UUID regionID, Vector3 position, Vector3 lookAt); - bool SetHomeLocation(string userID, UUID regionID, Vector3 position, Vector3 lookAt); + bool ReportAgent(UUID sessionID, UUID regionID); PresenceInfo GetAgent(UUID sessionID); PresenceInfo[] GetAgents(string[] userIDs); diff --git a/OpenSim/Services/Interfaces/IUserAccountService.cs b/OpenSim/Services/Interfaces/IUserAccountService.cs index befd14e02a..09d1d874f0 100644 --- a/OpenSim/Services/Interfaces/IUserAccountService.cs +++ b/OpenSim/Services/Interfaces/IUserAccountService.cs @@ -84,14 +84,14 @@ namespace OpenSim.Services.Interfaces if (kvp.ContainsKey("ScopeID")) UUID.TryParse(kvp["ScopeID"].ToString(), out ScopeID); if (kvp.ContainsKey("UserLevel")) - Convert.ToInt32(kvp["UserLevel"].ToString()); + UserLevel = Convert.ToInt32(kvp["UserLevel"].ToString()); if (kvp.ContainsKey("UserFlags")) - Convert.ToInt32(kvp["UserFlags"].ToString()); + UserFlags = Convert.ToInt32(kvp["UserFlags"].ToString()); if (kvp.ContainsKey("UserTitle")) - Email = kvp["UserTitle"].ToString(); + UserTitle = kvp["UserTitle"].ToString(); if (kvp.ContainsKey("Created")) - Convert.ToInt32(kvp["Created"].ToString()); + Created = Convert.ToInt32(kvp["Created"].ToString()); if (kvp.ContainsKey("ServiceURLs") && kvp["ServiceURLs"] != null) { ServiceURLs = new Dictionary(); diff --git a/OpenSim/Services/InventoryService/InventoryService.cs b/OpenSim/Services/InventoryService/InventoryService.cs index 0d6577e776..fbcd6634e7 100644 --- a/OpenSim/Services/InventoryService/InventoryService.cs +++ b/OpenSim/Services/InventoryService/InventoryService.cs @@ -109,7 +109,7 @@ namespace OpenSim.Services.InventoryService { existingRootFolder = GetRootFolder(user); } - catch (Exception e) + catch /*(Exception e)*/ { // Munch the exception, it has already been reported // diff --git a/OpenSim/Services/InventoryService/XInventoryService.cs b/OpenSim/Services/InventoryService/XInventoryService.cs index bbd37d123a..974caf0d7e 100644 --- a/OpenSim/Services/InventoryService/XInventoryService.cs +++ b/OpenSim/Services/InventoryService/XInventoryService.cs @@ -184,7 +184,7 @@ namespace OpenSim.Services.InventoryService foreach (XInventoryFolder x in allFolders) { - m_log.DebugFormat("[INVENTORY]: Adding folder {0} to skeleton", x.folderName); + //m_log.DebugFormat("[XINVENTORY]: Adding folder {0} to skeleton", x.folderName); folders.Add(ConvertToOpenSim(x)); } @@ -221,7 +221,7 @@ namespace OpenSim.Services.InventoryService // connector. So we disregard the principal and look // by ID. // - m_log.DebugFormat("[INVENTORY]: Fetch contents for folder {0}", folderID.ToString()); + m_log.DebugFormat("[XINVENTORY]: Fetch contents for folder {0}", folderID.ToString()); InventoryCollection inventory = new InventoryCollection(); inventory.UserID = principalID; inventory.Folders = new List(); @@ -233,7 +233,7 @@ namespace OpenSim.Services.InventoryService foreach (XInventoryFolder x in folders) { - m_log.DebugFormat("[INVENTORY]: Adding folder {0} to response", x.folderName); + //m_log.DebugFormat("[XINVENTORY]: Adding folder {0} to response", x.folderName); inventory.Folders.Add(ConvertToOpenSim(x)); } @@ -243,7 +243,7 @@ namespace OpenSim.Services.InventoryService foreach (XInventoryItem i in items) { - m_log.DebugFormat("[INVENTORY]: Adding item {0} to response", i.inventoryName); + //m_log.DebugFormat("[XINVENTORY]: Adding item {0} to response", i.inventoryName); inventory.Items.Add(ConvertToOpenSim(i)); } @@ -386,7 +386,7 @@ namespace OpenSim.Services.InventoryService XInventoryItem[] items = m_Database.GetActiveGestures(principalID); if (items.Length == 0) - return null; + return new List(); List ret = new List(); diff --git a/OpenSim/Services/LLLoginService/LLLoginResponse.cs b/OpenSim/Services/LLLoginService/LLLoginResponse.cs index ee30fa38ef..54d53fb2a4 100644 --- a/OpenSim/Services/LLLoginService/LLLoginResponse.cs +++ b/OpenSim/Services/LLLoginService/LLLoginResponse.cs @@ -215,14 +215,16 @@ namespace OpenSim.Services.LLLoginService SetDefaultValues(); } - public LLLoginResponse(UserAccount account, AgentCircuitData aCircuit, PresenceInfo pinfo, + public LLLoginResponse(UserAccount account, AgentCircuitData aCircuit, GridUserInfo pinfo, GridRegion destination, List invSkel, FriendInfo[] friendsList, ILibraryService libService, - string where, string startlocation, Vector3 position, Vector3 lookAt, string message, + string where, string startlocation, Vector3 position, Vector3 lookAt, List gestures, string message, GridRegion home, IPEndPoint clientIP) : this() { FillOutInventoryData(invSkel, libService); + FillOutActiveGestures(gestures); + CircuitCode = (int)aCircuit.circuitcode; Lastname = account.LastName; Firstname = account.FirstName; @@ -283,7 +285,23 @@ namespace OpenSim.Services.LLLoginService } } - private void FillOutHomeData(PresenceInfo pinfo, GridRegion home) + private void FillOutActiveGestures(List gestures) + { + ArrayList list = new ArrayList(); + if (gestures != null) + { + foreach (InventoryItemBase gesture in gestures) + { + Hashtable item = new Hashtable(); + item["item_id"] = gesture.ID.ToString(); + item["asset_id"] = gesture.AssetID.ToString(); + list.Add(item); + } + } + ActiveGestures = list; + } + + private void FillOutHomeData(GridUserInfo pinfo, GridRegion home) { int x = 1000 * (int)Constants.RegionSize, y = 1000 * (int)Constants.RegionSize; if (home != null) diff --git a/OpenSim/Services/LLLoginService/LLLoginService.cs b/OpenSim/Services/LLLoginService/LLLoginService.cs index 7b25274b47..6319cc4a13 100644 --- a/OpenSim/Services/LLLoginService/LLLoginService.cs +++ b/OpenSim/Services/LLLoginService/LLLoginService.cs @@ -26,6 +26,7 @@ */ using System; +using System.Collections; using System.Collections.Generic; using System.Net; using System.Reflection; @@ -52,24 +53,26 @@ namespace OpenSim.Services.LLLoginService private static bool Initialized = false; protected IUserAccountService m_UserAccountService; + protected IGridUserService m_GridUserService; protected IAuthenticationService m_AuthenticationService; protected IInventoryService m_InventoryService; protected IGridService m_GridService; protected IPresenceService m_PresenceService; - private ISimulationService m_LocalSimulationService; - private ISimulationService m_RemoteSimulationService; + protected ISimulationService m_LocalSimulationService; + protected ISimulationService m_RemoteSimulationService; protected ILibraryService m_LibraryService; protected IFriendsService m_FriendsService; protected IAvatarService m_AvatarService; - private IUserAgentService m_UserAgentService; + protected IUserAgentService m_UserAgentService; - private GatekeeperServiceConnector m_GatekeeperConnector; + protected GatekeeperServiceConnector m_GatekeeperConnector; - private string m_DefaultRegionName; + protected string m_DefaultRegionName; protected string m_WelcomeMessage; - private bool m_RequireInventory; + protected bool m_RequireInventory; protected int m_MinLoginLevel; - private string m_GatekeeperURL; + protected string m_GatekeeperURL; + protected bool m_AllowRemoteSetLoginLevel; IConfig m_LoginServerConfig; @@ -80,6 +83,7 @@ namespace OpenSim.Services.LLLoginService throw new Exception(String.Format("No section LoginService in config file")); string accountService = m_LoginServerConfig.GetString("UserAccountService", String.Empty); + string gridUserService = m_LoginServerConfig.GetString("GridUserService", String.Empty); string agentService = m_LoginServerConfig.GetString("UserAgentService", String.Empty); string authService = m_LoginServerConfig.GetString("AuthenticationService", String.Empty); string invService = m_LoginServerConfig.GetString("InventoryService", String.Empty); @@ -93,6 +97,8 @@ namespace OpenSim.Services.LLLoginService m_DefaultRegionName = m_LoginServerConfig.GetString("DefaultRegion", String.Empty); m_WelcomeMessage = m_LoginServerConfig.GetString("WelcomeMessage", "Welcome to OpenSim!"); m_RequireInventory = m_LoginServerConfig.GetBoolean("RequireInventory", true); + m_AllowRemoteSetLoginLevel = m_LoginServerConfig.GetBoolean("AllowRemoteSetLoginLevel", false); + m_MinLoginLevel = m_LoginServerConfig.GetInt("MinLoginLevel", 0); m_GatekeeperURL = m_LoginServerConfig.GetString("GatekeeperURI", string.Empty); // These are required; the others aren't @@ -101,8 +107,10 @@ namespace OpenSim.Services.LLLoginService Object[] args = new Object[] { config }; m_UserAccountService = ServerUtils.LoadPlugin(accountService, args); + m_GridUserService = ServerUtils.LoadPlugin(gridUserService, args); m_AuthenticationService = ServerUtils.LoadPlugin(authService, args); m_InventoryService = ServerUtils.LoadPlugin(invService, args); + if (gridService != string.Empty) m_GridService = ServerUtils.LoadPlugin(gridService, args); if (presenceService != string.Empty) @@ -147,7 +155,56 @@ namespace OpenSim.Services.LLLoginService { } - public LoginResponse Login(string firstName, string lastName, string passwd, string startLocation, IPEndPoint clientIP) + public Hashtable SetLevel(string firstName, string lastName, string passwd, int level, IPEndPoint clientIP) + { + Hashtable response = new Hashtable(); + response["success"] = "false"; + + if (!m_AllowRemoteSetLoginLevel) + return response; + + try + { + UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero, firstName, lastName); + if (account == null) + { + m_log.InfoFormat("[LLOGIN SERVICE]: Set Level failed, user {0} {1} not found", firstName, lastName); + return response; + } + + if (account.UserLevel < 200) + { + m_log.InfoFormat("[LLOGIN SERVICE]: Set Level failed, reason: user level too low"); + return response; + } + + // + // Authenticate this user + // + // We don't support clear passwords here + // + string token = m_AuthenticationService.Authenticate(account.PrincipalID, passwd, 30); + UUID secureSession = UUID.Zero; + if ((token == string.Empty) || (token != string.Empty && !UUID.TryParse(token, out secureSession))) + { + m_log.InfoFormat("[LLOGIN SERVICE]: SetLevel failed, reason: authentication failed"); + return response; + } + } + catch (Exception e) + { + m_log.Error("[LLOGIN SERVICE]: SetLevel failed, exception " + e.ToString()); + return response; + } + + m_MinLoginLevel = level; + m_log.InfoFormat("[LLOGIN SERVICE]: Login level set to {0} by {1} {2}", level, firstName, lastName); + + response["success"] = true; + return response; + } + + public LoginResponse Login(string firstName, string lastName, string passwd, string startLocation, UUID scopeID, string clientVersion, IPEndPoint clientIP) { bool success = false; UUID session = UUID.Random(); @@ -157,7 +214,7 @@ namespace OpenSim.Services.LLLoginService // // Get the account and check that it exists // - UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero, firstName, lastName); + UserAccount account = m_UserAccountService.GetUserAccount(scopeID, firstName, lastName); if (account == null) { m_log.InfoFormat("[LLOGIN SERVICE]: Login failed, reason: user not found"); @@ -170,6 +227,22 @@ namespace OpenSim.Services.LLLoginService return LLFailedLoginResponse.LoginBlockedProblem; } + // If a scope id is requested, check that the account is in + // that scope, or unscoped. + // + if (scopeID != UUID.Zero) + { + if (account.ScopeID != scopeID && account.ScopeID != UUID.Zero) + { + m_log.InfoFormat("[LLOGIN SERVICE]: Login failed, reason: user not found"); + return LLFailedLoginResponse.UserProblem; + } + } + else + { + scopeID = account.ScopeID; + } + // // Authenticate this user // @@ -199,11 +272,13 @@ namespace OpenSim.Services.LLLoginService return LLFailedLoginResponse.InventoryProblem; } + // Get active gestures + List gestures = m_InventoryService.GetActiveGestures(account.PrincipalID); + m_log.DebugFormat("[LLOGIN SERVICE]: {0} active gestures", gestures.Count); + // // Login the presence // - PresenceInfo presence = null; - GridRegion home = null; if (m_PresenceService != null) { success = m_PresenceService.LoginAgent(account.PrincipalID.ToString(), session, secureSession); @@ -212,17 +287,24 @@ namespace OpenSim.Services.LLLoginService m_log.InfoFormat("[LLOGIN SERVICE]: Login failed, reason: could not login presence"); return LLFailedLoginResponse.GridProblem; } - - // Get the updated presence info - presence = m_PresenceService.GetAgent(session); - - // Get the home region - if ((presence.HomeRegionID != UUID.Zero) && m_GridService != null) - { - home = m_GridService.GetRegionByUUID(account.ScopeID, presence.HomeRegionID); - } } + // + // Change Online status and get the home region + // + GridRegion home = null; + GridUserInfo guinfo = m_GridUserService.LoggedIn(account.PrincipalID.ToString()); + if (guinfo != null && (guinfo.HomeRegionID != UUID.Zero) && m_GridService != null) + { + home = m_GridService.GetRegionByUUID(scopeID, guinfo.HomeRegionID); + } + if (guinfo == null) + { + // something went wrong, make something up, so that we don't have to test this anywhere else + guinfo = new GridUserInfo(); + guinfo.LastPosition = guinfo.HomePosition = new Vector3(128, 128, 30); + } + // // Find the destination region/grid // @@ -230,10 +312,10 @@ namespace OpenSim.Services.LLLoginService Vector3 position = Vector3.Zero; Vector3 lookAt = Vector3.Zero; GridRegion gatekeeper = null; - GridRegion destination = FindDestination(account, presence, session, startLocation, out gatekeeper, out where, out position, out lookAt); + GridRegion destination = FindDestination(account, scopeID, guinfo, session, startLocation, home, out gatekeeper, out where, out position, out lookAt); if (destination == null) { - m_PresenceService.LogoutAgent(session, presence.Position, presence.LookAt); + m_PresenceService.LogoutAgent(session); m_log.InfoFormat("[LLOGIN SERVICE]: Login failed, reason: destination not found"); return LLFailedLoginResponse.GridProblem; } @@ -251,11 +333,11 @@ namespace OpenSim.Services.LLLoginService // Instantiate/get the simulation interface and launch an agent at the destination // string reason = string.Empty; - AgentCircuitData aCircuit = LaunchAgentAtGrid(gatekeeper, destination, account, avatar, session, secureSession, position, where, out where, out reason); + AgentCircuitData aCircuit = LaunchAgentAtGrid(gatekeeper, destination, account, avatar, session, secureSession, position, where, clientVersion, clientIP, out where, out reason); if (aCircuit == null) { - m_PresenceService.LogoutAgent(session, presence.Position, presence.LookAt); + m_PresenceService.LogoutAgent(session); m_log.InfoFormat("[LLOGIN SERVICE]: Login failed, reason: {0}", reason); return LLFailedLoginResponse.AuthorizationProblem; @@ -271,8 +353,8 @@ namespace OpenSim.Services.LLLoginService // // Finally, fill out the response and return it // - LLLoginResponse response = new LLLoginResponse(account, aCircuit, presence, destination, inventorySkel, friendsList, m_LibraryService, - where, startLocation, position, lookAt, m_WelcomeMessage, home, clientIP); + LLLoginResponse response = new LLLoginResponse(account, aCircuit, guinfo, destination, inventorySkel, friendsList, m_LibraryService, + where, startLocation, position, lookAt, gestures, m_WelcomeMessage, home, clientIP); m_log.DebugFormat("[LLOGIN SERVICE]: All clear. Sending login response to client."); return response; @@ -281,12 +363,12 @@ namespace OpenSim.Services.LLLoginService { m_log.WarnFormat("[LLOGIN SERVICE]: Exception processing login for {0} {1}: {2} {3}", firstName, lastName, e.ToString(), e.StackTrace); if (m_PresenceService != null) - m_PresenceService.LogoutAgent(session, new Vector3(128, 128, 0), new Vector3(0, 1, 0)); + m_PresenceService.LogoutAgent(session); return LLFailedLoginResponse.InternalError; } } - protected GridRegion FindDestination(UserAccount account, PresenceInfo pinfo, UUID sessionID, string startLocation, out GridRegion gatekeeper, out string where, out Vector3 position, out Vector3 lookAt) + protected GridRegion FindDestination(UserAccount account, UUID scopeID, GridUserInfo pinfo, UUID sessionID, string startLocation, GridRegion home, out GridRegion gatekeeper, out string where, out Vector3 position, out Vector3 lookAt) { m_log.DebugFormat("[LLOGIN SERVICE]: FindDestination for start location {0}", startLocation); @@ -308,7 +390,7 @@ namespace OpenSim.Services.LLLoginService bool tryDefaults = false; - if (pinfo.HomeRegionID.Equals(UUID.Zero)) + if (home == null) { m_log.WarnFormat( "[LLOGIN SERVICE]: User {0} {1} tried to login to a 'home' start location but they have none set", @@ -318,21 +400,15 @@ namespace OpenSim.Services.LLLoginService } else { - region = m_GridService.GetRegionByUUID(account.ScopeID, pinfo.HomeRegionID); + region = home; - if (null == region) - { - m_log.WarnFormat( - "[LLOGIN SERVICE]: User {0} {1} has a recorded home region of {2} but this cannot be found by the grid service", - account.FirstName, account.LastName, pinfo.HomeRegionID); - - tryDefaults = true; - } + position = pinfo.HomePosition; + lookAt = pinfo.HomeLookAt; } if (tryDefaults) { - List defaults = m_GridService.GetDefaultRegions(account.ScopeID); + List defaults = m_GridService.GetDefaultRegions(scopeID); if (defaults != null && defaults.Count > 0) { region = defaults[0]; @@ -342,7 +418,7 @@ namespace OpenSim.Services.LLLoginService { m_log.WarnFormat("[LLOGIN SERVICE]: User {0} {1} does not have a valid home and this grid does not have default locations. Attempting to find random region", account.FirstName, account.LastName); - defaults = m_GridService.GetRegionsByName(account.ScopeID, "", 1); + defaults = m_GridService.GetRegionsByName(scopeID, "", 1); if (defaults != null && defaults.Count > 0) { region = defaults[0]; @@ -363,9 +439,9 @@ namespace OpenSim.Services.LLLoginService GridRegion region = null; - if (pinfo.RegionID.Equals(UUID.Zero) || (region = m_GridService.GetRegionByUUID(account.ScopeID, pinfo.RegionID)) == null) + if (pinfo.LastRegionID.Equals(UUID.Zero) || (region = m_GridService.GetRegionByUUID(scopeID, pinfo.LastRegionID)) == null) { - List defaults = m_GridService.GetDefaultRegions(account.ScopeID); + List defaults = m_GridService.GetDefaultRegions(scopeID); if (defaults != null && defaults.Count > 0) { region = defaults[0]; @@ -374,7 +450,7 @@ namespace OpenSim.Services.LLLoginService else { m_log.Info("[LLOGIN SERVICE]: Last Region Not Found Attempting to find random region"); - defaults = m_GridService.GetRegionsByName(account.ScopeID, "", 1); + defaults = m_GridService.GetRegionsByName(scopeID, "", 1); if (defaults != null && defaults.Count > 0) { region = defaults[0]; @@ -385,8 +461,8 @@ namespace OpenSim.Services.LLLoginService } else { - position = pinfo.Position; - lookAt = pinfo.LookAt; + position = pinfo.LastPosition; + lookAt = pinfo.LastLookAt; } return region; @@ -405,20 +481,20 @@ namespace OpenSim.Services.LLLoginService } else { - position = new Vector3(float.Parse(uriMatch.Groups["x"].Value), - float.Parse(uriMatch.Groups["y"].Value), - float.Parse(uriMatch.Groups["z"].Value)); + position = new Vector3(float.Parse(uriMatch.Groups["x"].Value, Culture.NumberFormatInfo), + float.Parse(uriMatch.Groups["y"].Value, Culture.NumberFormatInfo), + float.Parse(uriMatch.Groups["z"].Value, Culture.NumberFormatInfo)); string regionName = uriMatch.Groups["region"].ToString(); if (regionName != null) { if (!regionName.Contains("@")) { - List regions = m_GridService.GetRegionsByName(account.ScopeID, regionName, 1); + List regions = m_GridService.GetRegionsByName(scopeID, regionName, 1); if ((regions == null) || (regions != null && regions.Count == 0)) { m_log.InfoFormat("[LLLOGIN SERVICE]: Got Custom Login URI {0}, can't locate region {1}. Trying defaults.", startLocation, regionName); - regions = m_GridService.GetDefaultRegions(UUID.Zero); + regions = m_GridService.GetDefaultRegions(scopeID); if (regions != null && regions.Count > 0) { where = "safe"; @@ -461,7 +537,7 @@ namespace OpenSim.Services.LLLoginService } else { - List defaults = m_GridService.GetDefaultRegions(account.ScopeID); + List defaults = m_GridService.GetDefaultRegions(scopeID); if (defaults != null && defaults.Count > 0) { where = "safe"; @@ -517,7 +593,7 @@ namespace OpenSim.Services.LLLoginService } protected AgentCircuitData LaunchAgentAtGrid(GridRegion gatekeeper, GridRegion destination, UserAccount account, AvatarData avatar, - UUID session, UUID secureSession, Vector3 position, string currentWhere, out string where, out string reason) + UUID session, UUID secureSession, Vector3 position, string currentWhere, string viewer, IPEndPoint clientIP, out string where, out string reason) { where = currentWhere; ISimulationService simConnector = null; @@ -557,7 +633,7 @@ namespace OpenSim.Services.LLLoginService if (m_UserAgentService == null && simConnector != null) { circuitCode = (uint)Util.RandomClass.Next(); ; - aCircuit = MakeAgent(destination, account, avatar, session, secureSession, circuitCode, position); + aCircuit = MakeAgent(destination, account, avatar, session, secureSession, circuitCode, position, viewer); success = LaunchAgentDirectly(simConnector, destination, aCircuit, out reason); if (!success && m_GridService != null) { @@ -582,8 +658,8 @@ namespace OpenSim.Services.LLLoginService if (m_UserAgentService != null) { circuitCode = (uint)Util.RandomClass.Next(); ; - aCircuit = MakeAgent(destination, account, avatar, session, secureSession, circuitCode, position); - success = LaunchAgentIndirectly(gatekeeper, destination, aCircuit, out reason); + aCircuit = MakeAgent(destination, account, avatar, session, secureSession, circuitCode, position, viewer); + success = LaunchAgentIndirectly(gatekeeper, destination, aCircuit, clientIP, out reason); if (!success && m_GridService != null) { // Try the fallback regions @@ -592,7 +668,7 @@ namespace OpenSim.Services.LLLoginService { foreach (GridRegion r in fallbacks) { - success = LaunchAgentIndirectly(gatekeeper, r, aCircuit, out reason); + success = LaunchAgentIndirectly(gatekeeper, r, aCircuit, clientIP, out reason); if (success) { where = "safe"; @@ -611,7 +687,7 @@ namespace OpenSim.Services.LLLoginService } private AgentCircuitData MakeAgent(GridRegion region, UserAccount account, - AvatarData avatar, UUID session, UUID secureSession, uint circuit, Vector3 position) + AvatarData avatar, UUID session, UUID secureSession, uint circuit, Vector3 position, string viewer) { AgentCircuitData aCircuit = new AgentCircuitData(); @@ -632,6 +708,7 @@ namespace OpenSim.Services.LLLoginService aCircuit.SecureSessionID = secureSession; aCircuit.SessionID = session; aCircuit.startpos = position; + aCircuit.Viewer = viewer; SetServiceURLs(aCircuit, account); return aCircuit; @@ -668,10 +745,18 @@ namespace OpenSim.Services.LLLoginService return simConnector.CreateAgent(region, aCircuit, (int)Constants.TeleportFlags.ViaLogin, out reason); } - private bool LaunchAgentIndirectly(GridRegion gatekeeper, GridRegion destination, AgentCircuitData aCircuit, out string reason) + private bool LaunchAgentIndirectly(GridRegion gatekeeper, GridRegion destination, AgentCircuitData aCircuit, IPEndPoint clientIP, out string reason) { m_log.Debug("[LLOGIN SERVICE] Launching agent at " + destination.RegionName); - return m_UserAgentService.LoginAgentToGrid(aCircuit, gatekeeper, destination, out reason); + if (m_UserAgentService.LoginAgentToGrid(aCircuit, gatekeeper, destination, out reason)) + { + // We may need to do this at some point, + // so leaving it here in comments. + //IPAddress addr = NetworkUtil.GetIPFor(clientIP.Address, destination.ExternalEndPoint.Address); + m_UserAgentService.SetClientToken(aCircuit.SessionID, /*addr.Address.ToString() */ clientIP.Address.ToString()); + return true; + } + return false; } #region Console Commands diff --git a/OpenSim/Services/PresenceService/PresenceService.cs b/OpenSim/Services/PresenceService/PresenceService.cs index ea8d673c1f..601a69f042 100644 --- a/OpenSim/Services/PresenceService/PresenceService.cs +++ b/OpenSim/Services/PresenceService/PresenceService.cs @@ -54,9 +54,8 @@ namespace OpenSim.Services.PresenceService public bool LoginAgent(string userID, UUID sessionID, UUID secureSessionID) { - m_Database.Prune(userID); - - PresenceData[] d = m_Database.Get("UserID", userID); + //PresenceData[] d = m_Database.Get("UserID", userID); + m_Database.Get("UserID", userID); PresenceData data = new PresenceData(); @@ -65,24 +64,6 @@ namespace OpenSim.Services.PresenceService data.SessionID = sessionID; data.Data = new Dictionary(); data.Data["SecureSessionID"] = secureSessionID.ToString(); - data.Data["Online"] = "true"; - data.Data["Login"] = Util.UnixTimeSinceEpoch().ToString(); - if (d != null && d.Length > 0) - { - data.Data["HomeRegionID"] = d[0].Data["HomeRegionID"]; - data.Data["HomePosition"] = d[0].Data["HomePosition"]; - data.Data["HomeLookAt"] = d[0].Data["HomeLookAt"]; - data.Data["Position"] = d[0].Data["Position"]; - data.Data["LookAt"] = d[0].Data["LookAt"]; - - data.RegionID = d[0].RegionID; - } - else - { - data.Data["HomeRegionID"] = UUID.Zero.ToString(); - data.Data["HomePosition"] = new Vector3(128, 128, 0).ToString(); - data.Data["HomeLookAt"] = new Vector3(0, 1, 0).ToString(); - } m_Database.Store(data); @@ -91,28 +72,10 @@ namespace OpenSim.Services.PresenceService return true; } - public bool LogoutAgent(UUID sessionID, Vector3 position, Vector3 lookat) + public bool LogoutAgent(UUID sessionID) { - PresenceData data = m_Database.Get(sessionID); - if (data == null) - return false; - - PresenceData[] d = m_Database.Get("UserID", data.UserID); - - m_log.DebugFormat("[PRESENCE SERVICE]: LogoutAgent {0} with {1} sessions currently present", data.UserID, d.Length); - if (d.Length > 1) - { - m_Database.Delete("UserID", data.UserID); - } - - data.Data["Online"] = "false"; - data.Data["Logout"] = Util.UnixTimeSinceEpoch().ToString(); - data.Data["Position"] = position.ToString(); - data.Data["LookAt"] = lookat.ToString(); - - m_Database.Store(data); - - return true; + m_log.DebugFormat("[PRESENCE SERVICE]: Session {0} logout", sessionID); + return m_Database.Delete("SessionID", sessionID.ToString()); } public bool LogoutRegionAgents(UUID regionID) @@ -123,7 +86,7 @@ namespace OpenSim.Services.PresenceService } - public bool ReportAgent(UUID sessionID, UUID regionID, Vector3 position, Vector3 lookAt) + public bool ReportAgent(UUID sessionID, UUID regionID) { m_log.DebugFormat("[PRESENCE SERVICE]: ReportAgent with session {0} in region {1}", sessionID, regionID); try @@ -134,14 +97,7 @@ namespace OpenSim.Services.PresenceService if (pdata.Data == null) return false; - if (!pdata.Data.ContainsKey("Online") || (pdata.Data.ContainsKey("Online") && pdata.Data["Online"] == "false")) - { - m_log.WarnFormat("[PRESENCE SERVICE]: Someone tried to report presence of an agent who's not online"); - return false; - } - - return m_Database.ReportAgent(sessionID, regionID, - position.ToString(), lookAt.ToString()); + return m_Database.ReportAgent(sessionID, regionID); } catch (Exception e) { @@ -160,22 +116,6 @@ namespace OpenSim.Services.PresenceService ret.UserID = data.UserID; ret.RegionID = data.RegionID; - if (data.Data.ContainsKey("Online")) - ret.Online = bool.Parse(data.Data["Online"]); - if (data.Data.ContainsKey("Login")) - ret.Login = Util.ToDateTime(Convert.ToInt32(data.Data["Login"])); - if (data.Data.ContainsKey("Logout")) - ret.Logout = Util.ToDateTime(Convert.ToInt32(data.Data["Logout"])); - if (data.Data.ContainsKey("Position")) - ret.Position = Vector3.Parse(data.Data["Position"]); - if (data.Data.ContainsKey("LookAt")) - ret.LookAt = Vector3.Parse(data.Data["LookAt"]); - if (data.Data.ContainsKey("HomeRegionID")) - ret.HomeRegionID = new UUID(data.Data["HomeRegionID"]); - if (data.Data.ContainsKey("HomePosition")) - ret.HomePosition = Vector3.Parse(data.Data["HomePosition"]); - if (data.Data.ContainsKey("HomeLookAt")) - ret.HomeLookAt = Vector3.Parse(data.Data["HomeLookAt"]); return ret; } @@ -195,16 +135,6 @@ namespace OpenSim.Services.PresenceService ret.UserID = d.UserID; ret.RegionID = d.RegionID; - ret.Online = bool.Parse(d.Data["Online"]); - ret.Login = Util.ToDateTime(Convert.ToInt32( - d.Data["Login"])); - ret.Logout = Util.ToDateTime(Convert.ToInt32( - d.Data["Logout"])); - ret.Position = Vector3.Parse(d.Data["Position"]); - ret.LookAt = Vector3.Parse(d.Data["LookAt"]); - ret.HomeRegionID = new UUID(d.Data["HomeRegionID"]); - ret.HomePosition = Vector3.Parse(d.Data["HomePosition"]); - ret.HomeLookAt = Vector3.Parse(d.Data["HomeLookAt"]); info.Add(ret); } @@ -214,9 +144,5 @@ namespace OpenSim.Services.PresenceService return info.ToArray(); } - public bool SetHomeLocation(string userID, UUID regionID, Vector3 position, Vector3 lookAt) - { - return m_Database.SetHomeLocation(userID, regionID, position, lookAt); - } } } diff --git a/OpenSim/Services/UserAccountService/GridUserService.cs b/OpenSim/Services/UserAccountService/GridUserService.cs index c6e33bbbfe..697ba639d2 100644 --- a/OpenSim/Services/UserAccountService/GridUserService.cs +++ b/OpenSim/Services/UserAccountService/GridUserService.cs @@ -31,6 +31,7 @@ using System.Reflection; using Nini.Config; using OpenSim.Data; using OpenSim.Services.Interfaces; +using OpenSim.Framework; using OpenSim.Framework.Console; using GridRegion = OpenSim.Services.Interfaces.GridRegion; @@ -50,27 +51,109 @@ namespace OpenSim.Services.UserAccountService public GridUserInfo GetGridUserInfo(string userID) { - GridUserData d = m_Database.GetGridUserData(userID); - + GridUserData d = m_Database.Get(userID); + + if (d == null) + return null; + GridUserInfo info = new GridUserInfo(); info.UserID = d.UserID; info.HomeRegionID = new UUID(d.Data["HomeRegionID"]); info.HomePosition = Vector3.Parse(d.Data["HomePosition"]); info.HomeLookAt = Vector3.Parse(d.Data["HomeLookAt"]); + info.LastRegionID = new UUID(d.Data["LastRegionID"]); + info.LastPosition = Vector3.Parse(d.Data["LastPosition"]); + info.LastLookAt = Vector3.Parse(d.Data["LastLookAt"]); + + info.Online = bool.Parse(d.Data["Online"]); + info.Login = Util.ToDateTime(Convert.ToInt32(d.Data["Login"])); + info.Logout = Util.ToDateTime(Convert.ToInt32(d.Data["Logout"])); + return info; } - - public bool StoreGridUserInfo(GridUserInfo info) + + public GridUserInfo LoggedIn(string userID) + { + m_log.DebugFormat("[GRID USER SERVICE]: User {0} is online", userID); + GridUserData d = m_Database.Get(userID); + + if (d == null) + { + d = new GridUserData(); + d.UserID = userID; + } + + d.Data["Online"] = true.ToString(); + d.Data["Login"] = Util.UnixTimeSinceEpoch().ToString(); + + m_Database.Store(d); + + return GetGridUserInfo(userID); + } + + public bool LoggedOut(string userID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt) + { + m_log.DebugFormat("[GRID USER SERVICE]: User {0} is offline", userID); + GridUserData d = m_Database.Get(userID); + + if (d == null) + { + d = new GridUserData(); + d.UserID = userID; + } + + d.Data["Online"] = false.ToString(); + d.Data["Logout"] = Util.UnixTimeSinceEpoch().ToString(); + d.Data["LastRegionID"] = regionID.ToString(); + d.Data["LastPosition"] = lastPosition.ToString(); + d.Data["LastLookAt"] = lastLookAt.ToString(); + + return m_Database.Store(d); + } + + protected bool StoreGridUserInfo(GridUserInfo info) { GridUserData d = new GridUserData(); - d.Data["UserID"] = info.UserID; d.Data["HomeRegionID"] = info.HomeRegionID.ToString(); d.Data["HomePosition"] = info.HomePosition.ToString(); d.Data["HomeLookAt"] = info.HomeLookAt.ToString(); - return m_Database.StoreGridUserData(d); + return m_Database.Store(d); + } + + public bool SetHome(string userID, UUID homeID, Vector3 homePosition, Vector3 homeLookAt) + { + GridUserData d = m_Database.Get(userID); + if (d == null) + { + d = new GridUserData(); + d.UserID = userID; + } + + d.Data["HomeRegionID"] = homeID.ToString(); + d.Data["HomePosition"] = homePosition.ToString(); + d.Data["HomeLookAt"] = homeLookAt.ToString(); + + return m_Database.Store(d); + } + + public bool SetLastPosition(string userID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt) + { + //m_log.DebugFormat("[Grid User Service]: SetLastPosition for {0}", userID); + GridUserData d = m_Database.Get(userID); + if (d == null) + { + d = new GridUserData(); + d.UserID = userID; + } + + d.Data["LastRegionID"] = regionID.ToString(); + d.Data["LastPosition"] = lastPosition.ToString(); + d.Data["LastLookAt"] = lastLookAt.ToString(); + + return m_Database.Store(d); } } } \ No newline at end of file diff --git a/OpenSim/Services/UserAccountService/UserAccountService.cs b/OpenSim/Services/UserAccountService/UserAccountService.cs index 7b38aa69f9..eb588f0145 100644 --- a/OpenSim/Services/UserAccountService/UserAccountService.cs +++ b/OpenSim/Services/UserAccountService/UserAccountService.cs @@ -46,7 +46,7 @@ namespace OpenSim.Services.UserAccountService protected IGridService m_GridService; protected IAuthenticationService m_AuthenticationService; - protected IPresenceService m_PresenceService; + protected IGridUserService m_GridUserService; protected IInventoryService m_InventoryService; public UserAccountService(IConfigSource config) @@ -69,9 +69,9 @@ namespace OpenSim.Services.UserAccountService if (authServiceDll != string.Empty) m_AuthenticationService = LoadPlugin(authServiceDll, new Object[] { config }); - string presenceServiceDll = userConfig.GetString("PresenceService", string.Empty); + string presenceServiceDll = userConfig.GetString("GridUserService", string.Empty); if (presenceServiceDll != string.Empty) - m_PresenceService = LoadPlugin(presenceServiceDll, new Object[] { config }); + m_GridUserService = LoadPlugin(presenceServiceDll, new Object[] { config }); string invServiceDll = userConfig.GetString("InventoryService", string.Empty); if (invServiceDll != string.Empty) @@ -104,6 +104,12 @@ namespace OpenSim.Services.UserAccountService d = m_Database.Get( new string[] { "ScopeID", "FirstName", "LastName" }, new string[] { scopeID.ToString(), firstName, lastName }); + if (d.Length < 1) + { + d = m_Database.Get( + new string[] { "ScopeID", "FirstName", "LastName" }, + new string[] { UUID.Zero.ToString(), firstName, lastName }); + } } else { @@ -172,6 +178,12 @@ namespace OpenSim.Services.UserAccountService d = m_Database.Get( new string[] { "ScopeID", "Email" }, new string[] { scopeID.ToString(), email }); + if (d.Length < 1) + { + d = m_Database.Get( + new string[] { "ScopeID", "Email" }, + new string[] { UUID.Zero.ToString(), email }); + } } else { @@ -195,6 +207,12 @@ namespace OpenSim.Services.UserAccountService d = m_Database.Get( new string[] { "ScopeID", "PrincipalID" }, new string[] { scopeID.ToString(), principalID.ToString() }); + if (d.Length < 1) + { + d = m_Database.Get( + new string[] { "ScopeID", "PrincipalID" }, + new string[] { UUID.Zero.ToString(), principalID.ToString() }); + } } else { @@ -259,8 +277,9 @@ namespace OpenSim.Services.UserAccountService #endregion #region Console commands + /// - /// Create a new user + /// Handle the create user command from the console. /// /// string array with parameters: firstname, lastname, password, locationX, locationY, email protected void HandleCreateUser(string module, string[] cmdparams) @@ -286,61 +305,7 @@ namespace OpenSim.Services.UserAccountService email = MainConsole.Instance.CmdPrompt("Email", ""); else email = cmdparams[5]; - UserAccount account = GetUserAccount(UUID.Zero, firstName, lastName); - if (null == account) - { - account = new UserAccount(UUID.Zero, firstName, lastName, email); - if (account.ServiceURLs == null || (account.ServiceURLs != null && account.ServiceURLs.Count == 0)) - { - account.ServiceURLs = new Dictionary(); - account.ServiceURLs["HomeURI"] = string.Empty; - account.ServiceURLs["GatekeeperURI"] = string.Empty; - account.ServiceURLs["InventoryServerURI"] = string.Empty; - account.ServiceURLs["AssetServerURI"] = string.Empty; - } - - if (StoreUserAccount(account)) - { - bool success = false; - if (m_AuthenticationService != null) - success = m_AuthenticationService.SetPassword(account.PrincipalID, password); - if (!success) - m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to set password for account {0} {1}.", - firstName, lastName); - - GridRegion home = null; - if (m_GridService != null) - { - List defaultRegions = m_GridService.GetDefaultRegions(UUID.Zero); - if (defaultRegions != null && defaultRegions.Count >= 1) - home = defaultRegions[0]; - - if (m_PresenceService != null && home != null) - m_PresenceService.SetHomeLocation(account.PrincipalID.ToString(), home.RegionID, new Vector3(128, 128, 0), new Vector3(0, 1, 0)); - else - m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to set home for account {0} {1}.", - firstName, lastName); - - } - else - m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to retrieve home region for account {0} {1}.", - firstName, lastName); - - if (m_InventoryService != null) - success = m_InventoryService.CreateUserInventory(account.PrincipalID); - if (!success) - m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to create inventory for account {0} {1}.", - firstName, lastName); - - - m_log.InfoFormat("[USER ACCOUNT SERVICE]: Account {0} {1} created successfully", firstName, lastName); - } - } - else - { - m_log.ErrorFormat("[USER ACCOUNT SERVICE]: A user with the name {0} {1} already exists!", firstName, lastName); - } - + CreateUser(firstName, lastName, password, email); } protected void HandleResetUserPassword(string module, string[] cmdparams) @@ -377,5 +342,67 @@ namespace OpenSim.Services.UserAccountService #endregion + /// + /// Create a user + /// + /// + /// + /// + /// + public void CreateUser(string firstName, string lastName, string password, string email) + { + UserAccount account = GetUserAccount(UUID.Zero, firstName, lastName); + if (null == account) + { + account = new UserAccount(UUID.Zero, firstName, lastName, email); + if (account.ServiceURLs == null || (account.ServiceURLs != null && account.ServiceURLs.Count == 0)) + { + account.ServiceURLs = new Dictionary(); + account.ServiceURLs["HomeURI"] = string.Empty; + account.ServiceURLs["GatekeeperURI"] = string.Empty; + account.ServiceURLs["InventoryServerURI"] = string.Empty; + account.ServiceURLs["AssetServerURI"] = string.Empty; + } + + if (StoreUserAccount(account)) + { + bool success = false; + if (m_AuthenticationService != null) + success = m_AuthenticationService.SetPassword(account.PrincipalID, password); + if (!success) + m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to set password for account {0} {1}.", + firstName, lastName); + + GridRegion home = null; + if (m_GridService != null) + { + List defaultRegions = m_GridService.GetDefaultRegions(UUID.Zero); + if (defaultRegions != null && defaultRegions.Count >= 1) + home = defaultRegions[0]; + + if (m_GridUserService != null && home != null) + m_GridUserService.SetHome(account.PrincipalID.ToString(), home.RegionID, new Vector3(128, 128, 0), new Vector3(0, 1, 0)); + else + m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to set home for account {0} {1}.", + firstName, lastName); + } + else + m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to retrieve home region for account {0} {1}.", + firstName, lastName); + + if (m_InventoryService != null) + success = m_InventoryService.CreateUserInventory(account.PrincipalID); + if (!success) + m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to create inventory for account {0} {1}.", + firstName, lastName); + + m_log.InfoFormat("[USER ACCOUNT SERVICE]: Account {0} {1} created successfully", firstName, lastName); + } + } + else + { + m_log.ErrorFormat("[USER ACCOUNT SERVICE]: A user with the name {0} {1} already exists!", firstName, lastName); + } + } } } diff --git a/OpenSim/Tests/Clients/Presence/PresenceClient.cs b/OpenSim/Tests/Clients/Presence/PresenceClient.cs index 4f959f6547..fd3905adcb 100644 --- a/OpenSim/Tests/Clients/Presence/PresenceClient.cs +++ b/OpenSim/Tests/Clients/Presence/PresenceClient.cs @@ -73,11 +73,11 @@ namespace OpenSim.Tests.Clients.PresenceClient if (pinfo == null) m_log.InfoFormat("[PRESENCE CLIENT]: Unable to retrieve presence for {0}", user1); else - m_log.InfoFormat("[PRESENCE CLIENT]: Presence retrieved correctly: userID={0}; Online={1}; regionID={2}; homeRegion={3}", - pinfo.UserID, pinfo.Online, pinfo.RegionID, pinfo.HomeRegionID); + m_log.InfoFormat("[PRESENCE CLIENT]: Presence retrieved correctly: userID={0}; regionID={1}", + pinfo.UserID, pinfo.RegionID); System.Console.WriteLine("\n"); - success = m_Connector.ReportAgent(session1, region1, new Vector3(128, 128, 128), new Vector3(4, 5, 6)); + success = m_Connector.ReportAgent(session1, region1); if (success) m_log.InfoFormat("[PRESENCE CLIENT]: Successfully reported session {0} in region {1}", user1, region1); else @@ -86,24 +86,11 @@ namespace OpenSim.Tests.Clients.PresenceClient if (pinfo == null) m_log.InfoFormat("[PRESENCE CLIENT]: Unable to retrieve presence for {0} for second time", user1); else - m_log.InfoFormat("[PRESENCE CLIENT]: Presence retrieved correctly: userID={0}; Online={1}; regionID={2}; homeRegion={3}", - pinfo.UserID, pinfo.Online, pinfo.RegionID, pinfo.HomeRegionID); + m_log.InfoFormat("[PRESENCE CLIENT]: Presence retrieved correctly: userID={0}; regionID={2}", + pinfo.UserID, pinfo.RegionID); System.Console.WriteLine("\n"); - success = m_Connector.SetHomeLocation(user1.ToString(), region1, new Vector3(128, 128, 128), new Vector3(4, 5, 6)); - if (success) - m_log.InfoFormat("[PRESENCE CLIENT]: Successfully set home for user {0} in region {1}", user1, region1); - else - m_log.InfoFormat("[PRESENCE CLIENT]: failed to set home for user {0}", user1); - pinfo = m_Connector.GetAgent(session1); - if (pinfo == null) - m_log.InfoFormat("[PRESENCE CLIENT]: Unable to retrieve presence for {0} for third time", user1); - else - m_log.InfoFormat("[PRESENCE CLIENT]: Presence retrieved correctly: userID={0}; Online={1}; regionID={2}; homeRegion={3}", - pinfo.UserID, pinfo.Online, pinfo.RegionID, pinfo.HomeRegionID); - - System.Console.WriteLine("\n"); - success = m_Connector.LogoutAgent(session1, Vector3.Zero, Vector3.UnitY); + success = m_Connector.LogoutAgent(session1); if (success) m_log.InfoFormat("[PRESENCE CLIENT]: Successfully logged out user {0}", user1); else @@ -112,11 +99,11 @@ namespace OpenSim.Tests.Clients.PresenceClient if (pinfo == null) m_log.InfoFormat("[PRESENCE CLIENT]: Unable to retrieve presence for {0} for fourth time", user1); else - m_log.InfoFormat("[PRESENCE CLIENT]: Presence retrieved correctly: userID={0}; Online={1}; regionID={2}; homeRegion={3}", - pinfo.UserID, pinfo.Online, pinfo.RegionID, pinfo.HomeRegionID); + m_log.InfoFormat("[PRESENCE CLIENT]: Presence retrieved correctly: userID={0}; regionID={1}", + pinfo.UserID, pinfo.RegionID); System.Console.WriteLine("\n"); - success = m_Connector.ReportAgent(session1, UUID.Random(), Vector3.Zero, Vector3.Zero); + success = m_Connector.ReportAgent(session1, UUID.Random()); if (success) m_log.InfoFormat("[PRESENCE CLIENT]: Report agent succeeded, but this is wrong"); else diff --git a/OpenSim/Tests/Common/Mock/MockAssetDataPlugin.cs b/OpenSim/Tests/Common/Mock/MockAssetDataPlugin.cs index cc1dfbf02a..4a15cf2d64 100644 --- a/OpenSim/Tests/Common/Mock/MockAssetDataPlugin.cs +++ b/OpenSim/Tests/Common/Mock/MockAssetDataPlugin.cs @@ -60,5 +60,10 @@ namespace OpenSim.Tests.Common.Mock } public List FetchAssetMetadataSet(int start, int count) { return new List(count); } + + public bool Delete(string id) + { + return false; + } } -} \ No newline at end of file +} diff --git a/OpenSim/Tests/Common/Mock/TestClient.cs b/OpenSim/Tests/Common/Mock/TestClient.cs index 63f6129587..a8f1b20abb 100644 --- a/OpenSim/Tests/Common/Mock/TestClient.cs +++ b/OpenSim/Tests/Common/Mock/TestClient.cs @@ -522,6 +522,11 @@ namespace OpenSim.Tests.Common.Mock } + public void SendGenericMessage(string method, List message) + { + + } + public void SendGenericMessage(string method, List message) { @@ -624,14 +629,6 @@ namespace OpenSim.Tests.Common.Mock { } - public virtual void SendAvatarData(SendAvatarData data) - { - } - - public virtual void SendAvatarTerseUpdate(SendAvatarTerseData data) - { - } - public virtual void SendCoarseLocationUpdate(List users, List CoarseLocations) { } @@ -644,15 +641,15 @@ namespace OpenSim.Tests.Common.Mock { } - public virtual void SendPrimitiveToClient(SendPrimitiveData data) + public void SendAvatarDataImmediate(ISceneEntity avatar) { } - public virtual void SendPrimTerseUpdate(SendPrimitiveTerseData data) + public void SendPrimUpdate(ISceneEntity entity, PrimUpdateFlags updateFlags) { } - public virtual void ReprioritizeUpdates(StateUpdateTypes type, UpdatePriorityHandler handler) + public void ReprioritizeUpdates() { } diff --git a/OpenSim/Tests/Common/Mock/TestLandChannel.cs b/OpenSim/Tests/Common/Mock/TestLandChannel.cs index be28c270df..159764cff8 100644 --- a/OpenSim/Tests/Common/Mock/TestLandChannel.cs +++ b/OpenSim/Tests/Common/Mock/TestLandChannel.cs @@ -85,5 +85,9 @@ namespace OpenSim.Tests.Common.Mock public void setParcelObjectMaxOverride(overrideParcelMaxPrimCountDelegate overrideDel) {} public void setSimulatorObjectMaxOverride(overrideSimulatorMaxPrimCountDelegate overrideDel) {} public void SetParcelOtherCleanTime(IClientAPI remoteClient, int localID, int otherCleanTime) {} + + public void Join(int start_x, int start_y, int end_x, int end_y, UUID attempting_user_id) {} + public void Subdivide(int start_x, int start_y, int end_x, int end_y, UUID attempting_user_id) {} + } } diff --git a/OpenSim/Tests/Common/Setup/AssetHelpers.cs b/OpenSim/Tests/Common/Setup/AssetHelpers.cs index 1fc3cb5455..6dc993f069 100644 --- a/OpenSim/Tests/Common/Setup/AssetHelpers.cs +++ b/OpenSim/Tests/Common/Setup/AssetHelpers.cs @@ -38,12 +38,20 @@ namespace OpenSim.Tests.Common /// /// Create an asset from the given data /// - public static AssetBase CreateAsset(UUID assetUuid, string data, UUID creatorID) + public static AssetBase CreateAsset(UUID assetUuid, AssetType assetType, byte[] data, UUID creatorID) { - AssetBase asset = new AssetBase(assetUuid, assetUuid.ToString(), (sbyte)AssetType.Object, creatorID.ToString()); - asset.Data = Encoding.ASCII.GetBytes(data); + AssetBase asset = new AssetBase(assetUuid, assetUuid.ToString(), (sbyte)assetType, creatorID.ToString()); + asset.Data = data; return asset; } + + /// + /// Create an asset from the given data + /// + public static AssetBase CreateAsset(UUID assetUuid, AssetType assetType, string data, UUID creatorID) + { + return CreateAsset(assetUuid, assetType, Encoding.ASCII.GetBytes(data), creatorID); + } /// /// Create an asset from the given scene object @@ -53,9 +61,11 @@ namespace OpenSim.Tests.Common /// public static AssetBase CreateAsset(UUID assetUuid, SceneObjectGroup sog) { - AssetBase asset = new AssetBase(assetUuid, assetUuid.ToString(), (sbyte)AssetType.Object, sog.OwnerID.ToString()); - asset.Data = Encoding.ASCII.GetBytes(SceneObjectSerializer.ToXml2Format(sog)); - return asset; + return CreateAsset( + assetUuid, + AssetType.Object, + Encoding.ASCII.GetBytes(SceneObjectSerializer.ToXml2Format(sog)), + sog.OwnerID); } } } diff --git a/OpenSim/Tests/Common/Setup/SceneSetupHelpers.cs b/OpenSim/Tests/Common/Setup/SceneSetupHelpers.cs index 864e2aa7c3..2756324a43 100644 --- a/OpenSim/Tests/Common/Setup/SceneSetupHelpers.cs +++ b/OpenSim/Tests/Common/Setup/SceneSetupHelpers.cs @@ -32,7 +32,6 @@ using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; - using OpenSim.Framework.Console; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; @@ -43,6 +42,7 @@ using OpenSim.Region.Framework.Scenes; using OpenSim.Region.CoreModules.Agent.Capabilities; using OpenSim.Region.CoreModules.Avatar.Gods; using OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset; +using OpenSim.Region.CoreModules.ServiceConnectorsOut.Authentication; using OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory; using OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid; using OpenSim.Region.CoreModules.ServiceConnectorsOut.UserAccounts; @@ -59,6 +59,7 @@ namespace OpenSim.Tests.Common.Setup // These static variables in order to allow regions to be linked by shared modules and same // CommunicationsManager. private static ISharedRegionModule m_assetService = null; +// private static ISharedRegionModule m_authenticationService = null; private static ISharedRegionModule m_inventoryService = null; private static ISharedRegionModule m_gridService = null; private static ISharedRegionModule m_userAccountService = null; @@ -115,7 +116,6 @@ namespace OpenSim.Tests.Common.Setup return SetupScene(name, id, x, y,""); } - /// /// Set up a scene. If it's more then one scene, use the same CommunicationsManager to link regions /// or a different, to get a brand new scene with new shared region modules. @@ -142,7 +142,7 @@ namespace OpenSim.Tests.Common.Setup //{ // System.Console.WriteLine("Starting a brand new scene"); // newScene = true; - // MainConsole.Instance = new LocalConsole("TEST PROMPT"); + MainConsole.Instance = new MockConsole("TEST PROMPT"); // MainServer.Instance = new BaseHttpServer(980); // commsManager = cm; //} @@ -179,6 +179,9 @@ namespace OpenSim.Tests.Common.Setup StartAssetService(testScene, true); else StartAssetService(testScene, false); + + // For now, always started a 'real' authenication service + StartAuthenticationService(testScene, true); if (realServices.Contains("inventory")) StartInventoryService(testScene, true); @@ -204,7 +207,7 @@ namespace OpenSim.Tests.Common.Setup m_inventoryService.PostInitialise(); m_assetService.PostInitialise(); m_userAccountService.PostInitialise(); - + testScene.RegionInfo.EstateSettings.EstateOwner = UUID.Random(); testScene.SetModuleInterfaces(); testScene.LandChannel = new TestLandChannel(testScene); @@ -238,13 +241,34 @@ namespace OpenSim.Tests.Common.Setup else config.Configs["AssetService"].Set("LocalServiceModule", "OpenSim.Tests.Common.dll:MockAssetService"); config.Configs["AssetService"].Set("StorageProvider", "OpenSim.Tests.Common.dll"); - assetService.Initialise(config); + assetService.Initialise(config); assetService.AddRegion(testScene); assetService.RegionLoaded(testScene); testScene.AddRegionModule(assetService.Name, assetService); m_assetService = assetService; } + private static void StartAuthenticationService(Scene testScene, bool real) + { + ISharedRegionModule service = new LocalAuthenticationServicesConnector(); + IConfigSource config = new IniConfigSource(); + config.AddConfig("Modules"); + config.AddConfig("AuthenticationService"); + config.Configs["Modules"].Set("AuthenticationServices", "LocalAuthenticationServicesConnector"); + if (real) + config.Configs["AuthenticationService"].Set( + "LocalServiceModule", "OpenSim.Services.AuthenticationService.dll:PasswordAuthenticationService"); + else + config.Configs["AuthenticationService"].Set( + "LocalServiceModule", "OpenSim.Tests.Common.dll:MockuthenticationService"); + config.Configs["AuthenticationService"].Set("StorageProvider", "OpenSim.Data.Null.dll"); + service.Initialise(config); + service.AddRegion(testScene); + service.RegionLoaded(testScene); + testScene.AddRegionModule(service.Name, service); + //m_authenticationService = service; + } + private static void StartInventoryService(Scene testScene, bool real) { ISharedRegionModule inventoryService = new LocalInventoryServicesConnector(); diff --git a/OpenSim/Tests/Common/Setup/UserProfileTestUtils.cs b/OpenSim/Tests/Common/Setup/UserProfileTestUtils.cs index cd61fa6d2d..e6a78182b2 100644 --- a/OpenSim/Tests/Common/Setup/UserProfileTestUtils.cs +++ b/OpenSim/Tests/Common/Setup/UserProfileTestUtils.cs @@ -27,7 +27,8 @@ using OpenMetaverse; using OpenSim.Framework.Communications; - +using OpenSim.Region.Framework.Scenes; +using OpenSim.Services.Interfaces; namespace OpenSim.Tests.Common.Setup { @@ -36,85 +37,99 @@ namespace OpenSim.Tests.Common.Setup /// public static class UserProfileTestUtils { - // REFACTORING PROBLEM - // This needs to be rewritten +// /// +// /// Create a test user with a standard inventory +// /// +// /// +// /// +// /// Callback to invoke when inventory has been loaded. This is required because +// /// loading may be asynchronous, even on standalone +// /// +// /// +// public static CachedUserInfo CreateUserWithInventory( +// CommunicationsManager commsManager, OnInventoryReceivedDelegate callback) +// { +// UUID userId = UUID.Parse("00000000-0000-0000-0000-000000000099"); +// return CreateUserWithInventory(commsManager, userId, callback); +// } +// +// /// +// /// Create a test user with a standard inventory +// /// +// /// +// /// User ID +// /// +// /// Callback to invoke when inventory has been loaded. This is required because +// /// loading may be asynchronous, even on standalone +// /// +// /// +// public static CachedUserInfo CreateUserWithInventory( +// CommunicationsManager commsManager, UUID userId, OnInventoryReceivedDelegate callback) +// { +// return CreateUserWithInventory(commsManager, "Bill", "Bailey", userId, callback); +// } +// +// /// +// /// Create a test user with a standard inventory +// /// +// /// +// /// First name of user +// /// Last name of user +// /// User ID +// /// +// /// Callback to invoke when inventory has been loaded. This is required because +// /// loading may be asynchronous, even on standalone +// /// +// /// +// public static CachedUserInfo CreateUserWithInventory( +// CommunicationsManager commsManager, string firstName, string lastName, +// UUID userId, OnInventoryReceivedDelegate callback) +// { +// return CreateUserWithInventory(commsManager, firstName, lastName, "troll", userId, callback); +// } +// +// /// +// /// Create a test user with a standard inventory +// /// +// /// +// /// First name of user +// /// Last name of user +// /// Password +// /// User ID +// /// +// /// Callback to invoke when inventory has been loaded. This is required because +// /// loading may be asynchronous, even on standalone +// /// +// /// +// public static CachedUserInfo CreateUserWithInventory( +// CommunicationsManager commsManager, string firstName, string lastName, string password, +// UUID userId, OnInventoryReceivedDelegate callback) +// { +// LocalUserServices lus = (LocalUserServices)commsManager.UserService; +// lus.AddUser(firstName, lastName, password, "bill@bailey.com", 1000, 1000, userId); +// +// CachedUserInfo userInfo = commsManager.UserProfileCacheService.GetUserDetails(userId); +// userInfo.OnInventoryReceived += callback; +// userInfo.FetchInventory(); +// +// return userInfo; +// } - ///// - ///// Create a test user with a standard inventory - ///// - ///// - ///// - ///// Callback to invoke when inventory has been loaded. This is required because - ///// loading may be asynchronous, even on standalone - ///// - ///// - //public static CachedUserInfo CreateUserWithInventory( - // CommunicationsManager commsManager, OnInventoryReceivedDelegate callback) - //{ - // UUID userId = UUID.Parse("00000000-0000-0000-0000-000000000099"); - // return CreateUserWithInventory(commsManager, userId, callback); - //} - - ///// - ///// Create a test user with a standard inventory - ///// - ///// - ///// User ID - ///// - ///// Callback to invoke when inventory has been loaded. This is required because - ///// loading may be asynchronous, even on standalone - ///// - ///// - //public static CachedUserInfo CreateUserWithInventory( - // CommunicationsManager commsManager, UUID userId, OnInventoryReceivedDelegate callback) - //{ - // return CreateUserWithInventory(commsManager, "Bill", "Bailey", userId, callback); - //} + public static UserAccount CreateUserWithInventory(Scene scene) + { + return CreateUserWithInventory( + scene, "Bill", "Bailey", UUID.Parse("00000000-0000-0000-0000-000000000099"), "troll"); + } - ///// - ///// Create a test user with a standard inventory - ///// - ///// - ///// First name of user - ///// Last name of user - ///// User ID - ///// - ///// Callback to invoke when inventory has been loaded. This is required because - ///// loading may be asynchronous, even on standalone - ///// - ///// - //public static CachedUserInfo CreateUserWithInventory( - // CommunicationsManager commsManager, string firstName, string lastName, - // UUID userId, OnInventoryReceivedDelegate callback) - //{ - // return CreateUserWithInventory(commsManager, firstName, lastName, "troll", userId, callback); - //} + public static UserAccount CreateUserWithInventory( + Scene scene, string firstName, string lastName, UUID userId, string pw) + { + UserAccount ua = new UserAccount(userId) { FirstName = firstName, LastName = lastName }; + scene.UserAccountService.StoreUserAccount(ua); + scene.InventoryService.CreateUserInventory(ua.PrincipalID); + scene.AuthenticationService.SetPassword(ua.PrincipalID, pw); - ///// - ///// Create a test user with a standard inventory - ///// - ///// - ///// First name of user - ///// Last name of user - ///// Password - ///// User ID - ///// - ///// Callback to invoke when inventory has been loaded. This is required because - ///// loading may be asynchronous, even on standalone - ///// - ///// - //public static CachedUserInfo CreateUserWithInventory( - // CommunicationsManager commsManager, string firstName, string lastName, string password, - // UUID userId, OnInventoryReceivedDelegate callback) - //{ - // LocalUserServices lus = (LocalUserServices)commsManager.UserService; - // lus.AddUser(firstName, lastName, password, "bill@bailey.com", 1000, 1000, userId); - - // CachedUserInfo userInfo = commsManager.UserProfileCacheService.GetUserDetails(userId); - // userInfo.OnInventoryReceived += callback; - // userInfo.FetchInventory(); - - // return userInfo; - //} + return ua; + } } -} +} \ No newline at end of file diff --git a/README.txt b/README.txt index f1a71beadf..e19e58ecad 100644 --- a/README.txt +++ b/README.txt @@ -1,6 +1,6 @@ Welcome to OpenSim! -== OVERVIEW == +=== OVERVIEW === OpenSim is a BSD Licensed Open Source project to develop a functioning virtual worlds server platform capable of supporting multiple clients @@ -10,12 +10,12 @@ C#, and can run under Mono or the Microsoft .NET runtimes. This is considered an alpha release. Some stuff works, a lot doesn't. If it breaks, you get to keep *both* pieces. -== Compiling OpenSim == +=== Compiling OpenSim === Please see BUILDING.txt if you downloaded a source distribution and need to build OpenSim before running it. -== Running OpenSim on Windows == +=== Running OpenSim on Windows === We recommend that you run OpenSim from a command prompt on Windows in order to capture any errors, though you can also run it by double-clicking @@ -28,7 +28,7 @@ To run OpenSim from a command prompt Now see the "Configuring OpenSim" section -== Running OpenSim on Linux == +=== Running OpenSim on Linux === You will need Mono >= 2.4.2 to run OpenSim. On some Linux distributions you may need to install additional packages. See http://opensimulator.org/wiki/Dependencies @@ -41,7 +41,7 @@ To run OpenSim, from the unpacked distribution type: Now see the "Configuring OpenSim" section -== Configuring OpenSim == +=== Configuring OpenSim === When OpenSim starts for the first time, you will be prompted with a series of questions that look something like: @@ -69,14 +69,14 @@ Helpful resources: * http://opensimulator.org/wiki/Configuring_Regions * http://opensimulator.org/wiki/Mysql-config -== Connecting to your OpenSim == +=== Connecting to your OpenSim === By default your sim will be running on http://127.0.0.1:9000. To use your OpenSim add -loginuri http://127.0.0.1:9000 to your second life client (running on the same machine as your OpenSim). To login, use the same avatar details that you gave to the "create user" console command. -== Bug reports == +=== Bug reports === In the likely event of bugs biting you (err, your OpenSim) we encourage you to see whether the problem has already been reported on @@ -97,10 +97,11 @@ mantis"). Useful information to include: mono --debug OpenSim.exe -== More Information on OpenSim == +=== More Information on OpenSim === More extensive information on building, running, and configuring OpenSim, as well as how to report bugs, and participate in the OpenSim project can always be found at http://opensimulator.org. Thanks for trying OpenSim, we hope it is a pleasant experience. + \ No newline at end of file diff --git a/bin/CSJ2K.dll b/bin/CSJ2K.dll index 31e0d59d54..238291f7e7 100644 Binary files a/bin/CSJ2K.dll and b/bin/CSJ2K.dll differ diff --git a/bin/Mono.Data.Sqlite.dll b/bin/Mono.Data.Sqlite.dll new file mode 100644 index 0000000000..4f69e0d4af Binary files /dev/null and b/bin/Mono.Data.Sqlite.dll differ diff --git a/bin/MySql.Data.dll b/bin/MySql.Data.dll index a94dd3def8..7aa95ec345 100644 Binary files a/bin/MySql.Data.dll and b/bin/MySql.Data.dll differ diff --git a/bin/OpenSim.ini.example b/bin/OpenSim.ini.example index 06306885db..2a70e9668e 100644 --- a/bin/OpenSim.ini.example +++ b/bin/OpenSim.ini.example @@ -87,9 +87,6 @@ ; YOU HAVE BEEN WARNED!!! TrustBinaries = false - ; How many prims to send to each avatar in the scene on each Update() - ; MaxPrimsPerFrame = 200 - ; Combine all contiguous regions into one large region ; Order your regions from South to North, West to East in your regions.ini and then set this to true ; Warning! Don't use this with regions that have existing content!, This will likely break them @@ -112,9 +109,15 @@ ;storage_plugin = "OpenSim.Data.Null.dll" ; --- To use sqlite as region storage: - ; NOTE: SQLite and OpenSim are not functioning properly with Mono 2.4.3 or greater. - ; If you are using Mono you probably should be using MySQL + ; + ; PLEASE NOTE: Unfortunately, the current SQLite database plugin (necessary to use SQLite with Mono on Linux) is + ; not compatible with the sqlite3 library installed on Mac OSX. If you're using Mono 2.4 you can still use the old sqlite + ; library by uncommenting the SQLiteLegacy.dll storage plugin (and commenting out SQLite.dll). Unfortunately, the older library + ; will not work with Mono 2.6 on Mac OSX so you will either need to replace the OSX sqlite3 system library or use MySQL instead + ; + ; You will also need to do the same thing in config-include/StandaloneCommon.ini if you are running in standalone mode storage_plugin = "OpenSim.Data.SQLite.dll" + ;storage_plugin = "OpenSim.Data.SQLiteLegacy.dll" storage_connection_string="URI=file:OpenSim.db,version=3"; ; --- To use MySQL storage, supply your own connection string (this is only an example): @@ -588,6 +591,10 @@ [RemoteAdmin] enabled = false + + ; Set this to a nonzero value to have remote admin use a different port + port = 0 + access_password = unknown ; set this variable to true if you want the create_region XmlRpc @@ -972,6 +979,12 @@ ; Comma separated list of UUIDS allows the function for that list of UUIDS ; Allow_osSetRegionWaterHeight = 888760cb-a3cf-43ac-8ea4-8732fd3ee2bb + ; You can also use script creators as the uuid + ; Creators_osSetRegionWaterHeight = , ... + + ; If both Allow_ and Creators_ are given, effective permissions + ; are the union of the two. + ; Allow for llCreateLink and llBreakLink to work without asking for permission ; only enable this in a trusted environment otherwise you may be subject to hijacking ; AutomaticLinkPermission = false @@ -1228,11 +1241,6 @@ ;; These defaults allow OpenSim to work out of the box with ;; zero configuration ;; -[DatabaseService] - ;; default standalone, overridable in StandaloneCommon.ini - StorageProvider = "OpenSim.Data.SQLite.dll" - - [AssetService] DefaultAssetLoader = "OpenSim.Framework.AssetLoader.Filesystem.dll" AssetLoaderArgs = "assets/AssetSets.xml" diff --git a/bin/OpenSim.Server.HG.ini.example b/bin/Robust.HG.ini.example similarity index 85% rename from bin/OpenSim.Server.HG.ini.example rename to bin/Robust.HG.ini.example index 5e3f9a75ef..9af1e4cdf3 100644 --- a/bin/OpenSim.Server.HG.ini.example +++ b/bin/Robust.HG.ini.example @@ -11,7 +11,7 @@ ;; [Startup] -ServiceConnectors = "8003/OpenSim.Server.Handlers.dll:AssetServiceConnector,8003/OpenSim.Server.Handlers.dll:InventoryServiceInConnector,8002/OpenSim.Server.Handlers.dll:FreeswitchServerConnector,8003/OpenSim.Server.Handlers.dll:GridServiceConnector,8003/OpenSim.Server.Handlers.dll:GridInfoServerInConnector,8003/OpenSim.Server.Handlers.dll:AuthenticationServiceConnector,8002/OpenSim.Server.Handlers.dll:OpenIdServerConnector,8003/OpenSim.Server.Handlers.dll:AvatarServiceConnector,8002/OpenSim.Server.Handlers.dll:LLLoginServiceInConnector,8003/OpenSim.Server.Handlers.dll:PresenceServiceConnector,8003/OpenSim.Server.Handlers.dll:UserAccountServiceConnector,8003/OpenSim.Server.Handlers.dll:FriendsServiceConnector,8002/OpenSim.Server.Handlers.dll:GatekeeperServiceInConnector,8002/OpenSim.Server.Handlers.dll:UserAgentServerConnector,HGInventoryService@8002/OpenSim.Server.Handlers.dll:HGInventoryServiceInConnector,8002/OpenSim.Server.Handlers.dll:AssetServiceConnector" +ServiceConnectors = "8003/OpenSim.Server.Handlers.dll:AssetServiceConnector,8003/OpenSim.Server.Handlers.dll:XInventoryServiceInConnector,8002/OpenSim.Server.Handlers.dll:FreeswitchServerConnector,8003/OpenSim.Server.Handlers.dll:GridServiceConnector,8003/OpenSim.Server.Handlers.dll:GridInfoServerInConnector,8003/OpenSim.Server.Handlers.dll:AuthenticationServiceConnector,8002/OpenSim.Server.Handlers.dll:OpenIdServerConnector,8003/OpenSim.Server.Handlers.dll:AvatarServiceConnector,8002/OpenSim.Server.Handlers.dll:LLLoginServiceInConnector,8003/OpenSim.Server.Handlers.dll:PresenceServiceConnector,8003/OpenSim.Server.Handlers.dll:UserAccountServiceConnector,8003/OpenSim.Server.Handlers.dll:GridUserServiceConnector,8003/OpenSim.Server.Handlers.dll:FriendsServiceConnector,8002/OpenSim.Server.Handlers.dll:GatekeeperServiceInConnector,8002/OpenSim.Server.Handlers.dll:UserAgentServerConnector,HGInventoryService@8002/OpenSim.Server.Handlers.dll:XInventoryInConnector,8002/OpenSim.Server.Handlers.dll:AssetServiceConnector" ; * This is common for all services, it's the network setup for the entire ; * server instance, if none if specified above @@ -44,8 +44,7 @@ ServiceConnectors = "8003/OpenSim.Server.Handlers.dll:AssetServiceConnector,8003 ; * the function of the legacy inventory server ; * [InventoryService] - LocalServiceModule = "OpenSim.Services.InventoryService.dll:InventoryService" - SessionAuthentication = "false" + LocalServiceModule = "OpenSim.Services.InventoryService.dll:XInventoryService" ; * This is the new style grid service. ; * "Realm" is the table that is used for user lookup. @@ -92,7 +91,11 @@ ServiceConnectors = "8003/OpenSim.Server.Handlers.dll:AssetServiceConnector,8003 AuthenticationService = "OpenSim.Services.AuthenticationService.dll:PasswordAuthenticationService" PresenceService = "OpenSim.Services.PresenceService.dll:PresenceService" GridService = "OpenSim.Services.GridService.dll:GridService" - InventoryService = "OpenSim.Services.InventoryService.dll:InventoryService" + InventoryService = "OpenSim.Services.InventoryService.dll:XInventoryService" + +[GridUserService] + ; for the server connector + LocalServiceModule = "OpenSim.Services.UserAccountService.dll:GridUserService" [PresenceService] ; for the server connector @@ -115,8 +118,9 @@ ServiceConnectors = "8003/OpenSim.Server.Handlers.dll:AssetServiceConnector,8003 LocalServiceModule = "OpenSim.Services.LLLoginService.dll:LLLoginService" ; for the service UserAccountService = "OpenSim.Services.UserAccountService.dll:UserAccountService" + GridUserService = "OpenSim.Services.UserAccountService.dll:GridUserService" AuthenticationService = "OpenSim.Services.AuthenticationService.dll:PasswordAuthenticationService" - InventoryService = "OpenSim.Services.InventoryService.dll:InventoryService" + InventoryService = "OpenSim.Services.InventoryService.dll:XInventoryService" AvatarService = "OpenSim.Services.AvatarService.dll:AvatarService" PresenceService = "OpenSim.Services.PresenceService.dll:PresenceService" GridService = "OpenSim.Services.GridService.dll:GridService" @@ -126,6 +130,8 @@ ServiceConnectors = "8003/OpenSim.Server.Handlers.dll:AssetServiceConnector,8003 FriendsService = "OpenSim.Services.FriendsService.dll:FriendsService" WelcomeMessage = "Welcome, Avatar!" + AllowRemoteSetLoginLevel = "false" + ; Defaults for the users, if none is specified in the useraccounts table entry (ServiceURLs) ; CHANGE THIS HomeURI = "http://127.0.0.1:8002" @@ -195,7 +201,7 @@ ServiceConnectors = "8003/OpenSim.Server.Handlers.dll:AssetServiceConnector,8003 [UserAgentService] LocalServiceModule = "OpenSim.Services.HypergridService.dll:UserAgentService" ;; for the service - PresenceService = "OpenSim.Services.PresenceService.dll:PresenceService" + GridUserService = "OpenSim.Services.UserAccountService.dll:GridUserService" GridService = "OpenSim.Services.GridService.dll:GridService" ;; The interface that local users get when they are in other grids. diff --git a/bin/OpenSim.Server.exe.config b/bin/Robust.exe.config similarity index 100% rename from bin/OpenSim.Server.exe.config rename to bin/Robust.exe.config diff --git a/bin/OpenSim.Server.ini.example b/bin/Robust.ini.example similarity index 85% rename from bin/OpenSim.Server.ini.example rename to bin/Robust.ini.example index 9bedac6699..f1b91269a7 100644 --- a/bin/OpenSim.Server.ini.example +++ b/bin/Robust.ini.example @@ -11,7 +11,7 @@ ; * [Startup] -ServiceConnectors = "8003/OpenSim.Server.Handlers.dll:AssetServiceConnector,8003/OpenSim.Server.Handlers.dll:InventoryServiceInConnector,8002/OpenSim.Server.Handlers.dll:FreeswitchServerConnector,8003/OpenSim.Server.Handlers.dll:GridServiceConnector,8002/OpenSim.Server.Handlers.dll:GridInfoServerInConnector,8003/OpenSim.Server.Handlers.dll:AuthenticationServiceConnector,8002/OpenSim.Server.Handlers.dll:OpenIdServerConnector,8003/OpenSim.Server.Handlers.dll:AvatarServiceConnector,8002/OpenSim.Server.Handlers.dll:LLLoginServiceInConnector,8003/OpenSim.Server.Handlers.dll:PresenceServiceConnector,8003/OpenSim.Server.Handlers.dll:UserAccountServiceConnector,8003/OpenSim.Server.Handlers.dll:FriendsServiceConnector" +ServiceConnectors = "8003/OpenSim.Server.Handlers.dll:AssetServiceConnector,8003/OpenSim.Server.Handlers.dll:XInventoryInConnector,8002/OpenSim.Server.Handlers.dll:FreeswitchServerConnector,8003/OpenSim.Server.Handlers.dll:GridServiceConnector,8002/OpenSim.Server.Handlers.dll:GridInfoServerInConnector,8003/OpenSim.Server.Handlers.dll:AuthenticationServiceConnector,8002/OpenSim.Server.Handlers.dll:OpenIdServerConnector,8003/OpenSim.Server.Handlers.dll:AvatarServiceConnector,8002/OpenSim.Server.Handlers.dll:LLLoginServiceInConnector,8003/OpenSim.Server.Handlers.dll:PresenceServiceConnector,8003/OpenSim.Server.Handlers.dll:UserAccountServiceConnector,8003/OpenSim.Server.Handlers.dll:GridUserServiceConnector,8003/OpenSim.Server.Handlers.dll:FriendsServiceConnector" ; * This is common for all services, it's the network setup for the entire ; * server instance, if none if specified above @@ -40,13 +40,13 @@ ServiceConnectors = "8003/OpenSim.Server.Handlers.dll:AssetServiceConnector,8003 LocalServiceModule = "OpenSim.Services.AssetService.dll:AssetService" DefaultAssetLoader = "OpenSim.Framework.AssetLoader.Filesystem.dll" AssetLoaderArgs = "assets/AssetSets.xml" + AllowRemoteDelete = "false" ; * This configuration loads the inventory server modules. It duplicates ; * the function of the legacy inventory server ; * [InventoryService] - LocalServiceModule = "OpenSim.Services.InventoryService.dll:InventoryService" - SessionAuthentication = "false" + LocalServiceModule = "OpenSim.Services.InventoryService.dll:XInventoryService" ; * This is the new style grid service. ; * "Realm" is the table that is used for user lookup. @@ -94,7 +94,11 @@ ServiceConnectors = "8003/OpenSim.Server.Handlers.dll:AssetServiceConnector,8003 AuthenticationService = "OpenSim.Services.AuthenticationService.dll:PasswordAuthenticationService" PresenceService = "OpenSim.Services.PresenceService.dll:PresenceService" GridService = "OpenSim.Services.GridService.dll:GridService" - InventoryService = "OpenSim.Services.InventoryService.dll:InventoryService" + InventoryService = "OpenSim.Services.InventoryService.dll:XInventoryService" + +[GridUserService] + ; for the server connector + LocalServiceModule = "OpenSim.Services.UserAccountService.dll:GridUserService" [PresenceService] ; for the server connector @@ -117,8 +121,9 @@ ServiceConnectors = "8003/OpenSim.Server.Handlers.dll:AssetServiceConnector,8003 LocalServiceModule = "OpenSim.Services.LLLoginService.dll:LLLoginService" ; for the service UserAccountService = "OpenSim.Services.UserAccountService.dll:UserAccountService" + GridUserService = "OpenSim.Services.UserAccountService.dll:GridUserService" AuthenticationService = "OpenSim.Services.AuthenticationService.dll:PasswordAuthenticationService" - InventoryService = "OpenSim.Services.InventoryService.dll:InventoryService" + InventoryService = "OpenSim.Services.InventoryService.dll:XInventoryService" AvatarService = "OpenSim.Services.AvatarService.dll:AvatarService" PresenceService = "OpenSim.Services.PresenceService.dll:PresenceService" GridService = "OpenSim.Services.GridService.dll:GridService" @@ -127,6 +132,7 @@ ServiceConnectors = "8003/OpenSim.Server.Handlers.dll:AssetServiceConnector,8003 FriendsService = "OpenSim.Services.FriendsService.dll:FriendsService" WelcomeMessage = "Welcome, Avatar!" + AllowRemoteSetLoginLevel = "false" [GridInfoService] diff --git a/bin/config-include/Grid.ini b/bin/config-include/Grid.ini index 9dff325749..9a75f19845 100644 --- a/bin/config-include/Grid.ini +++ b/bin/config-include/Grid.ini @@ -8,21 +8,24 @@ Include-Common = "config-include/GridCommon.ini" [Modules] - AssetServices = "RemoteAssetServicesConnector" - InventoryServices = "RemoteInventoryServicesConnector" - GridServices = "RemoteGridServicesConnector" - AvatarServices = "RemoteAvatarServicesConnector" - NeighbourServices = "RemoteNeighbourServicesConnector" - AuthenticationServices = "RemoteAuthenticationServicesConnector" - PresenceServices = "RemotePresenceServicesConnector" - UserAccountServices = "RemoteUserAccountServicesConnector" - SimulationServices = "RemoteSimulationConnectorModule" - EntityTransferModule = "BasicEntityTransferModule" - InventoryAccessModule = "BasicInventoryAccessModule" - LandServiceInConnector = true - NeighbourServiceInConnector = true - SimulationServiceInConnector = true - LibraryModule = true + AssetServices = "RemoteAssetServicesConnector" + InventoryServices = "RemoteXInventoryServicesConnector" + GridServices = "RemoteGridServicesConnector" + AvatarServices = "RemoteAvatarServicesConnector" + NeighbourServices = "RemoteNeighbourServicesConnector" + AuthenticationServices = "RemoteAuthenticationServicesConnector" + AuthorizationServices = "RemoteAuthorizationServicesConnector" + PresenceServices = "RemotePresenceServicesConnector" + UserAccountServices = "RemoteUserAccountServicesConnector" + GridUserServices = "RemoteGridUserServicesConnector" + SimulationServices = "RemoteSimulationConnectorModule" + EntityTransferModule = "BasicEntityTransferModule" + InventoryAccessModule = "BasicInventoryAccessModule" + + LandServiceInConnector = true + NeighbourServiceInConnector = true + SimulationServiceInConnector = true + LibraryModule = true [GridService] diff --git a/bin/config-include/GridCommon.ini.example b/bin/config-include/GridCommon.ini.example index 6e27694cd6..88ac5e2dbf 100644 --- a/bin/config-include/GridCommon.ini.example +++ b/bin/config-include/GridCommon.ini.example @@ -40,6 +40,12 @@ ; UserAccountServerURI = "http://mygridserver.com:8003" +[GridUserService] + ; + ; change this to your grid-wide user accounts server + ; + GridUserServerURI = "http://mygridserver.com:8003" + [AuthenticationService] ; ; change this to your grid-wide authentication server diff --git a/bin/config-include/GridHypergrid.ini b/bin/config-include/GridHypergrid.ini index b567817cc3..1adc2d8068 100644 --- a/bin/config-include/GridHypergrid.ini +++ b/bin/config-include/GridHypergrid.ini @@ -8,30 +8,31 @@ Include-Common = "config-include/GridCommon.ini" [Modules] - AssetServices = "HGAssetBroker" - InventoryServices = "HGInventoryBroker" - GridServices = "RemoteGridServicesConnector" - AvatarServices = "RemoteAvatarServicesConnector" - NeighbourServices = "RemoteNeighbourServicesConnector" - AuthenticationServices = "RemoteAuthenticationServicesConnector" - AuthorizationServices = "LocalAuthorizationServicesConnector" - PresenceServices = "RemotePresenceServicesConnector" - UserAccountServices = "RemoteUserAccountServicesConnector" - SimulationServices = "RemoteSimulationConnectorModule" - EntityTransferModule = "HGEntityTransferModule" - InventoryAccessModule = "HGInventoryAccessModule" - LandServiceInConnector = true - NeighbourServiceInConnector = true - SimulationServiceInConnector = true - LibraryModule = true + AssetServices = "HGAssetBroker" + InventoryServices = "HGInventoryBroker" + GridServices = "RemoteGridServicesConnector" + AvatarServices = "RemoteAvatarServicesConnector" + NeighbourServices = "RemoteNeighbourServicesConnector" + AuthenticationServices = "RemoteAuthenticationServicesConnector" + AuthorizationServices = "RemoteAuthorizationServicesConnector" + PresenceServices = "RemotePresenceServicesConnector" + UserAccountServices = "RemoteUserAccountServicesConnector" + GridUserServices = "RemoteGridUserServicesConnector" + SimulationServices = "RemoteSimulationConnectorModule" + EntityTransferModule = "HGEntityTransferModule" + InventoryAccessModule = "HGInventoryAccessModule" + + LandServiceInConnector = true + NeighbourServiceInConnector = true + SimulationServiceInConnector = true + LibraryModule = true [AssetService] LocalGridAssetService = "OpenSim.Services.Connectors.dll:AssetServicesConnector" HypergridAssetService = "OpenSim.Services.Connectors.dll:HGAssetServiceConnector" [InventoryService] - LocalGridInventoryService = "OpenSim.Region.CoreModules.dll:RemoteInventoryServicesConnector" - HypergridInventoryService = "OpenSim.Services.Connectors.dll:HGInventoryServiceConnector" + LocalGridInventoryService = "OpenSim.Region.CoreModules.dll:RemoteXInventoryServicesConnector" [GridService] ; RemoteGridServicesConnector instantiates a LocalGridServicesConnector, @@ -41,5 +42,10 @@ AllowHypergridMapSearch = true +[LibraryService] + LocalServiceModule = "OpenSim.Services.InventoryService.dll:LibraryService" + LibraryName = "OpenSim Library" + DefaultLibrary = "./inventory/Libraries.xml" + [Friends] Connector = "OpenSim.Services.Connectors.dll:FriendsServicesConnector" diff --git a/bin/config-include/Standalone.ini b/bin/config-include/Standalone.ini index 92c215498e..6b7dc50b7f 100644 --- a/bin/config-include/Standalone.ini +++ b/bin/config-include/Standalone.ini @@ -17,14 +17,15 @@ AvatarServices = "LocalAvatarServicesConnector" EntityTransferModule = "BasicEntityTransferModule" InventoryAccessModule = "BasicInventoryAccessModule" - LibraryModule = true - LLLoginServiceInConnector = true + + LibraryModule = true + LLLoginServiceInConnector = true [AssetService] LocalServiceModule = "OpenSim.Services.AssetService.dll:AssetService" [InventoryService] - LocalServiceModule = "OpenSim.Services.InventoryService.dll:InventoryService" + LocalServiceModule = "OpenSim.Services.InventoryService.dll:XInventoryService" [LibraryService] LocalServiceModule = "OpenSim.Services.InventoryService.dll:LibraryService" @@ -54,9 +55,9 @@ ;; These are for creating new accounts AuthenticationService = "OpenSim.Services.AuthenticationService.dll:PasswordAuthenticationService" - PresenceService = "OpenSim.Services.PresenceService.dll:PresenceService" + GridUserService = "OpenSim.Services.UserAccountService.dll:GridUserService" GridService = "OpenSim.Services.GridService.dll:GridService" - InventoryService = "OpenSim.Services.InventoryService.dll:InventoryService" + InventoryService = "OpenSim.Services.InventoryService.dll:XInventoryService" [GridUserService] LocalServiceModule = "OpenSim.Services.UserAccountService.dll:GridUserService" @@ -70,8 +71,9 @@ [LoginService] LocalServiceModule = "OpenSim.Services.LLLoginService.dll:LLLoginService" UserAccountService = "OpenSim.Services.UserAccountService.dll:UserAccountService" + GridUserService = "OpenSim.Services.UserAccountService.dll:GridUserService" AuthenticationService = "OpenSim.Services.AuthenticationService.dll:PasswordAuthenticationService" - InventoryService = "OpenSim.Services.InventoryService.dll:InventoryService" + InventoryService = "OpenSim.Services.InventoryService.dll:XInventoryService" PresenceService = "OpenSim.Services.PresenceService.dll:PresenceService" GridService = "OpenSim.Services.GridService.dll:GridService" AvatarService = "OpenSim.Services.AvatarService.dll:AvatarService" diff --git a/bin/config-include/StandaloneCommon.ini.example b/bin/config-include/StandaloneCommon.ini.example index f89c67a779..572c153bef 100644 --- a/bin/config-include/StandaloneCommon.ini.example +++ b/bin/config-include/StandaloneCommon.ini.example @@ -6,10 +6,14 @@ ; ; SQLite - ; Uncomment this line if you want to use sqlite storage Include-Storage = "config-include/storage/SQLiteStandalone.ini"; - ; For MySql. + ; Unfortunately the current SQLite database plugin is not compatible with Mac OSX. You can still use the older + ; legacy sqlite library if you are using Mono 2.4. Please see the notes in OpenSim.ini (search for sqlite) + ; for more details + ;Include-Storage = "config-include/storage/SQLiteLegacyStandalone.ini"; + + ; MySql ; Uncomment these lines if you want to use mysql storage ; Change the connection string to your db details ;StorageProvider = "OpenSim.Data.MySQL.dll" diff --git a/bin/config-include/StandaloneHypergrid.ini b/bin/config-include/StandaloneHypergrid.ini index 1d8e2efe72..52e30e211c 100644 --- a/bin/config-include/StandaloneHypergrid.ini +++ b/bin/config-include/StandaloneHypergrid.ini @@ -5,25 +5,27 @@ ;; [Modules] - AssetServices = "HGAssetBroker" - InventoryServices = "HGInventoryBroker" - NeighbourServices = "LocalNeighbourServicesConnector" - AuthenticationServices = "LocalAuthenticationServicesConnector" - GridServices = "LocalGridServicesConnector" - PresenceServices = "LocalPresenceServicesConnector" - UserAccountServices = "LocalUserAccountServicesConnector" - SimulationServices = "RemoteSimulationConnectorModule" - AvatarServices = "LocalAvatarServicesConnector" - EntityTransferModule = "HGEntityTransferModule" - InventoryAccessModule = "HGInventoryAccessModule" - InventoryServiceInConnector = true - AssetServiceInConnector = true - HypergridServiceInConnector = true - NeighbourServiceInConnector = true - LibraryModule = true - LLLoginServiceInConnector = true - AuthenticationServiceInConnector = true - SimulationServiceInConnector = true + AssetServices = "HGAssetBroker" + InventoryServices = "HGInventoryBroker" + NeighbourServices = "LocalNeighbourServicesConnector" + AuthenticationServices = "LocalAuthenticationServicesConnector" + GridServices = "LocalGridServicesConnector" + PresenceServices = "LocalPresenceServicesConnector" + UserAccountServices = "LocalUserAccountServicesConnector" + GridUserServices = "LocalGridUserServicesConnector" + SimulationServices = "RemoteSimulationConnectorModule" + AvatarServices = "LocalAvatarServicesConnector" + EntityTransferModule = "HGEntityTransferModule" + InventoryAccessModule = "HGInventoryAccessModule" + + InventoryServiceInConnector = true + AssetServiceInConnector = true + HypergridServiceInConnector = true + NeighbourServiceInConnector = true + LibraryModule = true + LLLoginServiceInConnector = true + AuthenticationServiceInConnector = true + SimulationServiceInConnector = true [AssetService] LocalServiceModule = "OpenSim.Services.AssetService.dll:AssetService" @@ -33,15 +35,13 @@ HypergridAssetService = "OpenSim.Services.Connectors.dll:HGAssetServiceConnector" [InventoryService] - LocalServiceModule = "OpenSim.Services.InventoryService.dll:InventoryService" + LocalServiceModule = "OpenSim.Services.InventoryService.dll:XInventoryService" ; For HGInventoryBroker - LocalGridInventoryService = "OpenSim.Services.InventoryService.dll:InventoryService" - HypergridInventoryService = "OpenSim.Services.Connectors.dll:HGInventoryServiceConnector" + LocalGridInventoryService = "OpenSim.Services.InventoryService.dll:XInventoryService" [AvatarService] LocalServiceModule = "OpenSim.Services.AvatarService.dll:AvatarService" - ConnectionString = "URI=file:avatars.db,version=3" [LibraryService] LocalServiceModule = "OpenSim.Services.InventoryService.dll:LibraryService" @@ -53,7 +53,6 @@ [AuthenticationService] LocalServiceModule = "OpenSim.Services.AuthenticationService.dll:PasswordAuthenticationService" - ConnectionString = "URI=file:auth.db,version=3" [GridService] ; LocalGridServicesConnector needs this @@ -69,30 +68,33 @@ [UserAccountService] LocalServiceModule = "OpenSim.Services.UserAccountService.dll:UserAccountService" - ConnectionString = "URI=file:userprofiles.db,version=3" + ;; These are for creating new accounts by the service AuthenticationService = "OpenSim.Services.AuthenticationService.dll:PasswordAuthenticationService" - PresenceService = "OpenSim.Services.PresenceService.dll:PresenceService" + GridUserService = "OpenSim.Services.UserAccountService.dll:GridUserService" GridService = "OpenSim.Services.GridService.dll:GridService" - InventoryService = "OpenSim.Services.InventoryService.dll:InventoryService" + InventoryService = "OpenSim.Services.InventoryService.dll:XInventoryService" + +[GridUserService] + LocalServiceModule = "OpenSim.Services.UserAccountService.dll:GridUserService" [FriendsService] LocalServiceModule = "OpenSim.Services.FriendsService.dll" - ConnectionString = "URI=file:friends.db,version=3" [Friends] Connector = "OpenSim.Services.FriendsService.dll" [LoginService] - LocalServiceModule = "OpenSim.Services.LLLoginService.dll:LLLoginService" - UserAccountService = "OpenSim.Services.UserAccountService.dll:UserAccountService" - UserAgentService = "OpenSim.Services.HypergridService.dll:UserAgentService" - AuthenticationService = "OpenSim.Services.AuthenticationService.dll:PasswordAuthenticationService" - InventoryService = "OpenSim.Services.InventoryService.dll:InventoryService" - PresenceService = "OpenSim.Services.PresenceService.dll:PresenceService" - GridService = "OpenSim.Services.GridService.dll:GridService" - AvatarService = "OpenSim.Services.AvatarService.dll:AvatarService" - FriendsService = "OpenSim.Services.FriendsService.dll:FriendsService" + LocalServiceModule = "OpenSim.Services.LLLoginService.dll:LLLoginService" + UserAccountService = "OpenSim.Services.UserAccountService.dll:UserAccountService" + GridUserService = "OpenSim.Services.UserAccountService.dll:GridUserService" + UserAgentService = "OpenSim.Services.HypergridService.dll:UserAgentService" + AuthenticationService = "OpenSim.Services.AuthenticationService.dll:PasswordAuthenticationService" + InventoryService = "OpenSim.Services.InventoryService.dll:XInventoryService" + PresenceService = "OpenSim.Services.PresenceService.dll:PresenceService" + GridService = "OpenSim.Services.GridService.dll:GridService" + AvatarService = "OpenSim.Services.AvatarService.dll:AvatarService" + FriendsService = "OpenSim.Services.FriendsService.dll:FriendsService" [GatekeeperService] LocalServiceModule = "OpenSim.Services.HypergridService.dll:GatekeeperService" @@ -107,7 +109,7 @@ [UserAgentService] LocalServiceModule = "OpenSim.Services.HypergridService.dll:UserAgentService" ;; for the service - PresenceService = "OpenSim.Services.PresenceService.dll:PresenceService" + GridUserService = "OpenSim.Services.UserAccountService.dll:GridUserService" GridService = "OpenSim.Services.GridService.dll:GridService" ;; The interface that local users get when they are in other grids diff --git a/bin/config-include/storage/SQLiteLegacyStandalone.ini b/bin/config-include/storage/SQLiteLegacyStandalone.ini new file mode 100644 index 0000000000..1d4dd29d60 --- /dev/null +++ b/bin/config-include/storage/SQLiteLegacyStandalone.ini @@ -0,0 +1,16 @@ +; These are the initialization settings for running OpenSim Standalone with an SQLite database + +[DatabaseService] + StorageProvider = "OpenSim.Data.SQLiteLegacy.dll" + +[AvatarService] + ConnectionString = "URI=file:avatars.db,version=3" + +[AuthenticationService] + ConnectionString = "URI=file:auth.db,version=3" + +[UserAccountService] + ConnectionString = "URI=file:userprofiles.db,version=3" + +[FriendsService] + ConnectionString = "URI=file:friends.db,version=3" diff --git a/bin/config-include/storage/SQLiteStandalone.ini b/bin/config-include/storage/SQLiteStandalone.ini index 1ce03578f2..fe814d7022 100644 --- a/bin/config-include/storage/SQLiteStandalone.ini +++ b/bin/config-include/storage/SQLiteStandalone.ini @@ -3,6 +3,11 @@ [DatabaseService] StorageProvider = "OpenSim.Data.SQLite.dll" +[InventoryService] + ;ConnectionString = "URI=file:inventory.db,version=3" + ; if you have a legacy inventory store use the connection string below + ConnectionString = "URI=file:inventory.db,version=3,UseUTF16Encoding=True" + [AvatarService] ConnectionString = "URI=file:avatars.db,version=3" @@ -12,5 +17,9 @@ [UserAccountService] ConnectionString = "URI=file:userprofiles.db,version=3" +[GridUserService] + ConnectionString = "URI=file:griduser.db,version=3" + [FriendsService] ConnectionString = "URI=file:friends.db,version=3" + diff --git a/prebuild.xml b/prebuild.xml index 37e3a98855..0a2abaa3c5 100644 --- a/prebuild.xml +++ b/prebuild.xml @@ -768,7 +768,6 @@ - @@ -1300,7 +1299,7 @@ - + ../../bin/ @@ -1407,7 +1406,6 @@ - @@ -1490,7 +1488,6 @@ - @@ -2142,6 +2139,7 @@ + @@ -2175,11 +2173,12 @@ + - + ../../../bin/ @@ -2212,10 +2211,49 @@ + + + + + ../../../bin/ + + + + + ../../../bin/ + + + + ../../../bin/ + + + + + + + + + + + + + + + + + + + + + + + + + @@ -2377,7 +2415,6 @@ ../../../../../bin/ - @@ -2514,7 +2551,6 @@ - @@ -2785,83 +2821,20 @@ - - - - + - - - - ../../../../bin/ - - - - - ../../../../bin/ - - - - ../../../../bin/ - - - - - - - - - - - - - - - - - + + + + + + - - - - ../../../../bin/ - - - - - ../../../../bin/ - - - - ../../../../bin/ - - - - - - - - - - - - - - - - - - - - - - - @@ -2992,7 +2965,6 @@ - @@ -3056,7 +3028,6 @@ -