Merge branch 'master' of ssh://MyConnection/var/git/opensim

remotes/origin/0.6.7-post-fixes
Teravus Ovares (Dan Olivares) 2009-08-25 16:13:02 -04:00
commit a7917b428a
104 changed files with 1534 additions and 6286 deletions

View File

@ -851,7 +851,9 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory
// Delete the old item // Delete the old item
Rest.InventoryServices.DeleteItem(uri); List<UUID> uuids = new List<UUID>();
uuids.Add(uri.ID);
Rest.InventoryServices.DeleteItems(uri.Owner, uuids);
// Add the new item to the inventory // Add the new item to the inventory
@ -927,7 +929,9 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory
InventoryItemBase item = (InventoryItemBase) InventoryNode; InventoryItemBase item = (InventoryItemBase) InventoryNode;
Rest.Log.DebugFormat("{0} {1}: Item {2} will be deleted", Rest.Log.DebugFormat("{0} {1}: Item {2} will be deleted",
MsgId, rdata.method, rdata.path); MsgId, rdata.method, rdata.path);
Rest.InventoryServices.DeleteItem(item); List<UUID> uuids = new List<UUID>();
uuids.Add(item.ID);
Rest.InventoryServices.DeleteItems(item.Owner, uuids);
rdata.appendStatus(String.Format("<p>Deleted item {0} UUID {1} <p>", item.Name, item.ID)); rdata.appendStatus(String.Format("<p>Deleted item {0} UUID {1} <p>", item.Name, item.ID));
} }

View File

@ -36,15 +36,9 @@ namespace OpenSim.Data
{ {
public abstract class AssetDataBase : IAssetDataPlugin public abstract class AssetDataBase : IAssetDataPlugin
{ {
public virtual AssetBase FetchAsset(UUID uuid) public abstract AssetBase GetAsset(UUID uuid);
{
return FetchStoredAsset(uuid);
}
protected abstract AssetBase FetchStoredAsset(UUID uuid);
public abstract void CreateAsset(AssetBase asset); public abstract void StoreAsset(AssetBase asset);
public abstract void UpdateAsset(AssetBase asset);
public abstract bool ExistsAsset(UUID uuid); public abstract bool ExistsAsset(UUID uuid);
public abstract List<AssetMetadata> FetchAssetMetadataSet(int start, int count); public abstract List<AssetMetadata> FetchAssetMetadataSet(int start, int count);

View File

@ -38,9 +38,8 @@ namespace OpenSim.Data
public abstract RegionProfileData[] GetProfilesInRange(uint Xmin, uint Ymin, uint Xmax, uint Ymax); public abstract RegionProfileData[] GetProfilesInRange(uint Xmin, uint Ymin, uint Xmax, uint Ymax);
public abstract List<RegionProfileData> GetRegionsByName(string namePrefix, uint maxNum); public abstract List<RegionProfileData> GetRegionsByName(string namePrefix, uint maxNum);
public abstract bool AuthenticateSim(UUID UUID, ulong regionHandle, string simrecvkey); public abstract bool AuthenticateSim(UUID UUID, ulong regionHandle, string simrecvkey);
public abstract DataResponse AddProfile(RegionProfileData profile); public abstract DataResponse StoreProfile(RegionProfileData profile);
public abstract ReservationData GetReservationAtPoint(uint x, uint y); public abstract ReservationData GetReservationAtPoint(uint x, uint y);
public abstract DataResponse UpdateProfile(RegionProfileData profile);
public abstract DataResponse DeleteProfile(string uuid); public abstract DataResponse DeleteProfile(string uuid);
public abstract void Initialise(); public abstract void Initialise();

View File

@ -33,9 +33,8 @@ namespace OpenSim.Data
{ {
public interface IAssetDataPlugin : IPlugin public interface IAssetDataPlugin : IPlugin
{ {
AssetBase FetchAsset(UUID uuid); AssetBase GetAsset(UUID uuid);
void CreateAsset(AssetBase asset); void StoreAsset(AssetBase asset);
void UpdateAsset(AssetBase asset);
bool ExistsAsset(UUID uuid); bool ExistsAsset(UUID uuid);
List<AssetMetadata> FetchAssetMetadataSet(int start, int count); List<AssetMetadata> FetchAssetMetadataSet(int start, int count);
void Initialise(string connect); void Initialise(string connect);

View File

@ -99,18 +99,11 @@ namespace OpenSim.Data
bool AuthenticateSim(UUID UUID, ulong regionHandle, string simrecvkey); bool AuthenticateSim(UUID UUID, ulong regionHandle, string simrecvkey);
/// <summary> /// <summary>
/// Adds a new profile to the database /// Adds or updates a profile in the database
/// </summary> /// </summary>
/// <param name="profile">The profile to add</param> /// <param name="profile">The profile to add</param>
/// <returns>RESPONSE_OK if successful, error if not.</returns> /// <returns>RESPONSE_OK if successful, error if not.</returns>
DataResponse AddProfile(RegionProfileData profile); DataResponse StoreProfile(RegionProfileData profile);
/// <summary>
/// Updates a profile in the database
/// </summary>
/// <param name="profile"></param>
/// <returns></returns>
DataResponse UpdateProfile(RegionProfileData profile);
/// <summary> /// <summary>
/// Remove a profile from the database /// Remove a profile from the database

View File

@ -122,7 +122,7 @@ namespace OpenSim.Data.MSSQL
/// </summary> /// </summary>
/// <param name="assetID">the asset UUID</param> /// <param name="assetID">the asset UUID</param>
/// <returns></returns> /// <returns></returns>
override protected AssetBase FetchStoredAsset(UUID assetID) override public AssetBase GetAsset(UUID assetID)
{ {
string sql = "SELECT * FROM assets WHERE id = @id"; string sql = "SELECT * FROM assets WHERE id = @id";
using (AutoClosingSqlCommand command = m_database.Query(sql)) using (AutoClosingSqlCommand command = m_database.Query(sql))
@ -152,7 +152,16 @@ namespace OpenSim.Data.MSSQL
/// Create asset in m_database /// Create asset in m_database
/// </summary> /// </summary>
/// <param name="asset">the asset</param> /// <param name="asset">the asset</param>
override public void CreateAsset(AssetBase 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)) if (ExistsAsset(asset.FullID))
{ {
@ -208,7 +217,7 @@ namespace OpenSim.Data.MSSQL
/// Update asset in m_database /// Update asset in m_database
/// </summary> /// </summary>
/// <param name="asset">the asset</param> /// <param name="asset">the asset</param>
override public void UpdateAsset(AssetBase asset) private void UpdateAsset(AssetBase asset)
{ {
string sql = @"UPDATE assets set id = @id, name = @name, description = @description, assetType = @assetType, string sql = @"UPDATE assets set id = @id, name = @name, description = @description, assetType = @assetType,
local = @local, temporary = @temporary, data = @data local = @local, temporary = @temporary, data = @data
@ -250,7 +259,7 @@ namespace OpenSim.Data.MSSQL
} }
} }
// Commented out since currently unused - this probably should be called in FetchAsset() // Commented out since currently unused - this probably should be called in GetAsset()
// private void UpdateAccessTime(AssetBase asset) // private void UpdateAccessTime(AssetBase asset)
// { // {
// using (AutoClosingSqlCommand cmd = m_database.Query("UPDATE assets SET access_time = @access_time WHERE id=@id")) // using (AutoClosingSqlCommand cmd = m_database.Query("UPDATE assets SET access_time = @access_time WHERE id=@id"))
@ -276,7 +285,7 @@ namespace OpenSim.Data.MSSQL
/// <returns>true if exist.</returns> /// <returns>true if exist.</returns>
override public bool ExistsAsset(UUID uuid) override public bool ExistsAsset(UUID uuid)
{ {
if (FetchAsset(uuid) != null) if (GetAsset(uuid) != null)
{ {
return true; return true;
} }

View File

@ -272,26 +272,23 @@ namespace OpenSim.Data.MSSQL
/// </summary> /// </summary>
/// <param name="profile">The profile to add</param> /// <param name="profile">The profile to add</param>
/// <returns>A dataresponse enum indicating success</returns> /// <returns>A dataresponse enum indicating success</returns>
override public DataResponse AddProfile(RegionProfileData profile) override public DataResponse StoreProfile(RegionProfileData profile)
{ {
if (InsertRegionRow(profile)) if (GetProfileByUUID(profile.UUID) == null)
{ {
return DataResponse.RESPONSE_OK; if (InsertRegionRow(profile))
{
return DataResponse.RESPONSE_OK;
}
}
else
{
if (UpdateRegionRow(profile))
{
return DataResponse.RESPONSE_OK;
}
} }
return DataResponse.RESPONSE_ERROR;
}
/// <summary>
/// Update the specified region in the database
/// </summary>
/// <param name="profile">The profile to update</param>
/// <returns>A dataresponse enum indicating success</returns>
override public DataResponse UpdateProfile(RegionProfileData profile)
{
if (UpdateRegionRow(profile))
{
return DataResponse.RESPONSE_OK;
}
return DataResponse.RESPONSE_ERROR; return DataResponse.RESPONSE_ERROR;
} }

View File

@ -135,7 +135,7 @@ namespace OpenSim.Data.MySQL
/// <param name="assetID">Asset UUID to fetch</param> /// <param name="assetID">Asset UUID to fetch</param>
/// <returns>Return the asset</returns> /// <returns>Return the asset</returns>
/// <remarks>On failure : throw an exception and attempt to reconnect to database</remarks> /// <remarks>On failure : throw an exception and attempt to reconnect to database</remarks>
override protected AssetBase FetchStoredAsset(UUID assetID) override public AssetBase GetAsset(UUID assetID)
{ {
AssetBase asset = null; AssetBase asset = null;
lock (_dbConnection) lock (_dbConnection)
@ -168,7 +168,7 @@ namespace OpenSim.Data.MySQL
} }
asset.Name = (string) dbReader["name"]; asset.Name = (string) dbReader["name"];
asset.Type = (sbyte) dbReader["assetType"]; asset.Type = (sbyte) dbReader["assetType"];
asset.Temporary = (bool)dbReader["temporary"]; asset.Temporary = Convert.ToBoolean(dbReader["temporary"]);
} }
dbReader.Close(); dbReader.Close();
cmd.Dispose(); cmd.Dispose();
@ -192,7 +192,7 @@ namespace OpenSim.Data.MySQL
/// </summary> /// </summary>
/// <param name="asset">Asset UUID to create</param> /// <param name="asset">Asset UUID to create</param>
/// <remarks>On failure : Throw an exception and attempt to reconnect to database</remarks> /// <remarks>On failure : Throw an exception and attempt to reconnect to database</remarks>
override public void CreateAsset(AssetBase asset) override public void StoreAsset(AssetBase asset)
{ {
lock (_dbConnection) lock (_dbConnection)
{ {
@ -284,15 +284,6 @@ namespace OpenSim.Data.MySQL
} }
/// <summary>
/// Update a asset in database, see <see cref="CreateAsset"/>
/// </summary>
/// <param name="asset">Asset UUID to update</param>
override public void UpdateAsset(AssetBase asset)
{
CreateAsset(asset);
}
/// <summary> /// <summary>
/// check if the asset UUID exist in database /// check if the asset UUID exist in database
/// </summary> /// </summary>
@ -368,7 +359,7 @@ namespace OpenSim.Data.MySQL
metadata.Name = (string) dbReader["name"]; metadata.Name = (string) dbReader["name"];
metadata.Description = (string) dbReader["description"]; metadata.Description = (string) dbReader["description"];
metadata.Type = (sbyte) dbReader["assetType"]; metadata.Type = (sbyte) dbReader["assetType"];
metadata.Temporary = (bool) dbReader["temporary"]; // Not sure if this is correct. metadata.Temporary = Convert.ToBoolean(dbReader["temporary"]); // Not sure if this is correct.
metadata.FullID = new UUID((string) dbReader["id"]); metadata.FullID = new UUID((string) dbReader["id"]);
// Current SHA1s are not stored/computed. // Current SHA1s are not stored/computed.

View File

@ -391,7 +391,7 @@ namespace OpenSim.Data.MySQL
/// </summary> /// </summary>
/// <param name="profile">The profile to add</param> /// <param name="profile">The profile to add</param>
/// <returns>Successful?</returns> /// <returns>Successful?</returns>
override public DataResponse AddProfile(RegionProfileData profile) override public DataResponse StoreProfile(RegionProfileData profile)
{ {
MySQLSuperManager dbm = GetLockedConnection(); MySQLSuperManager dbm = GetLockedConnection();
try { try {
@ -407,17 +407,6 @@ namespace OpenSim.Data.MySQL
} }
} }
/// <summary>
/// Update a sim profile
/// </summary>
/// <param name="profile">The profile to update</param>
/// <returns>Sucessful?</returns>
/// <remarks>Same as AddProfile</remarks>
override public DataResponse UpdateProfile(RegionProfileData profile)
{
return AddProfile(profile);
}
/// <summary> /// <summary>
/// Deletes a sim profile from the database /// Deletes a sim profile from the database
/// </summary> /// </summary>

View File

@ -65,30 +65,24 @@ namespace OpenSim.Data.NHibernate
} }
override protected AssetBase FetchStoredAsset(UUID uuid) override public AssetBase GetAsset(UUID uuid)
{ {
return (AssetBase)manager.Get(typeof(AssetBase), uuid); return (AssetBase)manager.Get(typeof(AssetBase), uuid);
} }
private void Save(AssetBase asset) override public void StoreAsset(AssetBase asset)
{ {
AssetBase temp = (AssetBase)manager.Get(typeof(AssetBase), asset.FullID); AssetBase temp = (AssetBase)manager.Get(typeof(AssetBase), asset.FullID);
if (temp == null) if (temp == null)
{ {
m_log.InfoFormat("[NHIBERNATE] inserting asset {0}", asset.FullID);
manager.Insert(asset); manager.Insert(asset);
} }
} else
{
override public void CreateAsset(AssetBase asset) m_log.InfoFormat("[NHIBERNATE] updating asset {0}", asset.FullID);
{ manager.Update(asset);
m_log.InfoFormat("[NHIBERNATE] inserting asset {0}", asset.FullID); }
Save(asset);
}
override public void UpdateAsset(AssetBase asset)
{
m_log.InfoFormat("[NHIBERNATE] updating asset {0}", asset.FullID);
manager.Update(asset);
} }
// private void LogAssetLoad(AssetBase asset) // private void LogAssetLoad(AssetBase asset)
@ -107,7 +101,7 @@ namespace OpenSim.Data.NHibernate
override public bool ExistsAsset(UUID uuid) override public bool ExistsAsset(UUID uuid)
{ {
m_log.InfoFormat("[NHIBERNATE] ExistsAsset: {0}", uuid); m_log.InfoFormat("[NHIBERNATE] ExistsAsset: {0}", uuid);
return (FetchAsset(uuid) != null); return (GetAsset(uuid) != null);
} }
/// <summary> /// <summary>

View File

@ -117,7 +117,7 @@ namespace OpenSim.Data.NHibernate
throw new NotImplementedException(); throw new NotImplementedException();
} }
public override DataResponse AddProfile(RegionProfileData profile) public override DataResponse StoreProfile(RegionProfileData profile)
{ {
if (manager.Get(typeof(RegionProfileData), profile.Uuid) == null) if (manager.Get(typeof(RegionProfileData), profile.Uuid) == null)
{ {
@ -125,22 +125,10 @@ namespace OpenSim.Data.NHibernate
return DataResponse.RESPONSE_OK; return DataResponse.RESPONSE_OK;
} }
else else
{
return DataResponse.RESPONSE_ERROR;
}
}
public override DataResponse UpdateProfile(RegionProfileData profile)
{
if (manager.Get(typeof(RegionProfileData), profile.Uuid) != null)
{ {
manager.Update(profile); manager.Update(profile);
return DataResponse.RESPONSE_OK; return DataResponse.RESPONSE_OK;
} }
else
{
return DataResponse.RESPONSE_ERROR;
}
} }
public override DataResponse DeleteProfile(string uuid) public override DataResponse DeleteProfile(string uuid)

View File

@ -90,7 +90,7 @@ namespace OpenSim.Data.SQLite
/// </summary> /// </summary>
/// <param name="uuid">UUID of ... ?</param> /// <param name="uuid">UUID of ... ?</param>
/// <returns>Asset base</returns> /// <returns>Asset base</returns>
override protected AssetBase FetchStoredAsset(UUID uuid) override public AssetBase GetAsset(UUID uuid)
{ {
lock (this) lock (this)
{ {
@ -119,12 +119,28 @@ namespace OpenSim.Data.SQLite
/// Create an asset /// Create an asset
/// </summary> /// </summary>
/// <param name="asset">Asset Base</param> /// <param name="asset">Asset Base</param>
override public void CreateAsset(AssetBase asset) override public void StoreAsset(AssetBase asset)
{ {
//m_log.Info("[ASSET DB]: Creating Asset " + asset.FullID.ToString()); //m_log.Info("[ASSET DB]: Creating Asset " + asset.FullID.ToString());
if (ExistsAsset(asset.FullID)) if (ExistsAsset(asset.FullID))
{ {
//m_log.Info("[ASSET DB]: Asset exists already, ignoring."); 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 else
{ {
@ -146,31 +162,6 @@ namespace OpenSim.Data.SQLite
} }
} }
/// <summary>
/// Update an asset
/// </summary>
/// <param name="asset"></param>
override public void UpdateAsset(AssetBase asset)
{
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();
}
}
}
/// <summary> /// <summary>
/// Some... logging functionnality /// Some... logging functionnality
/// </summary> /// </summary>

View File

@ -203,7 +203,7 @@ namespace OpenSim.Data.SQLite
/// </summary> /// </summary>
/// <param name="profile">The profile to add</param> /// <param name="profile">The profile to add</param>
/// <returns>A dataresponse enum indicating success</returns> /// <returns>A dataresponse enum indicating success</returns>
override public DataResponse AddProfile(RegionProfileData profile) override public DataResponse StoreProfile(RegionProfileData profile)
{ {
if (database.insertRow(profile)) if (database.insertRow(profile))
{ {
@ -215,17 +215,11 @@ namespace OpenSim.Data.SQLite
} }
} }
override public DataResponse UpdateProfile(RegionProfileData profile) /// <summary>
{
return AddProfile(profile);
}
/// <summary>
/// Deletes a sim profile from the database /// Deletes a sim profile from the database
/// </summary> /// </summary>
/// <param name="uuid">the sim UUID</param> /// <param name="uuid">the sim UUID</param>
/// <returns>Successful?</returns> /// <returns>Successful?</returns>
//public DataResponse DeleteProfile(RegionProfileData profile)
override public DataResponse DeleteProfile(string uuid) override public DataResponse DeleteProfile(string uuid)
{ {
Dictionary<string, string> param = new Dictionary<string, string>(); Dictionary<string, string> param = new Dictionary<string, string>();

View File

@ -628,12 +628,12 @@ namespace OpenSim.Data.SQLite
public InventoryItemBase queryInventoryItem(UUID itemID) public InventoryItemBase queryInventoryItem(UUID itemID)
{ {
return null; return getInventoryItem(itemID);
} }
public InventoryFolderBase queryInventoryFolder(UUID folderID) public InventoryFolderBase queryInventoryFolder(UUID folderID)
{ {
return null; return getInventoryFolder(folderID);
} }
/// <summary> /// <summary>

View File

@ -84,34 +84,34 @@ namespace OpenSim.Data.Tests
scrambler.Scramble(a2); scrambler.Scramble(a2);
scrambler.Scramble(a3); scrambler.Scramble(a3);
db.CreateAsset(a1); db.StoreAsset(a1);
db.CreateAsset(a2); db.StoreAsset(a2);
db.CreateAsset(a3); db.StoreAsset(a3);
AssetBase a1a = db.FetchAsset(uuid1); AssetBase a1a = db.GetAsset(uuid1);
Assert.That(a1a, Constraints.PropertyCompareConstraint(a1)); Assert.That(a1a, Constraints.PropertyCompareConstraint(a1));
AssetBase a2a = db.FetchAsset(uuid2); AssetBase a2a = db.GetAsset(uuid2);
Assert.That(a2a, Constraints.PropertyCompareConstraint(a2)); Assert.That(a2a, Constraints.PropertyCompareConstraint(a2));
AssetBase a3a = db.FetchAsset(uuid3); AssetBase a3a = db.GetAsset(uuid3);
Assert.That(a3a, Constraints.PropertyCompareConstraint(a3)); Assert.That(a3a, Constraints.PropertyCompareConstraint(a3));
scrambler.Scramble(a1a); scrambler.Scramble(a1a);
scrambler.Scramble(a2a); scrambler.Scramble(a2a);
scrambler.Scramble(a3a); scrambler.Scramble(a3a);
db.UpdateAsset(a1a); db.StoreAsset(a1a);
db.UpdateAsset(a2a); db.StoreAsset(a2a);
db.UpdateAsset(a3a); db.StoreAsset(a3a);
AssetBase a1b = db.FetchAsset(uuid1); AssetBase a1b = db.GetAsset(uuid1);
Assert.That(a1b, Constraints.PropertyCompareConstraint(a1a)); Assert.That(a1b, Constraints.PropertyCompareConstraint(a1a));
AssetBase a2b = db.FetchAsset(uuid2); AssetBase a2b = db.GetAsset(uuid2);
Assert.That(a2b, Constraints.PropertyCompareConstraint(a2a)); Assert.That(a2b, Constraints.PropertyCompareConstraint(a2a));
AssetBase a3b = db.FetchAsset(uuid3); AssetBase a3b = db.GetAsset(uuid3);
Assert.That(a3b, Constraints.PropertyCompareConstraint(a3a)); Assert.That(a3b, Constraints.PropertyCompareConstraint(a3a));
Assert.That(db.ExistsAsset(uuid1), Is.True); Assert.That(db.ExistsAsset(uuid1), Is.True);

View File

@ -70,7 +70,7 @@ namespace OpenSim.Data.Tests
reg.Uuid = regionUUID; reg.Uuid = regionUUID;
reg.RegionName = regionName; reg.RegionName = regionName;
db.AddProfile(reg); db.StoreProfile(reg);
return reg; return reg;
} }
@ -120,7 +120,7 @@ namespace OpenSim.Data.Tests
RegionProfileData retreg = db.GetProfileByUUID(region2); RegionProfileData retreg = db.GetProfileByUUID(region2);
retreg.regionName = "Gotham City"; retreg.regionName = "Gotham City";
db.UpdateProfile(retreg); db.StoreProfile(retreg);
retreg = db.GetProfileByUUID(region2); retreg = db.GetProfileByUUID(region2);
Assert.That(retreg.RegionName, Is.EqualTo("Gotham City"), "Assert.That(retreg.RegionName, Is.EqualTo(\"Gotham City\"))"); Assert.That(retreg.RegionName, Is.EqualTo("Gotham City"), "Assert.That(retreg.RegionName, Is.EqualTo(\"Gotham City\"))");
@ -135,13 +135,13 @@ namespace OpenSim.Data.Tests
retreg.RegionName = "Gotham Town"; retreg.RegionName = "Gotham Town";
retreg.Uuid = region1; retreg.Uuid = region1;
db.AddProfile(retreg); db.StoreProfile(retreg);
retreg = db.GetProfileByUUID(region2); retreg = db.GetProfileByUUID(region2);
retreg.RegionName = "Gothan Town"; retreg.RegionName = "Gothan Town";
retreg.Uuid = region3; retreg.Uuid = region3;
db.AddProfile(retreg); db.StoreProfile(retreg);
List<RegionProfileData> listreg = db.GetRegionsByName("Gotham",10); List<RegionProfileData> listreg = db.GetRegionsByName("Gotham",10);

View File

@ -503,7 +503,14 @@ namespace OpenSim.Framework
Owner = new UUID((string)h["owner"]); Owner = new UUID((string)h["owner"]);
Serial = Convert.ToInt32((string)h["serial"]); Serial = Convert.ToInt32((string)h["serial"]);
VisualParams = (byte[])h["visual_params"]; VisualParams = (byte[])h["visual_params"];
Texture = new Primitive.TextureEntry((byte[])h["texture"], 0, ((byte[])h["texture"]).Length);
if (h.Contains("texture"))
{
byte[] te = h["texture"] as byte[];
if (te != null && te.Length > 0)
Texture = new Primitive.TextureEntry(te, 0, te.Length);
}
AvatarHeight = (float)Convert.ToDouble((string)h["avatar_height"]); AvatarHeight = (float)Convert.ToDouble((string)h["avatar_height"]);
m_wearables = new AvatarWearable[MAX_WEARABLES]; m_wearables = new AvatarWearable[MAX_WEARABLES];

View File

@ -653,7 +653,9 @@ namespace OpenSim.Framework.Communications.Cache
if (RootFolder.DeleteItem(item.ID)) if (RootFolder.DeleteItem(item.ID))
{ {
return m_InventoryService.DeleteItem(item); List<UUID> uuids = new List<UUID>();
uuids.Add(itemID);
return m_InventoryService.DeleteItems(this.UserProfile.ID, uuids);
} }
} }
else else

View File

@ -184,7 +184,7 @@ namespace OpenSim.Framework.Communications.Cache
// Commented out for now. The implementation needs to be improved by protecting against race conditions, // Commented out for now. The implementation needs to be improved by protecting against race conditions,
// probably by making sure that the update doesn't use the UserCacheInfo.UserProfile directly (possibly via // probably by making sure that the update doesn't use the UserCacheInfo.UserProfile directly (possibly via
// returning a read only class from the cache). // returning a read only class from the cache).
// public bool UpdateProfile(UserProfileData userProfile) // public bool StoreProfile(UserProfileData userProfile)
// { // {
// lock (m_userProfilesById) // lock (m_userProfilesById)
// { // {

View File

@ -110,14 +110,14 @@ namespace OpenSim.Framework.Communications.Tests
IUserDataPlugin userDataPlugin = commsManager.UserDataPlugin; IUserDataPlugin userDataPlugin = commsManager.UserDataPlugin;
// Check that we can't update info before it exists // Check that we can't update info before it exists
Assert.That(userCacheService.UpdateProfile(newProfile), Is.False); Assert.That(userCacheService.StoreProfile(newProfile), Is.False);
Assert.That(userDataPlugin.GetUserByUUID(userId), Is.Null); Assert.That(userDataPlugin.GetUserByUUID(userId), Is.Null);
// Check that we can update a profile once it exists // Check that we can update a profile once it exists
LocalUserServices lus = (LocalUserServices)commsManager.UserService; LocalUserServices lus = (LocalUserServices)commsManager.UserService;
lus.AddUser(firstName, originalLastName, "pingu", "ted@excellentadventure.com", 1000, 1000, userId); lus.AddUser(firstName, originalLastName, "pingu", "ted@excellentadventure.com", 1000, 1000, userId);
Assert.That(userCacheService.UpdateProfile(newProfile), Is.True); Assert.That(userCacheService.StoreProfile(newProfile), Is.True);
UserProfileData retrievedProfile = userCacheService.GetUserDetails(userId).UserProfile; UserProfileData retrievedProfile = userCacheService.GetUserDetails(userId).UserProfile;
Assert.That(retrievedProfile.SurName, Is.EqualTo(newLastName)); Assert.That(retrievedProfile.SurName, Is.EqualTo(newLastName));
Assert.That(userDataPlugin.GetUserByUUID(userId).SurName, Is.EqualTo(newLastName)); Assert.That(userDataPlugin.GetUserByUUID(userId).SurName, Is.EqualTo(newLastName));

View File

@ -532,6 +532,11 @@ namespace OpenSim.Framework.Communications.Tests
return false; return false;
} }
public bool DeleteFolders(UUID ownerID, List<UUID> ids)
{
return false;
}
public bool PurgeFolder(InventoryFolderBase folder) public bool PurgeFolder(InventoryFolderBase folder)
{ {
return false; return false;
@ -547,7 +552,12 @@ namespace OpenSim.Framework.Communications.Tests
return false; return false;
} }
public bool DeleteItem(InventoryItemBase item) public bool MoveItems(UUID owner, List<InventoryItemBase> items)
{
return false;
}
public bool DeleteItems(UUID owner, List<UUID> items)
{ {
return false; return false;
} }

View File

@ -576,7 +576,7 @@ namespace OpenSim.Framework.Console
public void Prompt() public void Prompt()
{ {
string line = ReadLine(m_defaultPrompt, true, true); string line = ReadLine(m_defaultPrompt + "# ", true, true);
if (line != String.Empty) if (line != String.Empty)
{ {
@ -592,7 +592,7 @@ namespace OpenSim.Framework.Console
public override string ReadLine(string p, bool isCommand, bool e) public override string ReadLine(string p, bool isCommand, bool e)
{ {
System.Console.Write("{0}", prompt); System.Console.Write("{0}", p);
string cmdinput = System.Console.ReadLine(); string cmdinput = System.Console.ReadLine();
if (isCommand) if (isCommand)

View File

@ -48,7 +48,7 @@ namespace OpenSim.Framework.Console
/// </summary> /// </summary>
public string DefaultPrompt public string DefaultPrompt
{ {
set { m_defaultPrompt = value + "# "; } set { m_defaultPrompt = value; }
get { return m_defaultPrompt; } get { return m_defaultPrompt; }
} }
protected string m_defaultPrompt; protected string m_defaultPrompt;
@ -123,7 +123,7 @@ namespace OpenSim.Framework.Console
public virtual string ReadLine(string p, bool isCommand, bool e) public virtual string ReadLine(string p, bool isCommand, bool e)
{ {
System.Console.Write("{0}", prompt); System.Console.Write("{0}", p);
string cmdinput = System.Console.ReadLine(); string cmdinput = System.Console.ReadLine();
return cmdinput; return cmdinput;

View File

@ -217,6 +217,12 @@ namespace OpenSim.Framework.Console
id.AppendChild(xmldoc.CreateTextNode(sessionID.ToString())); id.AppendChild(xmldoc.CreateTextNode(sessionID.ToString()));
rootElement.AppendChild(id); rootElement.AppendChild(id);
XmlElement prompt = xmldoc.CreateElement("", "Prompt", "");
prompt.AppendChild(xmldoc.CreateTextNode(DefaultPrompt));
rootElement.AppendChild(prompt);
rootElement.AppendChild(MainConsole.Instance.Commands.GetXml(xmldoc)); rootElement.AppendChild(MainConsole.Instance.Commands.GetXml(xmldoc));
reply["str_response_string"] = xmldoc.InnerXml; reply["str_response_string"] = xmldoc.InnerXml;

View File

@ -45,6 +45,8 @@ namespace OpenSim.Framework
public string SimSendKey = String.Empty; public string SimSendKey = String.Empty;
public string UserRecvKey = String.Empty; public string UserRecvKey = String.Empty;
public string UserSendKey = String.Empty; public string UserSendKey = String.Empty;
public string ConsoleUser = String.Empty;
public string ConsolePass = String.Empty;
public GridConfig(string description, string filename) public GridConfig(string description, string filename)
{ {
@ -95,6 +97,12 @@ namespace OpenSim.Framework
"Allow regions to register immediately upon grid server startup? true/false", "Allow regions to register immediately upon grid server startup? true/false",
"True", "True",
false); false);
m_configMember.addConfigurationOption("console_user", ConfigurationOption.ConfigurationTypes.TYPE_STRING,
"Remote console access user name [Default: disabled]", "", false);
m_configMember.addConfigurationOption("console_pass", ConfigurationOption.ConfigurationTypes.TYPE_STRING,
"Remote console access password [Default: disabled]", "", false);
} }
public bool handleIncomingConfiguration(string configuration_key, object configuration_result) public bool handleIncomingConfiguration(string configuration_key, object configuration_result)
@ -140,9 +148,15 @@ namespace OpenSim.Framework
case "allow_region_registration": case "allow_region_registration":
AllowRegionRegistration = (bool)configuration_result; AllowRegionRegistration = (bool)configuration_result;
break; break;
case "console_user":
ConsoleUser = (string)configuration_result;
break;
case "console_pass":
ConsolePass = (string)configuration_result;
break;
} }
return true; return true;
} }
} }
} }

View File

@ -254,13 +254,13 @@ namespace OpenSim.Framework
string newName); string newName);
public delegate void MoveInventoryItem( public delegate void MoveInventoryItem(
IClientAPI remoteClient, UUID folderID, UUID itemID, int length, string newName); IClientAPI remoteClient, List<InventoryItemBase> items);
public delegate void RemoveInventoryItem( public delegate void RemoveInventoryItem(
IClientAPI remoteClient, UUID itemID); IClientAPI remoteClient, List<UUID> itemIDs);
public delegate void RemoveInventoryFolder( public delegate void RemoveInventoryFolder(
IClientAPI remoteClient, UUID folderID); IClientAPI remoteClient, List<UUID> folderIDs);
public delegate void RequestAsset(IClientAPI remoteClient, RequestAssetArgs transferRequest); public delegate void RequestAsset(IClientAPI remoteClient, RequestAssetArgs transferRequest);

View File

@ -78,6 +78,12 @@ namespace OpenSim.Framework
ID = id; ID = id;
} }
public InventoryFolderBase(UUID id, UUID owner)
{
ID = id;
Owner = owner;
}
public InventoryFolderBase(UUID id, string name, UUID owner, short type, UUID parent, ushort version) public InventoryFolderBase(UUID id, string name, UUID owner, short type, UUID parent, ushort version)
{ {
ID = id; ID = id;

View File

@ -46,6 +46,8 @@ namespace OpenSim.Framework
public string UserRecvKey = String.Empty; public string UserRecvKey = String.Empty;
public string UserSendKey = String.Empty; public string UserSendKey = String.Empty;
public string UserServerURL = String.Empty; public string UserServerURL = String.Empty;
public string ConsoleUser = String.Empty;
public string ConsolePass = String.Empty;
public MessageServerConfig(string description, string filename) public MessageServerConfig(string description, string filename)
{ {
@ -88,6 +90,12 @@ namespace OpenSim.Framework
"Use SSL? true/false", ConfigSettings.DefaultMessageServerHttpSSL.ToString(), false); "Use SSL? true/false", ConfigSettings.DefaultMessageServerHttpSSL.ToString(), false);
m_configMember.addConfigurationOption("published_ip", ConfigurationOption.ConfigurationTypes.TYPE_STRING, m_configMember.addConfigurationOption("published_ip", ConfigurationOption.ConfigurationTypes.TYPE_STRING,
"My Published IP Address", "127.0.0.1", false); "My Published IP Address", "127.0.0.1", false);
m_configMember.addConfigurationOption("console_user", ConfigurationOption.ConfigurationTypes.TYPE_STRING,
"Remote console access user name [Default: disabled]", "", false);
m_configMember.addConfigurationOption("console_pass", ConfigurationOption.ConfigurationTypes.TYPE_STRING,
"Remote console access password [Default: disabled]", "", false);
} }
public bool handleIncomingConfiguration(string configuration_key, object configuration_result) public bool handleIncomingConfiguration(string configuration_key, object configuration_result)
@ -130,9 +138,15 @@ namespace OpenSim.Framework
case "published_ip": case "published_ip":
MessageServerIP = (string) configuration_result; MessageServerIP = (string) configuration_result;
break; break;
case "console_user":
ConsoleUser = (string)configuration_result;
break;
case "console_pass":
ConsolePass = (string)configuration_result;
break;
} }
return true; return true;
} }
} }
} }

View File

@ -57,7 +57,7 @@ namespace OpenSim.Framework.Servers
protected override AssetBase GetAsset(UUID assetID) protected override AssetBase GetAsset(UUID assetID)
{ {
return m_assetProvider.FetchAsset(assetID); return m_assetProvider.GetAsset(assetID);
} }
} }
} }

View File

@ -75,6 +75,7 @@ namespace OpenSim.Framework.Servers.HttpServer
WebRequest request = WebRequest.Create(requestUrl); WebRequest request = WebRequest.Create(requestUrl);
request.Method = verb; request.Method = verb;
request.ContentType = "text/xml"; request.ContentType = "text/xml";
request.Timeout = 20000;
MemoryStream buffer = new MemoryStream(); MemoryStream buffer = new MemoryStream();
@ -98,7 +99,9 @@ namespace OpenSim.Framework.Servers.HttpServer
{ {
XmlSerializer deserializer = new XmlSerializer(typeof(TResponse)); XmlSerializer deserializer = new XmlSerializer(typeof(TResponse));
deserial = (TResponse)deserializer.Deserialize(resp.GetResponseStream()); deserial = (TResponse)deserializer.Deserialize(resp.GetResponseStream());
resp.Close();
} }
requestStream.Close();
return deserial; return deserial;
} }
} }

View File

@ -62,7 +62,7 @@ namespace OpenSim.Framework.Servers.HttpServer
WebRequest request = WebRequest.Create(requestUrl); WebRequest request = WebRequest.Create(requestUrl);
request.Method = verb; request.Method = verb;
if (verb == "POST") if ((verb == "POST") || (verb == "PUT"))
{ {
request.ContentType = "text/xml"; request.ContentType = "text/xml";

View File

@ -57,7 +57,7 @@ namespace OpenSim.Framework.Servers
AssetBase asset = (AssetBase) xs.Deserialize(request); AssetBase asset = (AssetBase) xs.Deserialize(request);
m_log.InfoFormat("[REST]: Creating asset {0}", asset.FullID); m_log.InfoFormat("[REST]: Creating asset {0}", asset.FullID);
m_assetProvider.CreateAsset(asset); m_assetProvider.StoreAsset(asset);
return new byte[] {}; return new byte[] {};
} }

View File

@ -128,7 +128,7 @@ namespace OpenSim.Framework.Servers.Tests
IAssetDataPlugin assetDataPlugin = new TestAssetDataPlugin(); IAssetDataPlugin assetDataPlugin = new TestAssetDataPlugin();
handler = new GetAssetStreamHandler(assetDataPlugin); handler = new GetAssetStreamHandler(assetDataPlugin);
assetDataPlugin.CreateAsset(asset); assetDataPlugin.StoreAsset(asset);
return asset; return asset;
} }
} }

View File

@ -46,6 +46,8 @@ namespace OpenSim.Framework
public bool HttpSSL = ConfigSettings.DefaultUserServerHttpSSL; public bool HttpSSL = ConfigSettings.DefaultUserServerHttpSSL;
public uint DefaultUserLevel = 0; public uint DefaultUserLevel = 0;
public string LibraryXmlfile = ""; public string LibraryXmlfile = "";
public string ConsoleUser = String.Empty;
public string ConsolePass = String.Empty;
private Uri m_inventoryUrl; private Uri m_inventoryUrl;
@ -155,6 +157,12 @@ namespace OpenSim.Framework
m_configMember.addConfigurationOption("default_loginLevel", ConfigurationOption.ConfigurationTypes.TYPE_UINT32, m_configMember.addConfigurationOption("default_loginLevel", ConfigurationOption.ConfigurationTypes.TYPE_UINT32,
"Minimum Level a user should have to login [0 default]", "0", false); "Minimum Level a user should have to login [0 default]", "0", false);
m_configMember.addConfigurationOption("console_user", ConfigurationOption.ConfigurationTypes.TYPE_STRING,
"Remote console access user name [Default: disabled]", "", false);
m_configMember.addConfigurationOption("console_pass", ConfigurationOption.ConfigurationTypes.TYPE_STRING,
"Remote console access password [Default: disabled]", "", false);
} }
public bool handleIncomingConfiguration(string configuration_key, object configuration_result) public bool handleIncomingConfiguration(string configuration_key, object configuration_result)
@ -209,6 +217,12 @@ namespace OpenSim.Framework
case "library_location": case "library_location":
LibraryXmlfile = (string)configuration_result; LibraryXmlfile = (string)configuration_result;
break; break;
case "console_user":
ConsoleUser = (string)configuration_result;
break;
case "console_pass":
ConsolePass = (string)configuration_result;
break;
} }
return true; return true;

View File

@ -1,98 +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.IO;
using System.Reflection;
using OpenSim.Framework;
using log4net;
using Nini.Config;
namespace OpenSim.Grid.AssetInventoryServer
{
public static class AssetInventoryConfig
{
public const string CONFIG_FILE = "AssetInventoryServer.ini";
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public static IConfigSource LoadConfig()
{
IConfigSource configSource = new IniConfigSource();
configSource.AddConfig("Startup");
return LoadConfig(configSource);
}
public static IConfigSource LoadConfig(IConfigSource source)
{
string iniFileName = source.Configs["Startup"].GetString("inifile", CONFIG_FILE);
string iniFilePath = Path.Combine(Util.configDir(), iniFileName);
source.Merge(DefaultConfig());
if (!File.Exists(iniFilePath))
{
m_log.FatalFormat("[CONFIG]: File {0} not found, could not load any configuration.", iniFilePath);
m_log.FatalFormat("[CONFIG]: Did you copy the AssetInventoryServer.ini.example file to AssetInventoryServer.ini?");
Environment.Exit(1);
}
source.Merge(new IniConfigSource(iniFilePath));
return source;
}
private static IConfigSource DefaultConfig()
{
IConfigSource result = new IniConfigSource();
{
IConfig config = result.AddConfig("Config");
config.Set("listen_port", 8003);
config.Set("assetset_location", String.Format(".{0}assets{0}AssetSets.xml", Path.DirectorySeparatorChar));
}
{
IConfig config = result.AddConfig("Plugins");
config.Set("asset_storage_provider", "OpenSimAssetStorage");
config.Set("inventory_storage_provider", "OpenSimInventoryStorage");
config.Set("authentication_provider", "NullAuthentication");
config.Set("authorization_provider", "AuthorizeAll");
config.Set("metrics_provider", "NullMetrics");
config.Set("frontends", "ReferenceFrontend,OpenSimAssetFrontend,OpenSimInventoryFrontend,BrowseFrontend");
}
{
IConfig config = result.AddConfig("OpenSim");
config.Set("asset_database_provider", "OpenSim.Data.MySQL.dll");
config.Set("inventory_database_provider", "OpenSim.Data.MySQL.dll");
config.Set("asset_database_connect", String.Empty);
config.Set("inventory_database_connect", String.Empty);
}
return result;
}
}
}

View File

@ -1,216 +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 System.Reflection;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Framework.Console;
using OpenSim.Framework.AssetLoader.Filesystem;
using Nini.Config;
using log4net;
namespace OpenSim.Grid.AssetInventoryServer
{
public class AssetInventoryServer : BaseOpenSimServer
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public IConfigSource ConfigFile;
public IAssetStorageProvider StorageProvider;
public IInventoryStorageProvider InventoryProvider;
public IAuthenticationProvider AuthenticationProvider;
public IAuthorizationProvider AuthorizationProvider;
public IMetricsProvider MetricsProvider;
private List<IAssetInventoryServerPlugin> m_frontends = new List<IAssetInventoryServerPlugin>();
private List<IAssetInventoryServerPlugin> m_backends = new List<IAssetInventoryServerPlugin>();
public AssetInventoryServer(IConfigSource config)
{
ConfigFile = config;
m_console = new LocalConsole("AssetInventory");
MainConsole.Instance = m_console;
}
public bool Start()
{
Startup();
m_log.Info("[ASSETINVENTORY]: Starting AssetInventory Server");
try
{
ConfigFile = AssetInventoryConfig.LoadConfig(ConfigFile);
}
catch (Exception)
{
m_log.Error("[ASSETINVENTORY]: Failed to load the config.");
return false;
}
StorageProvider = LoadAssetInventoryServerPlugin("/OpenSim/AssetInventoryServer/AssetStorageProvider",
"asset_storage_provider", false) as IAssetStorageProvider;
m_backends.Add(StorageProvider);
InventoryProvider = LoadAssetInventoryServerPlugin("/OpenSim/AssetInventoryServer/InventoryStorageProvider",
"inventory_storage_provider", false) as IInventoryStorageProvider;
m_backends.Add(InventoryProvider);
MetricsProvider = LoadAssetInventoryServerPlugin("/OpenSim/AssetInventoryServer/MetricsProvider",
"metrics_provider", false) as IMetricsProvider;
m_backends.Add(MetricsProvider);
try
{
InitHttpServer((uint) ConfigFile.Configs["Config"].GetInt("listen_port"));
}
catch (Exception ex)
{
m_log.Error("[ASSETINVENTORY]: Initializing the HTTP server failed, shutting down: " + ex.Message);
Shutdown();
return false;
}
LoadDefaultAssets();
AuthenticationProvider = LoadAssetInventoryServerPlugin("/OpenSim/AssetInventoryServer/AuthenticationProvider",
"authentication_provider", false) as IAuthenticationProvider;
m_backends.Add(AuthenticationProvider);
AuthorizationProvider = LoadAssetInventoryServerPlugin("/OpenSim/AssetInventoryServer/AuthorizationProvider",
"authorization_provider", false) as IAuthorizationProvider;
m_backends.Add(AuthorizationProvider);
m_frontends.AddRange(LoadAssetInventoryServerPlugins("/OpenSim/AssetInventoryServer/Frontend", "frontends"));
// Inform the user if we don't have any frontends at this point.
if (m_frontends.Count == 0)
m_log.Info("[ASSETINVENTORY]: Starting with no frontends loaded, which isn't extremely useful. Did you set the 'frontends' configuration parameter?");
return true;
}
public void Work()
{
m_console.Output("Enter help for a list of commands");
while (true)
{
m_console.Prompt();
}
}
public override void ShutdownSpecific()
{
foreach (IAssetInventoryServerPlugin plugin in m_frontends)
{
m_log.Debug("[ASSETINVENTORY]: Disposing plugin " + plugin.Name);
try { plugin.Dispose(); }
catch (Exception ex)
{ m_log.ErrorFormat("[ASSETINVENTORY]: Failure shutting down plugin {0}: {1}", plugin.Name, ex.Message); }
}
foreach (IAssetInventoryServerPlugin plugin in m_backends)
{
m_log.Debug("[ASSETINVENTORY]: Disposing plugin " + plugin.Name);
try { plugin.Dispose(); }
catch (Exception ex)
{ m_log.ErrorFormat("[ASSETINVENTORY]: Failure shutting down plugin {0}: {1}", plugin.Name, ex.Message); }
}
if (HttpServer != null)
HttpServer.Stop();
}
void InitHttpServer(uint port)
{
m_httpServer = new BaseHttpServer(port);
m_httpServer.Start();
m_log.Info("[ASSETINVENTORY]: AssetInventory server is listening on port " + port);
}
private IAssetInventoryServerPlugin LoadAssetInventoryServerPlugin(string addinPath, string configParam, bool optional)
{
IAssetInventoryServerPlugin result = null;
List<IAssetInventoryServerPlugin> plugins = LoadAssetInventoryServerPlugins(addinPath, configParam);
if (plugins.Count == 1)
{
result = plugins[0];
}
else if (plugins.Count > 1)
{
m_log.ErrorFormat("[ASSETINVENTORY]: Only 1 plugin expected for extension point '{0}', {1} plugins loaded. Check the '{2}' parameter in the config file.",
addinPath, plugins.Count, configParam);
Shutdown();
Environment.Exit(0);
}
else if (!optional)
{
m_log.ErrorFormat("[ASSETINVENTORY]: The extension point '{0}' is not optional. Check the '{1}' parameter in the config file.", addinPath, configParam);
Shutdown();
Environment.Exit(0);
}
return result;
}
private List<IAssetInventoryServerPlugin> LoadAssetInventoryServerPlugins(string addinPath, string configParam)
{
PluginLoader<IAssetInventoryServerPlugin> loader = new PluginLoader<IAssetInventoryServerPlugin>(new AssetInventoryServerPluginInitialiser(this));
loader.Add(addinPath, new PluginIdFilter(ConfigFile.Configs["Plugins"].GetString(configParam)));
try
{
loader.Load();
}
catch (PluginNotInitialisedException e)
{
m_log.ErrorFormat("[ASSETINVENTORY]: Error initialising plugin '{0}' for extension point '{1}'.", e.Message, addinPath);
Shutdown();
Environment.Exit(0);
}
return loader.Plugins;
}
private void LoadDefaultAssets()
{
AssetLoaderFileSystem assetLoader = new AssetLoaderFileSystem();
assetLoader.ForEachDefaultXmlAsset(ConfigFile.Configs["Config"].GetString("assetset_location"), StoreAsset);
}
private void StoreAsset(AssetBase asset)
{
StorageProvider.TryCreateAsset(asset);
}
}
}

View File

@ -1,143 +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 OpenMetaverse;
using OpenSim.Framework;
namespace OpenSim.Grid.AssetInventoryServer
{
/// <summary>
/// Response from a call to a backend provider
/// </summary>
public enum BackendResponse
{
/// <summary>The call succeeded</summary>
Success,
/// <summary>The resource requested was not found</summary>
NotFound,
/// <summary>A server failure prevented the call from
/// completing</summary>
Failure
}
public class AssetInventoryServerPluginInitialiser : PluginInitialiserBase
{
private AssetInventoryServer server;
public AssetInventoryServerPluginInitialiser(AssetInventoryServer server)
{
this.server = server;
}
public override void Initialise(IPlugin plugin)
{
IAssetInventoryServerPlugin p = plugin as IAssetInventoryServerPlugin;
p.Initialise (server);
}
}
#region Interfaces
public interface IAssetInventoryServerPlugin : IPlugin
{
void Initialise(AssetInventoryServer server);
}
public interface IAssetStorageProvider : IAssetInventoryServerPlugin
{
BackendResponse TryFetchMetadata(UUID assetID, out AssetMetadata metadata);
BackendResponse TryFetchData(UUID assetID, out byte[] assetData);
BackendResponse TryFetchDataMetadata(UUID assetID, out AssetBase asset);
BackendResponse TryCreateAsset(AssetBase asset);
BackendResponse TryCreateAsset(AssetBase asset, out UUID assetID);
int ForEach(Action<AssetMetadata> action, int start, int count);
}
public interface IInventoryStorageProvider : IAssetInventoryServerPlugin
{
BackendResponse TryFetchItem(Uri owner, UUID itemID, out InventoryItemBase item);
BackendResponse TryFetchFolder(Uri owner, UUID folderID, out InventoryFolderWithChildren folder);
BackendResponse TryFetchFolderContents(Uri owner, UUID folderID, out InventoryCollection contents);
BackendResponse TryFetchFolderList(Uri owner, out List<InventoryFolderWithChildren> folders);
BackendResponse TryFetchInventory(Uri owner, out InventoryCollection inventory);
BackendResponse TryFetchActiveGestures(Uri owner, out List<InventoryItemBase> gestures);
BackendResponse TryCreateItem(Uri owner, InventoryItemBase item);
BackendResponse TryCreateFolder(Uri owner, InventoryFolderWithChildren folder);
BackendResponse TryCreateInventory(Uri owner, InventoryFolderWithChildren rootFolder);
BackendResponse TryDeleteItem(Uri owner, UUID itemID);
BackendResponse TryDeleteFolder(Uri owner, UUID folderID);
BackendResponse TryPurgeFolder(Uri owner, UUID folderID);
}
public interface IAuthenticationProvider : IAssetInventoryServerPlugin
{
void AddIdentifier(UUID authToken, Uri identifier);
bool RemoveIdentifier(UUID authToken);
bool TryGetIdentifier(UUID authToken, out Uri identifier);
}
public interface IAuthorizationProvider : IAssetInventoryServerPlugin
{
bool IsMetadataAuthorized(UUID authToken, UUID assetID);
/// <summary>
/// Authorizes access to the data for an asset. Access to asset data
/// also implies access to the metadata for that asset
/// </summary>
/// <param name="authToken">Authentication token to check for access</param>
/// <param name="assetID">ID of the requested asset</param>
/// <returns>True if access is granted, otherwise false</returns>
bool IsDataAuthorized(UUID authToken, UUID assetID);
bool IsCreateAuthorized(UUID authToken);
bool IsInventoryReadAuthorized(UUID authToken, Uri owner);
bool IsInventoryWriteAuthorized(UUID authToken, Uri owner);
}
public interface IMetricsProvider : IAssetInventoryServerPlugin
{
void LogAssetMetadataFetch(string extension, BackendResponse response, UUID assetID, DateTime time);
void LogAssetDataFetch(string extension, BackendResponse response, UUID assetID, int dataSize, DateTime time);
void LogAssetCreate(string extension, BackendResponse response, UUID assetID, int dataSize, DateTime time);
void LogInventoryFetch(string extension, BackendResponse response, Uri owner, UUID objID, bool folder, DateTime time);
void LogInventoryFetchFolderContents(string extension, BackendResponse response, Uri owner, UUID folderID, DateTime time);
void LogInventoryFetchFolderList(string extension, BackendResponse response, Uri owner, DateTime time);
void LogInventoryFetchInventory(string extension, BackendResponse response, Uri owner, DateTime time);
void LogInventoryFetchActiveGestures(string extension, BackendResponse response, Uri owner, DateTime time);
void LogInventoryCreate(string extension, BackendResponse response, Uri owner, bool folder, DateTime time);
void LogInventoryCreateInventory(string extension, BackendResponse response, DateTime time);
void LogInventoryDelete(string extension, BackendResponse response, Uri owner, UUID objID, bool folder, DateTime time);
void LogInventoryPurgeFolder(string extension, BackendResponse response, Uri owner, UUID folderID, DateTime time);
}
#endregion Interfaces
}

View File

@ -1,139 +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 OpenMetaverse;
using OpenSim.Framework;
namespace OpenSim.Grid.AssetInventoryServer
{
//public class InventoryBase
//{
//}
//public class InventoryFolder : InventoryBase
//{
// public string Name;
// public UUID Owner;
// public UUID ParentID;
// public UUID ID;
// public short Type;
// public ushort Version;
// [NonSerialized]
// public Dictionary<UUID, InventoryBase> Children = new Dictionary<UUID, InventoryBase>();
// public InventoryFolder()
// {
// }
// public InventoryFolder(string name, UUID ownerID, UUID parentID, short assetType)
// {
// ID = UUID.Random();
// Name = name;
// Owner = ownerID;
// ParentID = parentID;
// Type = assetType;
// Version = 1;
// }
// public override string ToString()
// {
// return String.Format("{0} ({1})", Name, ID);
// }
//}
//public class InventoryItem : InventoryBase
//{
// public UUID ID;
// public int InvType;
// public UUID Folder;
// public UUID Owner;
// public UUID Creator;
// public string Name;
// public string Description;
// public uint NextPermissions;
// public uint CurrentPermissions;
// public uint BasePermissions;
// public uint EveryOnePermissions;
// public uint GroupPermissions;
// public int AssetType;
// public UUID AssetID;
// public UUID GroupID;
// public bool GroupOwned;
// public int SalePrice;
// public byte SaleType;
// public uint Flags;
// public int CreationDate;
// public override string ToString()
// {
// return String.Format("{0} ({1})", Name, ID);
// }
//}
public class InventoryFolderWithChildren : InventoryFolderBase
{
public InventoryFolderWithChildren()
{
}
public InventoryFolderWithChildren(InventoryFolderBase folder)
{
// from InventoryNodeBase
Name = folder.Name;
ID = folder.ID;
Owner = folder.Owner;
// from InventoryFolderBase
ParentID = folder.ParentID;
Type = folder.Type;
Version = folder.Version;
}
public InventoryFolderWithChildren(string name, UUID ownerID, UUID parentID, short assetType)
{
ID = UUID.Random();
Name = name;
Owner = ownerID;
ParentID = parentID;
Type = assetType;
Version = 1;
}
[NonSerialized]
public Dictionary<UUID, InventoryNodeBase> Children = new Dictionary<UUID, InventoryNodeBase>();
}
public class InventoryCollection
{
public Dictionary<UUID, InventoryFolderWithChildren> Folders;
public Dictionary<UUID, InventoryItemBase> Items;
public UUID UserID;
}
}

View File

@ -1,62 +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 Nini.Config;
using log4net.Config;
using log4net;
using System.Reflection;
namespace OpenSim.Grid.AssetInventoryServer
{
class MainEntry
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
static void Main(string[] args)
{
XmlConfigurator.Configure();
ArgvConfigSource configSource = new ArgvConfigSource(args);
configSource.AddSwitch("Startup", "inifile");
AssetInventoryServer server = new AssetInventoryServer(configSource);
if (server.Start())
{
Console.CancelKeyPress +=
delegate(object sender, ConsoleCancelEventArgs e)
{
m_log.Info("AssetInventory server is shutting down...");
server.Shutdown();
Environment.Exit(0);
};
server.Work();
}
}
}
}

View File

@ -1,105 +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.Reflection;
using OpenMetaverse;
using OpenSim.Framework;
using log4net;
namespace OpenSim.Grid.AssetInventoryServer.Plugins
{
public class AuthorizeAllPlugin : IAuthorizationProvider
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
//private AssetInventoryServer m_server;
public AuthorizeAllPlugin()
{
}
#region IPlugin implementation
public void Initialise(AssetInventoryServer server)
{
//m_server = server;
m_log.Info("[AUTHORIZEALL]: Authorize All loaded.");
}
/// <summary>
/// <para>Initialises asset interface</para>
/// </summary>
public void Initialise()
{
m_log.InfoFormat("[AUTHORIZEALL]: {0} cannot be default-initialized!", Name);
throw new PluginNotInitialisedException(Name);
}
public void Dispose()
{
}
public string Version
{
// TODO: this should be something meaningful and not hardcoded?
get { return "0.1"; }
}
public string Name
{
get { return "AuthorizeAll"; }
}
#endregion IPlugin implementation
public bool IsMetadataAuthorized(UUID authToken, UUID assetID)
{
return true;
}
public bool IsDataAuthorized(UUID authToken, UUID assetID)
{
return true;
}
public bool IsCreateAuthorized(UUID authToken)
{
return true;
}
public bool IsInventoryReadAuthorized(UUID authToken, Uri owner)
{
return true;
}
public bool IsInventoryWriteAuthorized(UUID authToken, Uri owner)
{
return true;
}
}
}

View File

@ -1,173 +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.IO;
using System.Reflection;
using System.Collections.Specialized;
using System.Net;
using System.Text;
using System.Web;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using log4net;
namespace OpenSim.Grid.AssetInventoryServer.Plugins
{
public class BrowseFrontendPlugin : IAssetInventoryServerPlugin
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private AssetInventoryServer m_server;
public BrowseFrontendPlugin()
{
}
#region IPlugin implementation
public void Initialise(AssetInventoryServer server)
{
m_server = server;
// Request for / or /?...
m_server.HttpServer.AddStreamHandler(new BrowseRequestHandler(server));
m_log.Info("[BROWSEFRONTEND]: Browser Frontend loaded.");
}
/// <summary>
/// <para>Initialises asset interface</para>
/// </summary>
public void Initialise()
{
m_log.InfoFormat("[BROWSEFRONTEND]: {0} cannot be default-initialized!", Name);
throw new PluginNotInitialisedException(Name);
}
public void Dispose()
{
}
public string Version
{
// TODO: this should be something meaningful and not hardcoded?
get { return "0.1"; }
}
public string Name
{
get { return "BrowseFrontend"; }
}
#endregion IPlugin implementation
public class BrowseRequestHandler : BaseStreamHandler
{
AssetInventoryServer m_server;
//public BrowseRequestHandler(AssetInventoryServer server) : base("GET", "(^/$|(^/\?.*)")
public BrowseRequestHandler(AssetInventoryServer server) : base("GET", "/")
{
m_server = server;
}
public override string ContentType
{
get { return "text/html"; }
}
#region IStreamedRequestHandler implementation
public override byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
const int ASSETS_PER_PAGE = 25;
const string HEADER = "<html><head><title>Asset Server</title></head><body>";
const string TABLE_HEADER =
"<table><tr><th>Name</th><th>Description</th><th>Type</th><th>ID</th><th>Temporary</th><th>SHA-1</th></tr>";
const string TABLE_FOOTER = "</table>";
const string FOOTER = "</body></html>";
UUID authToken = Utils.GetAuthToken(httpRequest);
StringBuilder html = new StringBuilder();
int start = 0;
uint page = 0;
if (!String.IsNullOrEmpty(httpRequest.Url.Query))
{
NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query);
if (!String.IsNullOrEmpty(query["page"]) && UInt32.TryParse(query["page"], out page))
start = (int)page * ASSETS_PER_PAGE;
}
html.AppendLine(HEADER);
html.AppendLine("<p>");
if (page > 0)
html.AppendFormat("<a href=\"{0}?page={1}\">&lt; Previous Page</a> | ", httpRequest.RawUrl, page - 1);
html.AppendFormat("<a href=\"{0}?page={1}\">Next Page &gt;</a>", httpRequest.RawUrl, page + 1);
html.AppendLine("</p>");
html.AppendLine(TABLE_HEADER);
m_server.StorageProvider.ForEach(
delegate(AssetMetadata data)
{
if (m_server.AuthorizationProvider.IsMetadataAuthorized(authToken, data.FullID))
{
html.AppendLine(String.Format(
"<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td><td>{5}</td></tr>",
data.Name, data.Description, data.ContentType, data.ID, data.Temporary,
BitConverter.ToString(data.SHA1).Replace("-", String.Empty)));
}
else
{
html.AppendLine(String.Format(
"<tr><td>[Protected Asset]</td><td>&nbsp;</td><td>&nbsp;</td><td>{0}</td><td>{1}</td><td>&nbsp;</td></tr>",
data.ID, data.Temporary));
}
}, start, ASSETS_PER_PAGE
);
html.AppendLine(TABLE_FOOTER);
html.AppendLine(FOOTER);
byte[] responseData = System.Text.Encoding.UTF8.GetBytes(html.ToString());
httpResponse.StatusCode = (int) HttpStatusCode.OK;
//httpResponse.Body.Write(responseData, 0, responseData.Length);
//httpResponse.Body.Flush();
return responseData;
}
#endregion IStreamedRequestHandler implementation
}
}
}

View File

@ -1,211 +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.Net;
using System.IO;
using System.IO.Compression;
using System.Xml;
using System.Reflection;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Serialization;
using OpenSim.Framework.Serialization.External;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using log4net;
namespace OpenSim.Grid.AssetInventoryServer.Plugins
{
public class InventoryArchivePlugin : IAssetInventoryServerPlugin
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private AssetInventoryServer m_server;
public InventoryArchivePlugin()
{
}
#region IPlugin implementation
public void Initialise(AssetInventoryServer server)
{
m_server = server;
m_server.HttpServer.AddStreamHandler(new GetInventoryArchive(server));
m_log.Info("[INVENTORYARCHIVE]: Inventory Archive loaded.");
}
/// <summary>
/// <para>Initialises asset interface</para>
/// </summary>
public void Initialise()
{
m_log.InfoFormat("[INVENTORYARCHIVE]: {0} cannot be default-initialized!", Name);
throw new PluginNotInitialisedException(Name);
}
public void Dispose()
{
}
public string Version
{
// TODO: this should be something meaningful and not hardcoded?
get { return "0.1"; }
}
public string Name
{
get { return "InventoryArchive"; }
}
#endregion IPlugin implementation
public class GetInventoryArchive : BaseStreamHandler
{
AssetInventoryServer m_server;
//public GetInventoryArchive(AssetInventoryServer server) : base("GET", @"^/inventoryarchive/")
public GetInventoryArchive(AssetInventoryServer server) : base("GET", "/inventoryarchive")
{
m_server = server;
}
public override string ContentType
{
get { return "application/x-compressed"; }
}
public override byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
byte[] buffer = new byte[] {};
UUID ownerID;
// Split the URL up to get the asset ID out
string[] rawUrl = httpRequest.Url.PathAndQuery.Split('/');
if (rawUrl.Length >= 3 && rawUrl[2].Length >= 36 && UUID.TryParse(rawUrl[2].Substring(0, 36), out ownerID))
{
Uri owner = Utils.GetOpenSimUri(ownerID);
InventoryCollection inventory;
BackendResponse storageResponse = m_server.InventoryProvider.TryFetchInventory(owner, out inventory);
if (storageResponse == BackendResponse.Success)
{
m_log.DebugFormat("[INVENTORYARCHIVE]: Archiving inventory for user UUID {0}", ownerID);
buffer = ArchiveInventoryCollection(inventory);
httpResponse.StatusCode = (int) HttpStatusCode.OK;
}
else
{
httpResponse.StatusCode = (int) HttpStatusCode.InternalServerError;
}
}
else
{
m_log.Warn("[INVENTORYARCHIVE]: Unrecognized inventory archive request: " + httpRequest.Url.PathAndQuery);
}
return buffer;
}
}
private static byte[] ArchiveInventoryCollection(InventoryCollection inventory)
{
byte[] buffer = new byte[] {};
// Fill in each folder's Children dictionary.
InventoryFolderWithChildren rootFolder = BuildInventoryHierarchy(ref inventory);
// TODO: It's probably a bad idea to tar to memory for large
// inventories.
MemoryStream ms = new MemoryStream();
GZipStream gzs = new GZipStream(ms, CompressionMode.Compress, true);
TarArchiveWriter archive = new TarArchiveWriter(gzs);
WriteInventoryFolderToArchive(archive, rootFolder, ArchiveConstants.INVENTORY_PATH);
archive.Close();
ms.Seek(0, SeekOrigin.Begin);
buffer = ms.GetBuffer();
Array.Resize<byte>(ref buffer, (int) ms.Length);
ms.Close();
return buffer;
}
private static InventoryFolderWithChildren BuildInventoryHierarchy(ref InventoryCollection inventory)
{
m_log.DebugFormat("[INVENTORYARCHIVE]: Building inventory hierarchy");
InventoryFolderWithChildren rootFolder = null;
foreach (InventoryFolderWithChildren parentFolder in inventory.Folders.Values)
{
// Grab the root folder, it has no parents.
if (UUID.Zero == parentFolder.ParentID) rootFolder = parentFolder;
foreach (InventoryFolderWithChildren folder in inventory.Folders.Values)
if (parentFolder.ID == folder.ParentID)
parentFolder.Children.Add(folder.ID, folder);
foreach (InventoryItemBase item in inventory.Items.Values)
if (parentFolder.ID == item.Folder)
parentFolder.Children.Add(item.ID, item);
}
return rootFolder;
}
private static void WriteInventoryFolderToArchive(
TarArchiveWriter archive, InventoryFolderWithChildren folder, string path)
{
path += string.Format("{0}{1}{2}/", folder.Name, ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR, folder.ID);
archive.WriteDir(path);
foreach (InventoryNodeBase inventoryNode in folder.Children.Values)
{
if (inventoryNode is InventoryFolderWithChildren)
{
WriteInventoryFolderToArchive(archive, (InventoryFolderWithChildren) inventoryNode, path);
}
else if (inventoryNode is InventoryItemBase)
{
WriteInventoryItemToArchive(archive, (InventoryItemBase) inventoryNode, path);
}
}
}
private static void WriteInventoryItemToArchive(TarArchiveWriter archive, InventoryItemBase item, string path)
{
string filename = string.Format("{0}{1}_{2}.xml", path, item.Name, item.ID);
string serialization = UserInventoryItemSerializer.Serialize(item);
archive.WriteFile(filename, serialization);
//m_assetGatherer.GatherAssetUuids(item.AssetID, (AssetType) item.AssetType, assetUuids);
}
}
}

View File

@ -1,151 +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.Reflection;
using OpenMetaverse;
using log4net;
namespace OpenSim.Grid.AssetInventoryServer.Plugins
{
public class NullMetricsPlugin : IMetricsProvider
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
//private AssetInventoryServer m_server;
public NullMetricsPlugin()
{
}
#region IMetricsProvider implementation
public void LogAssetMetadataFetch(string extension, BackendResponse response, UUID assetID, DateTime time)
{
m_log.DebugFormat("[{0}]: AssetMetadataFetch(): AssetID: {1}, Response: {2}", extension, assetID, response);
}
public void LogAssetDataFetch(string extension, BackendResponse response, UUID assetID, int dataSize, DateTime time)
{
m_log.DebugFormat("[{0}]: AssetDataFetch(): AssetID: {1}, DataSize: {2}, Response: {3}", extension, assetID,
dataSize, response);
}
public void LogAssetCreate(string extension, BackendResponse response, UUID assetID, int dataSize, DateTime time)
{
m_log.DebugFormat("[{0}]: AssetCreate(): AssetID: {1}, DataSize: {2}, Response: {3}", extension, assetID,
dataSize, response);
}
public void LogInventoryFetch(string extension, BackendResponse response, Uri owner, UUID objID, bool folder, DateTime time)
{
m_log.DebugFormat("[{0}]: InventoryFetch(): ObjID: {1}, Folder: {2}, OwnerID: {3}, Response: {4}", extension,
objID, folder, owner, response);
}
public void LogInventoryFetchFolderContents(string extension, BackendResponse response, Uri owner, UUID folderID, DateTime time)
{
m_log.DebugFormat("[{0}]: InventoryFetchFolderContents(): FolderID: {1}, OwnerID: {2}, Response: {3}", extension,
folderID, owner, response);
}
public void LogInventoryFetchFolderList(string extension, BackendResponse response, Uri owner, DateTime time)
{
m_log.DebugFormat("[{0}]: InventoryFetchFolderList(): OwnerID: {1}, Response: {2}", extension,
owner, response);
}
public void LogInventoryFetchInventory(string extension, BackendResponse response, Uri owner, DateTime time)
{
m_log.DebugFormat("[{0}]: InventoryFetchInventory(): OwnerID: {1}, Response: {2}", extension,
owner, response);
}
public void LogInventoryFetchActiveGestures(string extension, BackendResponse response, Uri owner, DateTime time)
{
m_log.DebugFormat("[{0}]: InventoryFetchActiveGestures(): OwnerID: {1}, Response: {2}", extension,
owner, response);
}
public void LogInventoryCreate(string extension, BackendResponse response, Uri owner, bool folder, DateTime time)
{
m_log.DebugFormat("[{0}]: InventoryCreate(): OwnerID: {1}, Response: {2}", extension,
owner, response);
}
public void LogInventoryCreateInventory(string extension, BackendResponse response, DateTime time)
{
m_log.DebugFormat("[{0}]: InventoryCreateInventory(): Response: {1}", extension,
response);
}
public void LogInventoryDelete(string extension, BackendResponse response, Uri owner, UUID objID, bool folder, DateTime time)
{
m_log.DebugFormat("[{0}]: InventoryDelete(): OwnerID: {1}, Folder: {2}, Response: {3}", extension,
owner, folder, response);
}
public void LogInventoryPurgeFolder(string extension, BackendResponse response, Uri owner, UUID folderID, DateTime time)
{
m_log.DebugFormat("[{0}]: InventoryPurgeFolder(): OwnerID: {1}, FolderID: {2}, Response: {3}", extension,
owner, folderID, response);
}
#endregion IMetricsProvider implementation
#region IPlugin implementation
public void Initialise(AssetInventoryServer server)
{
//m_server = server;
}
/// <summary>
/// <para>Initialises metrics interface</para>
/// </summary>
public void Initialise()
{
m_log.Info("[NULLMETRICS]: Null metrics loaded.");
}
public void Dispose()
{
}
public string Version
{
// TODO: this should be something meaningful and not hardcoded?
get { return "0.1"; }
}
public string Name
{
get { return "NullMetrics"; }
}
#endregion IPlugin implementation
}
}

View File

@ -1,198 +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.Reflection;
using System.Net;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using log4net;
namespace OpenSim.Grid.AssetInventoryServer.Plugins.OpenSim
{
public class OpenSimAssetFrontendPlugin : IAssetInventoryServerPlugin
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private AssetInventoryServer m_server;
public OpenSimAssetFrontendPlugin()
{
}
#region IPlugin implementation
public void Initialise(AssetInventoryServer server)
{
m_server = server;
// Asset request
m_server.HttpServer.AddStreamHandler(new AssetRequestHandler(server));
// Asset creation
m_server.HttpServer.AddStreamHandler(new AssetPostHandler(server));
m_log.Info("[OPENSIMASSETFRONTEND]: OpenSim Asset Frontend loaded.");
}
/// <summary>
/// <para>Initialises asset interface</para>
/// </summary>
public void Initialise()
{
m_log.InfoFormat("[OPENSIMASSETFRONTEND]: {0} cannot be default-initialized!", Name);
throw new PluginNotInitialisedException(Name);
}
public void Dispose()
{
}
public string Version
{
// TODO: this should be something meaningful and not hardcoded?
get { return "0.1"; }
}
public string Name
{
get { return "OpenSimAssetFrontend"; }
}
#endregion IPlugin implementation
public class AssetRequestHandler : BaseStreamHandler
{
AssetInventoryServer m_server;
//public AssetRequestHandler(AssetInventoryServer server) : base("GET", "^/assets")
public AssetRequestHandler(AssetInventoryServer server) : base("GET", "/assets")
{
m_server = server;
}
public override byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
byte[] buffer = new byte[] {};
UUID assetID;
// Split the URL up to get the asset ID out
string[] rawUrl = httpRequest.Url.PathAndQuery.Split('/');
if (rawUrl.Length >= 3 && rawUrl[2].Length >= 36 && UUID.TryParse(rawUrl[2].Substring(0, 36), out assetID))
{
BackendResponse dataResponse;
AssetBase asset = new AssetBase();
if ((dataResponse = m_server.StorageProvider.TryFetchDataMetadata(assetID, out asset)) == BackendResponse.Success)
{
if (rawUrl.Length >= 4 && rawUrl[3] == "data")
{
httpResponse.StatusCode = (int)HttpStatusCode.OK;
httpResponse.ContentType = Utils.SLAssetTypeToContentType(asset.Type);
buffer=asset.Data;
}
else
{
XmlSerializer xs = new XmlSerializer(typeof(AssetBase));
MemoryStream ms = new MemoryStream();
XmlTextWriter xw = new XmlTextWriter(ms, Encoding.UTF8);
xs.Serialize(xw, asset);
xw.Flush();
ms.Seek(0, SeekOrigin.Begin);
buffer = ms.GetBuffer();
Array.Resize<byte>(ref buffer, (int)ms.Length);
ms.Close();
httpResponse.StatusCode = (int)HttpStatusCode.OK;
}
}
else
{
m_log.WarnFormat("[OPENSIMASSETFRONTEND]: Failed to fetch asset data or metadata for {0}: {1}", assetID, dataResponse);
httpResponse.StatusCode = (int) HttpStatusCode.NotFound;
}
}
else
{
m_log.Warn("[OPENSIMASSETFRONTEND]: Unrecognized OpenSim asset request: " + httpRequest.Url.PathAndQuery);
}
return buffer;
}
}
public class AssetPostHandler : BaseStreamHandler
{
AssetInventoryServer m_server;
//public AssetPostHandler(AssetInventoryServer server) : base("POST", "/^assets")
public AssetPostHandler(AssetInventoryServer server) : base("POST", "/assets")
{
m_server = server;
}
public override byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
AssetBase asset = null;
try
{
asset = (AssetBase) new XmlSerializer(typeof (AssetBase)).Deserialize(httpRequest.InputStream);
}
catch (Exception ex)
{
m_log.Warn("[OPENSIMASSETFRONTEND]: Failed to parse POST data (expecting AssetBase): " + ex.Message);
httpResponse.StatusCode = (int) HttpStatusCode.BadRequest;
}
if (asset != null && asset.Data != null && asset.Data.Length > 0)
{
BackendResponse storageResponse = m_server.StorageProvider.TryCreateAsset(asset);
if (storageResponse == BackendResponse.Success)
httpResponse.StatusCode = (int) HttpStatusCode.Created;
else if (storageResponse == BackendResponse.NotFound)
httpResponse.StatusCode = (int) HttpStatusCode.NotFound;
else
httpResponse.StatusCode = (int) HttpStatusCode.InternalServerError;
}
else
{
m_log.Warn("[OPENSIMASSETFRONTEND]: AssetPostHandler called with no asset data");
httpResponse.StatusCode = (int) HttpStatusCode.BadRequest;
}
return new byte[] {};
}
}
}
}

View File

@ -1,189 +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.Reflection;
using System.Data;
using System.Collections.Generic;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Data;
using Nini.Config;
using log4net;
namespace OpenSim.Grid.AssetInventoryServer.Plugins.OpenSim
{
public class OpenSimAssetStoragePlugin : IAssetStorageProvider
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
const string EXTENSION_NAME = "OpenSimAssetStorage"; // Used in metrics reporting
private AssetInventoryServer m_server;
private IAssetDataPlugin m_assetProvider;
private IConfig m_openSimConfig;
public OpenSimAssetStoragePlugin()
{
}
#region IAssetStorageProvider implementation
public BackendResponse TryFetchMetadata(UUID assetID, out AssetMetadata metadata)
{
metadata = null;
BackendResponse ret;
AssetBase asset = m_assetProvider.FetchAsset(assetID);
if (asset == null) ret = BackendResponse.NotFound;
else
{
metadata = asset.Metadata;
ret = BackendResponse.Success;
}
m_server.MetricsProvider.LogAssetMetadataFetch(EXTENSION_NAME, ret, assetID, DateTime.Now);
return ret;
}
public BackendResponse TryFetchData(UUID assetID, out byte[] assetData)
{
assetData = null;
BackendResponse ret;
AssetBase asset = m_assetProvider.FetchAsset(assetID);
if (asset == null) ret = BackendResponse.NotFound;
else
{
assetData = asset.Data;
ret = BackendResponse.Success;
}
m_server.MetricsProvider.LogAssetDataFetch(EXTENSION_NAME, ret, assetID, (assetData != null ? assetData.Length : 0), DateTime.Now);
return ret;
}
public BackendResponse TryFetchDataMetadata(UUID assetID, out AssetBase asset)
{
asset = m_assetProvider.FetchAsset(assetID);
if (asset == null) return BackendResponse.NotFound;
return BackendResponse.Success;
}
public BackendResponse TryCreateAsset(AssetBase asset, out UUID assetID)
{
assetID = asset.FullID = UUID.Random();
return TryCreateAsset(asset);
}
public BackendResponse TryCreateAsset(AssetBase asset)
{
BackendResponse ret;
m_assetProvider.CreateAsset(asset);
ret = BackendResponse.Success;
m_server.MetricsProvider.LogAssetCreate(EXTENSION_NAME, ret, asset.FullID, asset.Data.Length, DateTime.Now);
return ret;
}
public int ForEach(Action<AssetMetadata> action, int start, int count)
{
int rowCount = 0;
foreach (AssetMetadata metadata in m_assetProvider.FetchAssetMetadataSet(start, count))
{
// We set the ContentType here because Utils is only in
// AssetInventoryServer. This should be moved to the DB
// backends when the equivalent of SLAssetTypeToContentType is
// in OpenSim.Framework or similar.
metadata.ContentType = Utils.SLAssetTypeToContentType(metadata.Type);
action(metadata);
++rowCount;
}
return rowCount;
}
#endregion IAssetStorageProvider implementation
#region IPlugin implementation
public void Initialise(AssetInventoryServer server)
{
m_server = server;
m_openSimConfig = server.ConfigFile.Configs["OpenSim"];
try
{
m_assetProvider = DataPluginFactory.LoadDataPlugin<IAssetDataPlugin>(m_openSimConfig.GetString("asset_database_provider"),
m_openSimConfig.GetString("asset_database_connect"));
if (m_assetProvider == null)
{
m_log.Error("[OPENSIMASSETSTORAGE]: Failed to load a database plugin, server halting.");
Environment.Exit(-1);
}
else
m_log.InfoFormat("[OPENSIMASSETSTORAGE]: Loaded storage backend: {0}", Version);
}
catch (Exception e)
{
m_log.WarnFormat("[OPENSIMASSETSTORAGE]: Failure loading data plugin: {0}", e.ToString());
throw new PluginNotInitialisedException(Name);
}
}
/// <summary>
/// <para>Initialises asset interface</para>
/// </summary>
public void Initialise()
{
m_log.InfoFormat("[OPENSIMASSETSTORAGE]: {0} cannot be default-initialized!", Name);
throw new PluginNotInitialisedException(Name);
}
public void Dispose()
{
}
public string Version
{
get { return m_assetProvider.Version; }
}
public string Name
{
get { return "OpenSimAssetStorage"; }
}
#endregion IPlugin implementation
}
}

View File

@ -1,867 +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.Net;
using System.Reflection;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using log4net;
namespace OpenSim.Grid.AssetInventoryServer.Plugins.OpenSim
{
public class OpenSimInventoryFrontendPlugin : IAssetInventoryServerPlugin
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private AssetInventoryServer m_server;
private Utils.InventoryCollectionSerializer collectionSerializer = new Utils.InventoryCollectionSerializer();
public OpenSimInventoryFrontendPlugin()
{
}
#region IPlugin implementation
public void Initialise(AssetInventoryServer server)
{
m_server = server;
m_server.HttpServer.AddStreamHandler(new GetInventoryHandler(server, collectionSerializer));
m_server.HttpServer.AddStreamHandler(new CreateInventoryHandler(server));
m_server.HttpServer.AddStreamHandler(new NewFolderHandler(server));
m_server.HttpServer.AddStreamHandler(new UpdateFolderHandler(server));
m_server.HttpServer.AddStreamHandler(new MoveFolderHandler(server));
m_server.HttpServer.AddStreamHandler(new PurgeFolderHandler(server));
m_server.HttpServer.AddStreamHandler(new NewItemHandler(server));
m_server.HttpServer.AddStreamHandler(new DeleteItemHandler(server));
m_server.HttpServer.AddStreamHandler(new RootFoldersHandler(server));
m_server.HttpServer.AddStreamHandler(new ActiveGesturesHandler(server));
m_log.Info("[OPENSIMINVENTORYFRONTEND]: OpenSim Inventory Frontend loaded.");
}
/// <summary>
/// <para>Initialises asset interface</para>
/// </summary>
public void Initialise()
{
m_log.InfoFormat("[OPENSIMINVENTORYFRONTEND]: {0} cannot be default-initialized!", Name);
throw new PluginNotInitialisedException(Name);
}
public void Dispose()
{
}
public string Version
{
// TODO: this should be something meaningful and not hardcoded?
get { return "0.1"; }
}
public string Name
{
get { return "OpenSimInventoryFrontend"; }
}
#endregion IPlugin implementation
public class GetInventoryHandler : BaseStreamHandler
{
AssetInventoryServer m_server;
Utils.InventoryCollectionSerializer m_collectionSerializer;
//public GetInventoryHandler(AssetInventoryServer server, Utils.InventoryCollectionSerializer collectionSerializer) : base("POST", @"^/GetInventory/")
public GetInventoryHandler(AssetInventoryServer server, Utils.InventoryCollectionSerializer collectionSerializer) : base("POST", "/GetInventory")
{
m_server = server;
m_collectionSerializer = collectionSerializer;
}
public override byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
byte[] buffer = new byte[] {};
UUID sessionID, agentID;
UUID ownerID = DeserializeUUID(httpRequest.InputStream, out agentID, out sessionID);
if (ownerID != UUID.Zero)
{
m_log.Warn("[OPENSIMINVENTORYFRONTEND]: GetInventory is not scalable on some inventory backends, avoid calling it wherever possible");
Uri owner = Utils.GetOpenSimUri(ownerID);
InventoryCollection inventory;
BackendResponse storageResponse = m_server.InventoryProvider.TryFetchInventory(owner, out inventory);
if (storageResponse == BackendResponse.Success)
{
//collectionSerializer.Serialize(httpResponse.Body, inventory);
//httpResponse.Body.Flush();
MemoryStream ms = new MemoryStream();
m_collectionSerializer.Serialize(ms, inventory);
ms.Seek(0, SeekOrigin.Begin);
buffer = ms.GetBuffer();
Array.Resize<byte>(ref buffer, (int) ms.Length);
ms.Close();
httpResponse.StatusCode = (int) HttpStatusCode.OK;
}
else if (storageResponse == BackendResponse.NotFound)
{
// Return an empty inventory set to mimic OpenSim.Grid.InventoryServer.exe
inventory = new InventoryCollection();
inventory.UserID = ownerID;
inventory.Folders = new Dictionary<UUID, InventoryFolderWithChildren>();
inventory.Items = new Dictionary<UUID, InventoryItemBase>();
//collectionSerializer.Serialize(httpResponse.Body, inventory);
//httpResponse.Body.Flush();
MemoryStream ms = new MemoryStream();
m_collectionSerializer.Serialize(ms, inventory);
ms.Seek(0, SeekOrigin.Begin);
buffer = ms.GetBuffer();
Array.Resize<byte>(ref buffer, (int) ms.Length);
ms.Close();
httpResponse.StatusCode = (int) HttpStatusCode.OK;
}
else
{
httpResponse.StatusCode = (int) HttpStatusCode.InternalServerError;
}
}
else
{
httpResponse.StatusCode = (int) HttpStatusCode.BadRequest;
}
return buffer;
}
}
public class CreateInventoryHandler : BaseStreamHandler
{
AssetInventoryServer m_server;
//public CreateInventoryHandler(AssetInventoryServer server) : base("POST", @"^/CreateInventory/")
public CreateInventoryHandler(AssetInventoryServer server) : base("POST", "/CreateInventory")
{
m_server = server;
}
public override byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
UUID ownerID = DeserializeUUID(httpRequest.InputStream);
if (ownerID != UUID.Zero)
{
Uri owner = Utils.GetOpenSimUri(ownerID);
m_log.DebugFormat("[OPENSIMINVENTORYFRONTEND]: Created URI {0} for inventory creation", owner);
InventoryFolderWithChildren rootFolder = new InventoryFolderWithChildren("My Inventory", ownerID, UUID.Zero, (short)AssetType.Folder);
BackendResponse storageResponse = m_server.InventoryProvider.TryCreateInventory(owner, rootFolder);
if (storageResponse == BackendResponse.Success)
{
// TODO: The CreateFolder calls need to be executed in SimpleStorage.
//CreateFolder("Animations", ownerID, rootFolder.ID, AssetType.Animation);
//CreateFolder("Body Parts", ownerID, rootFolder.ID, AssetType.Bodypart);
//CreateFolder("Calling Cards", ownerID, rootFolder.ID, AssetType.CallingCard);
//CreateFolder("Clothing", ownerID, rootFolder.ID, AssetType.Clothing);
//CreateFolder("Gestures", ownerID, rootFolder.ID, AssetType.Gesture);
//CreateFolder("Landmarks", ownerID, rootFolder.ID, AssetType.Landmark);
//CreateFolder("Lost and Found", ownerID, rootFolder.ID, AssetType.LostAndFoundFolder);
//CreateFolder("Notecards", ownerID, rootFolder.ID, AssetType.Notecard);
//CreateFolder("Objects", ownerID, rootFolder.ID, AssetType.Object);
//CreateFolder("Photo Album", ownerID, rootFolder.ID, AssetType.SnapshotFolder);
//CreateFolder("Scripts", ownerID, rootFolder.ID, AssetType.LSLText);
//CreateFolder("Sounds", ownerID, rootFolder.ID, AssetType.Sound);
//CreateFolder("Textures", ownerID, rootFolder.ID, AssetType.Texture);
//CreateFolder("Trash", ownerID, rootFolder.ID, AssetType.TrashFolder);
return SerializeBool(true);
}
}
return SerializeBool(false);
}
}
public class NewFolderHandler : BaseStreamHandler
{
AssetInventoryServer m_server;
//public NewFolderHandler(AssetInventoryServer server) : base("POST", @"^/NewFolder/")
public NewFolderHandler(AssetInventoryServer server) : base("POST", "/NewFolder")
{
m_server = server;
}
public override byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
UUID agentID, sessionID;
InventoryFolderWithChildren folder = DeserializeFolder(httpRequest.InputStream, out agentID, out sessionID);
if (folder != null)
{
Uri owner = Utils.GetOpenSimUri(folder.Owner);
// Some calls that are moving or updating a folder instead
// of creating a new one will pass in an InventoryFolder
// without the name set and type set to 0. If this is the
// case we need to look up the name first and preserver
// it's type.
if (String.IsNullOrEmpty(folder.Name))
{
InventoryFolderWithChildren oldFolder;
if (m_server.InventoryProvider.TryFetchFolder(owner, folder.ID, out oldFolder) == BackendResponse.Success)
{
folder.Name = oldFolder.Name;
folder.Type = oldFolder.Type;
}
}
BackendResponse storageResponse = m_server.InventoryProvider.TryCreateFolder(owner, folder);
if (storageResponse == BackendResponse.Success)
{
return SerializeBool(true);
}
}
return SerializeBool(false);
}
}
public class UpdateFolderHandler : BaseStreamHandler
{
AssetInventoryServer m_server;
//public UpdateFolderHandler(AssetInventoryServer server) : base("POST", @"^/UpdateFolder/")
public UpdateFolderHandler(AssetInventoryServer server) : base("POST", "/UpdateFolder")
{
m_server = server;
}
public override byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
return new NewFolderHandler(m_server).Handle(path, request, httpRequest, httpResponse);
}
}
public class MoveFolderHandler : BaseStreamHandler
{
AssetInventoryServer m_server;
//public MoveFolderHandler(AssetInventoryServer server) : base("POST", @"^/MoveFolder/")
public MoveFolderHandler(AssetInventoryServer server) : base("POST", "/MoveFolder")
{
m_server = server;
}
public override byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
return new NewFolderHandler(m_server).Handle(path, request, httpRequest, httpResponse);
}
}
public class PurgeFolderHandler : BaseStreamHandler
{
AssetInventoryServer m_server;
//public PurgeFolderHandler(AssetInventoryServer server) : base("POST", @"^/PurgeFolder/")
public PurgeFolderHandler(AssetInventoryServer server) : base("POST", "/PurgeFolder")
{
m_server = server;
}
public override byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
UUID agentID, sessionID;
InventoryFolderWithChildren folder = DeserializeFolder(httpRequest.InputStream, out agentID, out sessionID);
if (folder != null)
{
Uri owner = Utils.GetOpenSimUri(folder.Owner);
BackendResponse storageResponse = m_server.InventoryProvider.TryPurgeFolder(owner, folder.ID);
if (storageResponse == BackendResponse.Success)
{
return SerializeBool(true);
}
}
return SerializeBool(false);
}
}
public class NewItemHandler : BaseStreamHandler
{
AssetInventoryServer m_server;
//public NewItemHandler(AssetInventoryServer server) : base("POST", @"^/NewItem/")
public NewItemHandler(AssetInventoryServer server) : base("POST", "/NewItem")
{
m_server = server;
}
public override byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
UUID agentID, sessionID;
InventoryItemBase item = DeserializeItem(httpRequest.InputStream, out agentID, out sessionID);
if (item != null)
{
Uri owner = Utils.GetOpenSimUri(agentID);
BackendResponse storageResponse = m_server.InventoryProvider.TryCreateItem(owner, item);
if (storageResponse == BackendResponse.Success)
{
return SerializeBool(true);
}
}
return SerializeBool(false);
}
}
public class DeleteItemHandler : BaseStreamHandler
{
AssetInventoryServer m_server;
//public DeleteItemHandler(AssetInventoryServer server) : base("POST", @"^/DeleteItem/")
public DeleteItemHandler(AssetInventoryServer server) : base("POST", "/DeleteItem")
{
m_server = server;
}
public override byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
UUID agentID, sessionID;
InventoryItemBase item = DeserializeItem(httpRequest.InputStream, out agentID, out sessionID);
if (item != null)
{
Uri owner = Utils.GetOpenSimUri(item.Owner);
BackendResponse storageResponse = m_server.InventoryProvider.TryDeleteItem(owner, item.ID);
if (storageResponse == BackendResponse.Success)
{
return SerializeBool(true);
}
}
return SerializeBool(false);
}
}
public class RootFoldersHandler : BaseStreamHandler
{
AssetInventoryServer m_server;
//public RootFoldersHandler(AssetInventoryServer server) : base("POST", @"^/RootFolders/")
public RootFoldersHandler(AssetInventoryServer server) : base("POST", "/RootFolders")
{
m_server = server;
}
public override byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
byte[] buffer = new byte[] {};
UUID ownerID = DeserializeUUID(httpRequest.InputStream);
if (ownerID != UUID.Zero)
{
Uri owner = Utils.GetOpenSimUri(ownerID);
List<InventoryFolderWithChildren> skeleton;
BackendResponse storageResponse = m_server.InventoryProvider.TryFetchFolderList(owner, out skeleton);
if (storageResponse == BackendResponse.Success)
{
MemoryStream ms = new MemoryStream();
SerializeFolderList(ms, skeleton);
ms.Seek(0, SeekOrigin.Begin);
buffer = ms.GetBuffer();
Array.Resize<byte>(ref buffer, (int) ms.Length);
ms.Close();
httpResponse.StatusCode = (int) HttpStatusCode.OK;
}
else if (storageResponse == BackendResponse.NotFound)
{
// Return an empty set of inventory so the requester knows that
// an inventory needs to be created for this agent
MemoryStream ms = new MemoryStream();
SerializeFolderList(ms, new List<InventoryFolderWithChildren>(0));
ms.Seek(0, SeekOrigin.Begin);
buffer = ms.GetBuffer();
Array.Resize<byte>(ref buffer, (int) ms.Length);
ms.Close();
httpResponse.StatusCode = (int) HttpStatusCode.OK;
}
else
{
httpResponse.StatusCode = (int) HttpStatusCode.InternalServerError;
}
}
else
{
httpResponse.StatusCode = (int) HttpStatusCode.BadRequest;
}
return buffer;
}
}
public class ActiveGesturesHandler : BaseStreamHandler
{
AssetInventoryServer m_server;
//public ActiveGesturesHandler(AssetInventoryServer server) : base("POST", @"^/ActiveGestures/")
public ActiveGesturesHandler(AssetInventoryServer server) : base("POST", "/ActiveGestures")
{
m_server = server;
}
public override byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
byte[] buffer = new byte[] {};
UUID ownerID = DeserializeUUID(httpRequest.InputStream);
if (ownerID != UUID.Zero)
{
Uri owner = Utils.GetOpenSimUri(ownerID);
List<InventoryItemBase> gestures;
BackendResponse storageResponse = m_server.InventoryProvider.TryFetchActiveGestures(owner, out gestures);
if (storageResponse == BackendResponse.Success)
{
MemoryStream ms = new MemoryStream();
SerializeItemList(ms, gestures);
ms.Seek(0, SeekOrigin.Begin);
buffer = ms.GetBuffer();
Array.Resize<byte>(ref buffer, (int) ms.Length);
ms.Close();
httpResponse.StatusCode = (int) HttpStatusCode.OK;
}
else if (storageResponse == BackendResponse.NotFound)
{
// Return an empty set of gestures to match OpenSim.Grid.InventoryServer.exe behavior
MemoryStream ms = new MemoryStream();
SerializeItemList(ms, new List<InventoryItemBase>(0));
ms.Seek(0, SeekOrigin.Begin);
buffer = ms.GetBuffer();
Array.Resize<byte>(ref buffer, (int) ms.Length);
ms.Close();
httpResponse.StatusCode = (int) HttpStatusCode.OK;
}
else
{
httpResponse.StatusCode = (int) HttpStatusCode.InternalServerError;
}
}
else
{
httpResponse.StatusCode = (int) HttpStatusCode.BadRequest;
}
return buffer;
}
}
//BackendResponse CreateFolder(string name, UUID ownerID, UUID parentID, AssetType assetType)
//{
// InventoryFolder folder = new InventoryFolder(name, ownerID, parentID, (short)assetType);
// Uri owner = Utils.GetOpenSimUri(ownerID);
// return m_server.InventoryProvider.TryCreateFolder(owner, folder);
//}
private static UUID DeserializeUUID(Stream stream)
{
UUID id = UUID.Zero;
try
{
using (XmlReader reader = XmlReader.Create(stream))
{
reader.MoveToContent();
UUID.TryParse(reader.ReadElementContentAsString("guid", String.Empty), out id);
}
}
catch (Exception ex)
{
m_log.Warn("[OPENSIMINVENTORYFRONTEND]: Failed to parse POST data (expecting guid): " + ex.Message);
}
return id;
}
private static UUID DeserializeUUID(Stream stream, out UUID agentID, out UUID sessionID)
{
UUID id;
try
{
using (XmlReader reader = XmlReader.Create(stream))
{
reader.MoveToContent();
reader.ReadStartElement("RestSessionObjectOfGuid");
UUID.TryParse(reader.ReadElementContentAsString("SessionID", String.Empty), out sessionID);
UUID.TryParse(reader.ReadElementContentAsString("AvatarID", String.Empty), out agentID);
UUID.TryParse(reader.ReadElementContentAsString("Body", String.Empty), out id);
reader.ReadEndElement();
}
}
catch (Exception ex)
{
m_log.Warn("[OPENSIMINVENTORYFRONTEND]: Failed to parse GetInventory POST data: " + ex.Message);
agentID = UUID.Zero;
sessionID = UUID.Zero;
return UUID.Zero;
}
return id;
}
private static InventoryFolderWithChildren DeserializeFolder(Stream stream, out UUID agentID, out UUID sessionID)
{
InventoryFolderWithChildren folder = new InventoryFolderWithChildren();
try
{
using (XmlReader reader = XmlReader.Create(stream))
{
reader.MoveToContent();
reader.ReadStartElement("RestSessionObjectOfInventoryFolderBase");
UUID.TryParse(reader.ReadElementContentAsString("SessionID", String.Empty), out sessionID);
UUID.TryParse(reader.ReadElementContentAsString("AvatarID", String.Empty), out agentID);
reader.ReadStartElement("Body");
if (reader.Name == "Name")
folder.Name = reader.ReadElementContentAsString("Name", String.Empty);
else
folder.Name = String.Empty;
UUID dummyUUID;
ReadUUID(reader, "ID", out dummyUUID);
folder.ID = dummyUUID;
ReadUUID(reader, "Owner", out dummyUUID);
folder.Owner = dummyUUID;
ReadUUID(reader, "ParentID", out dummyUUID);
folder.ParentID = dummyUUID;
short dummyType;
Int16.TryParse(reader.ReadElementContentAsString("Type", String.Empty), out dummyType);
folder.Type = dummyType;
ushort dummyVersion;
UInt16.TryParse(reader.ReadElementContentAsString("Version", String.Empty), out dummyVersion);
folder.Version = dummyVersion;
reader.ReadEndElement();
reader.ReadEndElement();
}
}
catch (Exception ex)
{
m_log.Warn("[OPENSIMINVENTORYFRONTEND]: Failed to parse POST data (expecting InventoryFolderBase): " + ex.Message);
agentID = UUID.Zero;
sessionID = UUID.Zero;
return null;
}
return folder;
}
private static InventoryItemBase DeserializeItem(Stream stream, out UUID agentID, out UUID sessionID)
{
InventoryItemBase item = new InventoryItemBase();
try
{
using (XmlReader reader = XmlReader.Create(stream))
{
reader.MoveToContent();
reader.ReadStartElement("RestSessionObjectOfInventoryItemBase");
UUID.TryParse(reader.ReadElementContentAsString("SessionID", String.Empty), out sessionID);
UUID.TryParse(reader.ReadElementContentAsString("AvatarID", String.Empty), out agentID);
reader.ReadStartElement("Body");
item.Name = reader.ReadElementContentAsString("Name", String.Empty);
UUID dummyUUID;
ReadUUID(reader, "ID", out dummyUUID);
item.ID = dummyUUID;
ReadUUID(reader, "Owner", out dummyUUID);
item.Owner = dummyUUID;
int dummyInt;
Int32.TryParse(reader.ReadElementContentAsString("InvType", String.Empty), out dummyInt);
item.InvType = dummyInt;
ReadUUID(reader, "Folder", out dummyUUID);
item.Folder = dummyUUID;
item.CreatorId = reader.ReadElementContentAsString("CreatorId", String.Empty);
item.Description = reader.ReadElementContentAsString("Description", String.Empty);
uint dummyUInt;
UInt32.TryParse(reader.ReadElementContentAsString("NextPermissions", String.Empty), out dummyUInt);
item.NextPermissions = dummyUInt;
UInt32.TryParse(reader.ReadElementContentAsString("CurrentPermissions", String.Empty), out dummyUInt);
item.CurrentPermissions = dummyUInt;
UInt32.TryParse(reader.ReadElementContentAsString("BasePermissions", String.Empty), out dummyUInt);
item.BasePermissions = dummyUInt;
UInt32.TryParse(reader.ReadElementContentAsString("EveryOnePermissions", String.Empty), out dummyUInt);
item.EveryOnePermissions = dummyUInt;
UInt32.TryParse(reader.ReadElementContentAsString("GroupPermissions", String.Empty), out dummyUInt);
item.GroupPermissions = dummyUInt;
Int32.TryParse(reader.ReadElementContentAsString("AssetType", String.Empty), out dummyInt);
item.AssetType = dummyInt;
ReadUUID(reader, "AssetID", out dummyUUID);
item.AssetID = dummyUUID;
ReadUUID(reader, "GroupID", out dummyUUID);
item.GroupID = dummyUUID;
bool dummyBool;
Boolean.TryParse(reader.ReadElementContentAsString("GroupOwned", String.Empty), out dummyBool);
item.GroupOwned = dummyBool;
Int32.TryParse(reader.ReadElementContentAsString("SalePrice", String.Empty), out dummyInt);
item.SalePrice = dummyInt;
byte dummyByte;
Byte.TryParse(reader.ReadElementContentAsString("SaleType", String.Empty), out dummyByte);
item.SaleType = dummyByte;
UInt32.TryParse(reader.ReadElementContentAsString("Flags", String.Empty), out dummyUInt);
item.Flags = dummyUInt;
Int32.TryParse(reader.ReadElementContentAsString("CreationDate", String.Empty), out dummyInt);
item.CreationDate = dummyInt;
reader.ReadEndElement();
reader.ReadEndElement();
}
}
catch (Exception ex)
{
m_log.Warn("[OPENSIMINVENTORYFRONTEND]: Failed to parse POST data (expecting InventoryItemBase): " + ex.Message);
agentID = UUID.Zero;
sessionID = UUID.Zero;
return null;
}
return item;
}
private static byte[] SerializeBool(bool value)
{
byte[] buffer;
MemoryStream ms = new MemoryStream();
using (XmlWriter writer = XmlWriter.Create(ms))
{
writer.WriteStartDocument();
writer.WriteStartElement("boolean");
writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
writer.WriteAttributeString("xmlns", "xsd", null, "http://www.w3.org/2001/XMLSchema");
writer.WriteString(value.ToString().ToLower());
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
}
ms.Seek(0, SeekOrigin.Begin);
buffer = ms.GetBuffer();
Array.Resize<byte>(ref buffer, (int) ms.Length);
ms.Close();
return buffer;
}
private static void SerializeFolderList(Stream stream, List<InventoryFolderWithChildren> folders)
{
using (XmlWriter writer = XmlWriter.Create(stream))
{
writer.WriteStartDocument();
writer.WriteStartElement("ArrayOfInventoryFolderBase");
writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
writer.WriteAttributeString("xmlns", "xsd", null, "http://www.w3.org/2001/XMLSchema");
if (folders != null)
{
foreach (InventoryFolderWithChildren folder in folders)
{
writer.WriteStartElement("InventoryFolderBase");
writer.WriteElementString("Name", folder.Name);
WriteUUID(writer, "Owner", folder.Owner);
WriteUUID(writer, "ParentID", folder.ParentID);
WriteUUID(writer, "ID", folder.ID);
writer.WriteElementString("Type", XmlConvert.ToString(folder.Type));
writer.WriteElementString("Version", XmlConvert.ToString(folder.Version));
writer.WriteEndElement();
}
}
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
}
stream.Flush();
}
private static void SerializeItemList(Stream stream, List<InventoryItemBase> items)
{
using (XmlWriter writer = XmlWriter.Create(stream))
{
writer.WriteStartDocument();
writer.WriteStartElement("ArrayOfInventoryItemBase");
writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
writer.WriteAttributeString("xmlns", "xsd", null, "http://www.w3.org/2001/XMLSchema");
if (items != null)
{
foreach (InventoryItemBase item in items)
{
writer.WriteStartElement("InventoryItemBase");
WriteUUID(writer, "ID", item.ID);
writer.WriteElementString("InvType", XmlConvert.ToString(item.InvType));
WriteUUID(writer, "Folder", item.Folder);
WriteUUID(writer, "Owner", item.Owner);
writer.WriteElementString("Creator", item.CreatorId);
writer.WriteElementString("Name", item.Name);
writer.WriteElementString("Description", item.Description);
writer.WriteElementString("NextPermissions", XmlConvert.ToString(item.NextPermissions));
writer.WriteElementString("CurrentPermissions", XmlConvert.ToString(item.CurrentPermissions));
writer.WriteElementString("BasePermissions", XmlConvert.ToString(item.BasePermissions));
writer.WriteElementString("EveryOnePermissions", XmlConvert.ToString(item.EveryOnePermissions));
writer.WriteElementString("GroupPermissions", XmlConvert.ToString(item.GroupPermissions));
writer.WriteElementString("AssetType", XmlConvert.ToString(item.AssetType));
WriteUUID(writer, "AssetID", item.AssetID);
WriteUUID(writer, "GroupID", item.GroupID);
writer.WriteElementString("GroupOwned", XmlConvert.ToString(item.GroupOwned));
writer.WriteElementString("SalePrice", XmlConvert.ToString(item.SalePrice));
writer.WriteElementString("SaleType", XmlConvert.ToString(item.SaleType));
writer.WriteElementString("Flags", XmlConvert.ToString(item.Flags));
writer.WriteElementString("CreationDate", XmlConvert.ToString(item.CreationDate));
writer.WriteEndElement();
}
}
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
}
stream.Flush();
}
private static void WriteUUID(XmlWriter writer, string name, UUID id)
{
writer.WriteStartElement(name);
writer.WriteElementString("Guid", XmlConvert.ToString(id.Guid));
writer.WriteEndElement();
}
private static void ReadUUID(XmlReader reader, string name, out UUID id)
{
reader.ReadStartElement(name);
UUID.TryParse(reader.ReadElementContentAsString("Guid", String.Empty), out id);
reader.ReadEndElement();
}
}
#region OpenSim AssetType
/// <summary>
/// The different types of grid assets
/// </summary>
public enum AssetType : sbyte
{
/// <summary>Unknown asset type</summary>
Unknown = -1,
/// <summary>Texture asset, stores in JPEG2000 J2C stream format</summary>
Texture = 0,
/// <summary>Sound asset</summary>
Sound = 1,
/// <summary>Calling card for another avatar</summary>
CallingCard = 2,
/// <summary>Link to a location in world</summary>
Landmark = 3,
// <summary>Legacy script asset, you should never see one of these</summary>
//[Obsolete]
//Script = 4,
/// <summary>Collection of textures and parameters that can be
/// worn by an avatar</summary>
Clothing = 5,
/// <summary>Primitive that can contain textures, sounds,
/// scripts and more</summary>
Object = 6,
/// <summary>Notecard asset</summary>
Notecard = 7,
/// <summary>Holds a collection of inventory items</summary>
Folder = 8,
/// <summary>Root inventory folder</summary>
RootFolder = 9,
/// <summary>Linden scripting language script</summary>
LSLText = 10,
/// <summary>LSO bytecode for a script</summary>
LSLBytecode = 11,
/// <summary>Uncompressed TGA texture</summary>
TextureTGA = 12,
/// <summary>Collection of textures and shape parameters that can
/// be worn</summary>
Bodypart = 13,
/// <summary>Trash folder</summary>
TrashFolder = 14,
/// <summary>Snapshot folder</summary>
SnapshotFolder = 15,
/// <summary>Lost and found folder</summary>
LostAndFoundFolder = 16,
/// <summary>Uncompressed sound</summary>
SoundWAV = 17,
/// <summary>Uncompressed TGA non-square image, not to be used as a
/// texture</summary>
ImageTGA = 18,
/// <summary>Compressed JPEG non-square image, not to be used as a
/// texture</summary>
ImageJPEG = 19,
/// <summary>Animation</summary>
Animation = 20,
/// <summary>Sequence of animations, sounds, chat, and pauses</summary>
Gesture = 21,
/// <summary>Simstate file</summary>
Simstate = 22,
}
#endregion OpenSim AssetType
}

View File

@ -1,547 +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.Reflection;
using System.Collections.Generic;
using System.Data;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Data;
using Nini.Config;
using log4net;
namespace OpenSim.Grid.AssetInventoryServer.Plugins.OpenSim
{
public class OpenSimInventoryStoragePlugin : IInventoryStorageProvider
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
const string EXTENSION_NAME = "OpenSimInventoryStorage"; // Used in metrics reporting
private AssetInventoryServer m_server;
private IConfig m_openSimConfig;
private OpenSimInventoryService m_inventoryService;
public OpenSimInventoryStoragePlugin()
{
}
#region IInventoryStorageProvider implementation
public BackendResponse TryFetchItem(Uri owner, UUID itemID, out InventoryItemBase item)
{
item = null;
//BackendResponse ret;
//using (MySqlConnection dbConnection = new MySqlConnection(m_openSimConfig.GetString("inventory_database_connect")))
//{
// IDataReader reader;
// try
// {
// dbConnection.Open();
// IDbCommand command = dbConnection.CreateCommand();
// command.CommandText = String.Format("SELECT assetID,assetType,inventoryName,inventoryDescription,inventoryNextPermissions," +
// "inventoryCurrentPermissions,invType,creatorID,inventoryBasePermissions,inventoryEveryOnePermissions,salePrice,saleType," +
// "creationDate,groupID,groupOwned,flags,avatarID,parentFolderID,inventoryGroupPermissions FROM inventoryitems WHERE inventoryID='{0}'",
// itemID.ToString());
// reader = command.ExecuteReader();
// if (reader.Read())
// {
// item = new InventoryItemBase();
// item.ID = itemID;
// item.AssetID = UUID.Parse(reader.GetString(0));
// item.AssetType = reader.GetInt32(1);
// item.Name = reader.GetString(2);
// item.Description = reader.GetString(3);
// item.NextPermissions = (uint)reader.GetInt32(4);
// item.CurrentPermissions = (uint)reader.GetInt32(5);
// item.InvType = reader.GetInt32(6);
// item.Creator = UUID.Parse(reader.GetString(7));
// item.BasePermissions = (uint)reader.GetInt32(8);
// item.EveryOnePermissions = (uint)reader.GetInt32(9);
// item.SalePrice = reader.GetInt32(10);
// item.SaleType = reader.GetByte(11);
// item.CreationDate = reader.GetInt32(12);
// item.GroupID = UUID.Parse(reader.GetString(13));
// item.GroupOwned = reader.GetBoolean(14);
// item.Flags = (uint)reader.GetInt32(15);
// item.Owner = UUID.Parse(reader.GetString(16));
// item.Folder = UUID.Parse(reader.GetString(17));
// item.GroupPermissions = (uint)reader.GetInt32(18);
// ret = BackendResponse.Success;
// }
// else
// {
// ret = BackendResponse.NotFound;
// }
// }
// catch (MySqlException ex)
// {
// m_log.Error("[OPENSIMINVENTORYSTORAGE]: Connection to MySQL backend failed: " + ex.Message);
// ret = BackendResponse.Failure;
// }
//}
//m_server.MetricsProvider.LogInventoryFetch(EXTENSION_NAME, ret, owner, itemID, false, DateTime.Now);
//return ret;
m_log.Warn("[OPENSIMINVENTORYSTORAGE]: Called TryFetchItem which is not implemented.");
return BackendResponse.Success;
}
public BackendResponse TryFetchFolder(Uri owner, UUID folderID, out InventoryFolderWithChildren folder)
{
BackendResponse ret;
// TODO: implement some logic for "folder not found"
folder = m_inventoryService.GetInventoryFolder(folderID);
ret = BackendResponse.Success;
m_server.MetricsProvider.LogInventoryFetch(EXTENSION_NAME, ret, owner, folderID, true, DateTime.Now);
return ret;
}
public BackendResponse TryFetchFolderContents(Uri owner, UUID folderID, out InventoryCollection contents)
{
contents = null;
//BackendResponse ret;
//using (MySqlConnection dbConnection = new MySqlConnection(m_openSimConfig.GetString("inventory_database_connect")))
//{
// IDataReader reader;
// try
// {
// dbConnection.Open();
// contents = new InventoryCollection();
// #region Folder retrieval
// IDbCommand command = dbConnection.CreateCommand();
// command.CommandText = String.Format("SELECT folderName,type,version,agentID,folderID FROM inventoryfolders WHERE parentFolderID='{0}'",
// folderID.ToString());
// reader = command.ExecuteReader();
// contents.Folders = new Dictionary<UUID, InventoryFolderWithChildren>();
// while (reader.Read())
// {
// InventoryFolderWithChildren folder = new InventoryFolderWithChildren();
// folder.ParentID = folderID;
// folder.Children = null; // This call doesn't do recursion
// folder.Name = reader.GetString(0);
// folder.Type = reader.GetInt16(1);
// folder.Version = (ushort)reader.GetInt16(2);
// folder.Owner = UUID.Parse(reader.GetString(3));
// folder.ID = UUID.Parse(reader.GetString(4));
// contents.Folders.Add(folder.ID, folder);
// contents.UserID = folder.Owner;
// }
// reader.Close();
// #endregion Folder retrieval
// #region Item retrieval
// command = dbConnection.CreateCommand();
// command.CommandText = String.Format("SELECT assetID,assetType,inventoryName,inventoryDescription,inventoryNextPermissions," +
// "inventoryCurrentPermissions,invType,creatorID,inventoryBasePermissions,inventoryEveryOnePermissions,salePrice,saleType," +
// "creationDate,groupID,groupOwned,flags,avatarID,inventoryID,inventoryGroupPermissions FROM inventoryitems WHERE parentFolderID='{0}'",
// folderID.ToString());
// reader = command.ExecuteReader();
// contents.Items = new Dictionary<UUID, InventoryItemBase>();
// while (reader.Read())
// {
// InventoryItemBase item = new InventoryItemBase();
// item.Folder = folderID;
// item.AssetID = UUID.Parse(reader.GetString(0));
// item.AssetType = reader.GetInt32(1);
// item.Name = reader.GetString(2);
// item.Description = reader.GetString(3);
// item.NextPermissions = (uint)reader.GetInt32(4);
// item.CurrentPermissions = (uint)reader.GetInt32(5);
// item.InvType = reader.GetInt32(6);
// item.Creator = UUID.Parse(reader.GetString(7));
// item.BasePermissions = (uint)reader.GetInt32(8);
// item.EveryOnePermissions = (uint)reader.GetInt32(9);
// item.SalePrice = reader.GetInt32(10);
// item.SaleType = reader.GetByte(11);
// item.CreationDate = reader.GetInt32(12);
// item.GroupID = UUID.Parse(reader.GetString(13));
// item.GroupOwned = reader.GetBoolean(14);
// item.Flags = (uint)reader.GetInt32(15);
// item.Owner = UUID.Parse(reader.GetString(16));
// item.ID = UUID.Parse(reader.GetString(17));
// item.GroupPermissions = (uint)reader.GetInt32(18);
// contents.Items.Add(item.ID, item);
// contents.UserID = item.Owner;
// }
// #endregion Item retrieval
// ret = BackendResponse.Success;
// }
// catch (MySqlException ex)
// {
// m_log.Error("[OPENSIMINVENTORYSTORAGE]: Connection to MySQL backend failed: " + ex.Message);
// ret = BackendResponse.Failure;
// }
//}
//m_server.MetricsProvider.LogInventoryFetchFolderContents(EXTENSION_NAME, ret, owner, folderID, DateTime.Now);
//return ret;
m_log.Warn("[OPENSIMINVENTORYSTORAGE]: Called TryFetchFolderContents which is not implemented.");
return BackendResponse.Success;
}
public BackendResponse TryFetchFolderList(Uri owner, out List<InventoryFolderWithChildren> folders)
{
folders = new List<InventoryFolderWithChildren>();
BackendResponse ret;
UUID ownerID;
if (Utils.TryGetOpenSimUUID(owner, out ownerID))
{
List<InventoryFolderBase> baseFolders = m_inventoryService.GetInventorySkeleton(ownerID);
foreach (InventoryFolderBase baseFolder in baseFolders)
{
InventoryFolderWithChildren folder = new InventoryFolderWithChildren(baseFolder);
//folder.Children = null; // This call does not create a folder hierarchy
folders.Add(folder);
}
ret = BackendResponse.Success;
}
else
{
folders = null;
ret = BackendResponse.NotFound;
}
m_server.MetricsProvider.LogInventoryFetchFolderList(EXTENSION_NAME, ret, owner, DateTime.Now);
return ret;
}
public BackendResponse TryFetchInventory(Uri owner, out InventoryCollection inventory)
{
inventory = null;
BackendResponse ret;
List<InventoryFolderWithChildren> folders;
ret = TryFetchFolderList(owner, out folders);
if (ret == BackendResponse.Success)
{
// Add the retrieved folders to the inventory collection
inventory = new InventoryCollection();
inventory.Folders = new Dictionary<UUID, InventoryFolderWithChildren>(folders.Count);
foreach (InventoryFolderWithChildren folder in folders)
inventory.Folders[folder.ID] = folder;
// Fetch inventory items
UUID ownerID;
if (Utils.TryGetOpenSimUUID(owner, out ownerID))
{
inventory.UserID = ownerID;
inventory.Items = new Dictionary<UUID, InventoryItemBase>();
foreach (InventoryFolderWithChildren folder in folders)
{
foreach (InventoryItemBase item in m_inventoryService.RequestFolderItems(folder.ID))
{
inventory.Items.Add(item.ID, item);
}
}
ret = BackendResponse.Success;
}
else
{
ret = BackendResponse.NotFound;
}
}
m_server.MetricsProvider.LogInventoryFetchInventory(EXTENSION_NAME, ret, owner, DateTime.Now);
return ret;
}
public BackendResponse TryFetchActiveGestures(Uri owner, out List<InventoryItemBase> gestures)
{
gestures = null;
BackendResponse ret;
UUID ownerID;
if (Utils.TryGetOpenSimUUID(owner, out ownerID))
{
gestures = m_inventoryService.GetActiveGestures(ownerID);
ret = BackendResponse.Success;
}
else
{
ret = BackendResponse.NotFound;
}
m_server.MetricsProvider.LogInventoryFetchActiveGestures(EXTENSION_NAME, ret, owner, DateTime.Now);
return ret;
}
public BackendResponse TryCreateItem(Uri owner, InventoryItemBase item)
{
BackendResponse ret;
if (m_inventoryService.AddItem(item))
{
ret = BackendResponse.Success;
}
else
{
ret = BackendResponse.Failure;
}
m_server.MetricsProvider.LogInventoryCreate(EXTENSION_NAME, ret, owner, false, DateTime.Now);
return ret;
}
public BackendResponse TryCreateFolder(Uri owner, InventoryFolderWithChildren folder)
{
BackendResponse ret;
if (m_inventoryService.AddFolder(folder))
{
ret = BackendResponse.Success;
}
else
{
ret = BackendResponse.Failure;
}
m_server.MetricsProvider.LogInventoryCreate(EXTENSION_NAME, ret, owner, true, DateTime.Now);
return ret;
}
public BackendResponse TryCreateInventory(Uri owner, InventoryFolderWithChildren rootFolder)
{
BackendResponse ret;
UUID ownerID;
if (Utils.TryGetOpenSimUUID(owner, out ownerID))
{
if (m_inventoryService.CreateNewUserInventory(ownerID))
{
ret = BackendResponse.Success;
}
else
{
ret = BackendResponse.Failure;
}
}
else
{
ret = BackendResponse.Failure;
}
return ret;
}
public BackendResponse TryDeleteItem(Uri owner, UUID itemID)
{
BackendResponse ret;
if (m_inventoryService.DeleteItem(m_inventoryService.GetInventoryItem(itemID)))
{
ret = BackendResponse.Success;
}
else
{
ret = BackendResponse.Failure;
}
m_server.MetricsProvider.LogInventoryDelete(EXTENSION_NAME, ret, owner, itemID, false, DateTime.Now);
return ret;
}
public BackendResponse TryDeleteFolder(Uri owner, UUID folderID)
{
//BackendResponse ret;
//UUID ownerID;
//if (Utils.TryGetOpenSimUUID(owner, out ownerID))
//{
// using (MySqlConnection dbConnection = new MySqlConnection(m_openSimConfig.GetString("inventory_database_connect")))
// {
// try
// {
// dbConnection.Open();
// MySqlCommand command = new MySqlCommand(
// "DELETE FROM inventoryfolders WHERE folderID=?folderID AND agentID=?agentID", dbConnection);
// command.Parameters.AddWithValue("?folderID", folderID.ToString());
// command.Parameters.AddWithValue("?agentID", ownerID.ToString());
// int rowsAffected = command.ExecuteNonQuery();
// if (rowsAffected == 1)
// {
// ret = BackendResponse.Success;
// }
// else
// {
// m_log.ErrorFormat("[OPENSIMINVENTORYSTORAGE]: MySQL DELETE query affected {0} rows", rowsAffected);
// ret = BackendResponse.NotFound;
// }
// }
// catch (MySqlException ex)
// {
// m_log.Error("[OPENSIMINVENTORYSTORAGE]: Connection to MySQL backend failed: " + ex.Message);
// ret = BackendResponse.Failure;
// }
// }
//}
//else
//{
// ret = BackendResponse.NotFound;
//}
//m_server.MetricsProvider.LogInventoryDelete(EXTENSION_NAME, ret, owner, folderID, true, DateTime.Now);
//return ret;
m_log.Warn("[OPENSIMINVENTORYSTORAGE]: Called TryDeleteFolder which is not implemented.");
return BackendResponse.Success;
}
public BackendResponse TryPurgeFolder(Uri owner, UUID folderID)
{
BackendResponse ret;
if (m_inventoryService.PurgeFolder(m_inventoryService.GetInventoryFolder(folderID)))
{
ret = BackendResponse.Success;
}
else
{
ret = BackendResponse.Failure;
}
m_server.MetricsProvider.LogInventoryPurgeFolder(EXTENSION_NAME, ret, owner, folderID, DateTime.Now);
return ret;
}
public int ForEach(Action<AssetMetadata> action, int start, int count)
{
int rowCount = 0;
//using (MySqlConnection dbConnection = new MySqlConnection(m_openSimConfig.GetString("inventory_database_connect")))
//{
// MySqlDataReader reader;
// try
// {
// dbConnection.Open();
// MySqlCommand command = dbConnection.CreateCommand();
// command.CommandText = String.Format("SELECT name,description,assetType,temporary,data,id FROM assets LIMIT {0}, {1}",
// start, count);
// reader = command.ExecuteReader();
// }
// catch (MySqlException ex)
// {
// m_log.Error("[OPENSIMINVENTORYSTORAGE]: Connection to MySQL backend failed: " + ex.Message);
// return 0;
// }
// while (reader.Read())
// {
// Metadata metadata = new Metadata();
// metadata.CreationDate = OpenMetaverse.Utils.Epoch;
// metadata.Description = reader.GetString(1);
// metadata.ID = UUID.Parse(reader.GetString(5));
// metadata.Name = reader.GetString(0);
// metadata.SHA1 = OpenMetaverse.Utils.SHA1((byte[])reader.GetValue(4));
// metadata.Temporary = reader.GetBoolean(3);
// metadata.ContentType = Utils.SLAssetTypeToContentType(reader.GetInt32(2));
// action(metadata);
// ++rowCount;
// }
// reader.Close();
//}
return rowCount;
}
#endregion IInventoryStorageProvider implementation
#region IPlugin implementation
public void Initialise(AssetInventoryServer server)
{
m_server = server;
m_openSimConfig = server.ConfigFile.Configs["OpenSim"];
m_inventoryService = new OpenSimInventoryService();
m_inventoryService.AddPlugin(m_openSimConfig.GetString("inventory_database_provider"),
m_openSimConfig.GetString("inventory_database_connect"));
}
public void Stop()
{
}
public void Initialise()
{
m_log.InfoFormat("[OPENSIMINVENTORYSTORAGE]: {0} cannot be default-initialized!", Name);
throw new PluginNotInitialisedException(Name);
}
public void Dispose()
{
}
public string Version
{
// TODO: this should be something meaningful and not hardcoded?
get { return "0.1"; }
}
public string Name
{
get { return "OpenSimInventoryStorage"; }
}
#endregion IPlugin implementation
}
}

View File

@ -1,27 +0,0 @@
<Addin id="OpenSim.Grid.AssetInventoryServer.Plugins.OpenSim" version="0.1">
<Runtime>
<Import assembly="OpenSim.Grid.AssetInventoryServer.Plugins.OpenSim.dll" />
<Import assembly="OpenSim.Data.dll" />
</Runtime>
<Dependencies>
<Addin id="OpenSim.Grid.AssetInventoryServer" version="0.1" />
</Dependencies>
<ExtensionPoint path = "/OpenSim/AssetData">
<ExtensionNode name="Plugin" type="OpenSim.Framework.PluginExtensionNode" objectType="OpenSim.Data.IAssetDataPlugin" />
</ExtensionPoint>
<Extension path="/OpenSim/AssetInventoryServer/AssetStorageProvider">
<Plugin id="OpenSimAssetStorage" provider="OpenSim.Grid.AssetInventoryServer.Plugins.OpenSim.dll" type="OpenSim.Grid.AssetInventoryServer.Plugins.OpenSim.OpenSimAssetStoragePlugin" />
</Extension>
<Extension path="/OpenSim/AssetInventoryServer/InventoryStorageProvider">
<Plugin id="OpenSimInventoryStorage" provider="OpenSim.Grid.AssetInventoryServer.Plugins.OpenSim.dll" type="OpenSim.Grid.AssetInventoryServer.Plugins.OpenSim.OpenSimInventoryStoragePlugin" />
</Extension>
<Extension path="/OpenSim/AssetInventoryServer/Frontend">
<Plugin id="OpenSimAssetFrontend" provider="OpenSim.Grid.AssetInventoryServer.Plugins.OpenSim.dll" type="OpenSim.Grid.AssetInventoryServer.Plugins.OpenSim.OpenSimAssetFrontendPlugin" />
</Extension>
<Extension path="/OpenSim/AssetInventoryServer/Frontend">
<Plugin id="OpenSimInventoryFrontend" provider="OpenSim.Grid.AssetInventoryServer.Plugins.OpenSim.dll" type="OpenSim.Grid.AssetInventoryServer.Plugins.OpenSim.OpenSimInventoryFrontendPlugin" />
</Extension>
</Addin>

View File

@ -1,369 +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.IO;
using System.Reflection;
using System.Net;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using log4net;
namespace OpenSim.Grid.AssetInventoryServer.Plugins
{
public class ReferenceFrontendPlugin : IAssetInventoryServerPlugin
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
AssetInventoryServer m_server;
public ReferenceFrontendPlugin()
{
}
#region IPlugin implementation
public void Initialise(AssetInventoryServer server)
{
m_server = server;
// Asset metadata request
//m_server.HttpServer.AddStreamHandler(new MetadataRequestHandler(server));
// Asset data request
m_server.HttpServer.AddStreamHandler(new DataRequestHandler(server));
// Asset creation
//m_server.HttpServer.AddStreamHandler(new CreateRequestHandler(server));
m_log.Info("[REFERENCEFRONTEND]: Reference Frontend loaded.");
}
/// <summary>
/// <para>Initialises asset interface</para>
/// </summary>
public void Initialise()
{
m_log.InfoFormat("[REFERENCEFRONTEND]: {0} cannot be default-initialized!", Name);
throw new PluginNotInitialisedException(Name);
}
public void Dispose()
{
}
public string Version
{
// TODO: this should be something meaningful and not hardcoded?
get { return "0.1"; }
}
public string Name
{
get { return "ReferenceFrontend"; }
}
#endregion IPlugin implementation
//public class MetadataRequestHandler : IStreamedRequestHandler
//{
// AssetInventoryServer m_server;
// string m_contentType;
// string m_httpMethod;
// string m_path;
// public MetadataRequestHandler(AssetInventoryServer server)
// {
// m_server = server;
// m_contentType = null;
// m_httpMethod = "GET";
// m_path = @"^/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/metadata";
// }
// #region IStreamedRequestHandler implementation
// public string ContentType
// {
// get { return m_contentType; }
// }
// public string HttpMethod
// {
// get { return m_httpMethod; }
// }
// public string Path
// {
// get { return m_path; }
// }
// public byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
// {
// byte[] serializedData = null;
// UUID assetID;
// // Split the URL up into an AssetID and a method
// string[] rawUrl = httpRequest.Url.PathAndQuery.Split('/');
// if (rawUrl.Length >= 3 && UUID.TryParse(rawUrl[1], out assetID))
// {
// UUID authToken = Utils.GetAuthToken(httpRequest);
// if (m_server.AuthorizationProvider.IsMetadataAuthorized(authToken, assetID))
// {
// AssetMetadata metadata;
// BackendResponse storageResponse = m_server.StorageProvider.TryFetchMetadata(assetID, out metadata);
// if (storageResponse == BackendResponse.Success)
// {
// // If the asset data location wasn't specified in the metadata, specify it
// // manually here by pointing back to this asset server
// if (!metadata.Methods.ContainsKey("data"))
// {
// metadata.Methods["data"] = new Uri(String.Format("{0}://{1}/{2}/data",
// httpRequest.Url.Scheme, httpRequest.Url.Authority, assetID));
// }
// serializedData = metadata.SerializeToBytes();
// httpResponse.StatusCode = (int) HttpStatusCode.OK;
// httpResponse.ContentType = "application/json";
// httpResponse.ContentLength = serializedData.Length;
// httpResponse.Body.Write(serializedData, 0, serializedData.Length);
// }
// else if (storageResponse == BackendResponse.NotFound)
// {
// m_log.Warn("[REFERENCEFRONTEND]: Could not find metadata for asset " + assetID.ToString());
// httpResponse.StatusCode = (int) HttpStatusCode.NotFound;
// }
// else
// {
// httpResponse.StatusCode = (int) HttpStatusCode.InternalServerError;
// }
// }
// else
// {
// httpResponse.StatusCode = (int) HttpStatusCode.Forbidden;
// }
// return serializedData;
// }
// httpResponse.StatusCode = (int) HttpStatusCode.NotFound;
// return serializedData;
// }
// #endregion IStreamedRequestHandler implementation
//}
public class DataRequestHandler : IStreamedRequestHandler
{
AssetInventoryServer m_server;
string m_contentType;
string m_httpMethod;
string m_path;
public DataRequestHandler(AssetInventoryServer server)
{
m_server = server;
m_contentType = null;
m_httpMethod = "GET";
m_path = @"^/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/data";
}
#region IStreamedRequestHandler implementation
public string ContentType
{
get { return m_contentType; }
}
public string HttpMethod
{
get { return m_httpMethod; }
}
public string Path
{
get { return m_path; }
}
public byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
byte[] assetData = null;
UUID assetID;
// Split the URL up into an AssetID and a method
string[] rawUrl = httpRequest.Url.PathAndQuery.Split('/');
if (rawUrl.Length >= 3 && UUID.TryParse(rawUrl[1], out assetID))
{
UUID authToken = Utils.GetAuthToken(httpRequest);
if (m_server.AuthorizationProvider.IsDataAuthorized(authToken, assetID))
{
BackendResponse storageResponse = m_server.StorageProvider.TryFetchData(assetID, out assetData);
if (storageResponse == BackendResponse.Success)
{
httpResponse.StatusCode = (int) HttpStatusCode.OK;
httpResponse.ContentType = "application/octet-stream";
httpResponse.AddHeader("Content-Disposition", "attachment; filename=" + assetID.ToString());
httpResponse.ContentLength = assetData.Length;
httpResponse.Body.Write(assetData, 0, assetData.Length);
}
else if (storageResponse == BackendResponse.NotFound)
{
httpResponse.StatusCode = (int) HttpStatusCode.NotFound;
}
else
{
httpResponse.StatusCode = (int) HttpStatusCode.InternalServerError;
}
}
else
{
httpResponse.StatusCode = (int) HttpStatusCode.Forbidden;
}
return assetData;
}
httpResponse.StatusCode = (int) HttpStatusCode.BadRequest;
return assetData;
}
#endregion IStreamedRequestHandler implementation
}
//public class CreateRequestHandler : IStreamedRequestHandler
//{
// AssetInventoryServer m_server;
// string m_contentType;
// string m_httpMethod;
// string m_path;
// public CreateRequestHandler(AssetInventoryServer server)
// {
// m_server = server;
// m_contentType = null;
// m_httpMethod = "POST";
// m_path = "^/createasset";
// }
// #region IStreamedRequestHandler implementation
// public string ContentType
// {
// get { return m_contentType; }
// }
// public string HttpMethod
// {
// get { return m_httpMethod; }
// }
// public string Path
// {
// get { return m_path; }
// }
// public byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
// {
// byte[] responseData = null;
// UUID authToken = Utils.GetAuthToken(httpRequest);
// if (m_server.AuthorizationProvider.IsCreateAuthorized(authToken))
// {
// try
// {
// OSD osdata = OSDParser.DeserializeJson(new StreamReader(httpRequest.InputStream).ReadToEnd());
// if (osdata.Type == OSDType.Map)
// {
// OSDMap map = (OSDMap)osdata;
// Metadata metadata = new Metadata();
// metadata.Deserialize(map);
// byte[] assetData = map["data"].AsBinary();
// if (assetData != null && assetData.Length > 0)
// {
// BackendResponse storageResponse;
// if (metadata.ID != UUID.Zero)
// storageResponse = m_server.StorageProvider.TryCreateAsset(metadata, assetData);
// else
// storageResponse = m_server.StorageProvider.TryCreateAsset(metadata, assetData, out metadata.ID);
// if (storageResponse == BackendResponse.Success)
// {
// httpResponse.StatusCode = (int) HttpStatusCode.Created;
// OSDMap responseMap = new OSDMap(1);
// responseMap["id"] = OSD.FromUUID(metadata.ID);
// LitJson.JsonData jsonData = OSDParser.SerializeJson(responseMap);
// responseData = System.Text.Encoding.UTF8.GetBytes(jsonData.ToJson());
// httpResponse.Body.Write(responseData, 0, responseData.Length);
// httpResponse.Body.Flush();
// }
// else if (storageResponse == BackendResponse.NotFound)
// {
// httpResponse.StatusCode = (int) HttpStatusCode.NotFound;
// }
// else
// {
// httpResponse.StatusCode = (int) HttpStatusCode.InternalServerError;
// }
// }
// else
// {
// httpResponse.StatusCode = (int) HttpStatusCode.BadRequest;
// }
// }
// else
// {
// httpResponse.StatusCode = (int) HttpStatusCode.BadRequest;
// }
// }
// catch (Exception ex)
// {
// httpResponse.StatusCode = (int) HttpStatusCode.InternalServerError;
// httpResponse.StatusDescription = ex.Message;
// }
// }
// else
// {
// httpResponse.StatusCode = (int) HttpStatusCode.Forbidden;
// }
// return responseData;
// }
// #endregion IStreamedRequestHandler implementation
//}
}
}

View File

@ -1,28 +0,0 @@
<Addin id="OpenSim.Grid.AssetInventoryServer.Plugins" version="0.1">
<Runtime>
<Import assembly="OpenSim.Grid.AssetInventoryServer.Plugins.dll" />
</Runtime>
<Dependencies>
<Addin id="OpenSim.Grid.AssetInventoryServer" version="0.1" />
</Dependencies>
<Extension path="/OpenSim/AssetInventoryServer/MetricsProvider">
<Plugin id="NullMetrics" provider="OpenSim.Grid.AssetInventoryServer.Plugins.dll" type="OpenSim.Grid.AssetInventoryServer.Plugins.NullMetricsPlugin" />
</Extension>
<Extension path="/OpenSim/AssetInventoryServer/Frontend">
<Plugin id="BrowseFrontend" provider="OpenSim.Grid.AssetInventoryServer.Plugins.dll" type="OpenSim.Grid.AssetInventoryServer.Plugins.BrowseFrontendPlugin" />
</Extension>
<Extension path="/OpenSim/AssetInventoryServer/Frontend">
<Plugin id="ReferenceFrontend" provider="OpenSim.Grid.AssetInventoryServer.Plugins.dll" type="OpenSim.Grid.AssetInventoryServer.Plugins.ReferenceFrontendPlugin" />
</Extension>
<Extension path="/OpenSim/AssetInventoryServer/AuthenticationProvider">
<Plugin id="NullAuthentication" provider="OpenSim.Grid.AssetInventoryServer.Plugins.dll" type="OpenSim.Grid.AssetInventoryServer.Plugins.NullAuthenticationPlugin" />
</Extension>
<Extension path="/OpenSim/AssetInventoryServer/AuthorizationProvider">
<Plugin id="AuthorizeAll" provider="OpenSim.Grid.AssetInventoryServer.Plugins.dll" type="OpenSim.Grid.AssetInventoryServer.Plugins.AuthorizeAllPlugin" />
</Extension>
<Extension path="/OpenSim/AssetInventoryServer/Frontend">
<Plugin id="InventoryArchive" provider="OpenSim.Grid.AssetInventoryServer.Plugins.dll" type="OpenSim.Grid.AssetInventoryServer.Plugins.InventoryArchivePlugin" />
</Extension>
</Addin>

View File

@ -1,16 +0,0 @@
<Addin id="OpenSim.Grid.AssetInventoryServer.Plugins.Simple" version="0.1">
<Runtime>
<Import assembly="OpenSim.Grid.AssetInventoryServer.Plugins.Simple.dll" />
</Runtime>
<Dependencies>
<Addin id="OpenSim.Grid.AssetInventoryServer" version="0.1" />
</Dependencies>
<Extension path="/OpenSim/AssetInventoryServer/AssetStorageProvider">
<Plugin id="SimpleAssetStorage" provider="OpenSim.Grid.AssetInventoryServer.Plugins.Simple.dll" type="OpenSim.Grid.AssetInventoryServer.Plugins.Simple.SimpleAssetStoragePlugin" />
</Extension>
<Extension path="/OpenSim/AssetInventoryServer/InventoryStorageProvider">
<Plugin id="SimpleInventoryStorage" provider="OpenSim.Grid.AssetInventoryServer.Plugins.Simple.dll" type="OpenSim.Grid.AssetInventoryServer.Plugins.Simple.SimpleInventoryStoragePlugin" />
</Extension>
</Addin>

View File

@ -1,290 +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.Reflection;
using System.Collections.Generic;
using System.IO;
using OpenMetaverse;
using OpenSim.Framework;
using log4net;
namespace OpenSim.Grid.AssetInventoryServer.Plugins.Simple
{
public class SimpleAssetStoragePlugin : IAssetStorageProvider
{
const string EXTENSION_NAME = "SimpleAssetStorage"; // Used in metrics reporting
const string DEFAULT_DATA_DIR = "SimpleAssets";
const string TEMP_DATA_DIR = "SimpleAssetsTemp";
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
AssetInventoryServer server;
Dictionary<UUID, AssetMetadata> metadataStorage;
Dictionary<UUID, string> filenames;
public SimpleAssetStoragePlugin()
{
}
#region Required Interfaces
public BackendResponse TryFetchMetadata(UUID assetID, out AssetMetadata metadata)
{
metadata = null;
BackendResponse ret;
if (metadataStorage.TryGetValue(assetID, out metadata))
ret = BackendResponse.Success;
else
ret = BackendResponse.NotFound;
server.MetricsProvider.LogAssetMetadataFetch(EXTENSION_NAME, ret, assetID, DateTime.Now);
return ret;
}
public BackendResponse TryFetchData(UUID assetID, out byte[] assetData)
{
assetData = null;
string filename;
BackendResponse ret;
if (filenames.TryGetValue(assetID, out filename))
{
try
{
assetData = File.ReadAllBytes(filename);
ret = BackendResponse.Success;
}
catch (Exception ex)
{
m_log.ErrorFormat("[SIMPLEASSETSTORAGE]: Failed reading data for asset {0} from {1}: {2}", assetID, filename, ex.Message);
ret = BackendResponse.Failure;
}
}
else
{
ret = BackendResponse.NotFound;
}
server.MetricsProvider.LogAssetDataFetch(EXTENSION_NAME, ret, assetID, (assetData != null ? assetData.Length : 0), DateTime.Now);
return ret;
}
public BackendResponse TryFetchDataMetadata(UUID assetID, out AssetBase asset)
{
asset = new AssetBase();
AssetMetadata metadata = asset.Metadata;
string filename;
BackendResponse ret;
if (metadataStorage.TryGetValue(assetID, out metadata) &&
filenames.TryGetValue(assetID, out filename))
{
try
{
asset.Data = File.ReadAllBytes(filename);
ret = BackendResponse.Success;
}
catch (Exception ex)
{
m_log.ErrorFormat("[SIMPLEASSETSTORAGE]: Failed reading data for asset {0} from {1}: {2}", assetID, filename, ex.Message);
ret = BackendResponse.Failure;
}
asset.Type = (sbyte) Utils.ContentTypeToSLAssetType(metadata.ContentType);
asset.Local = false;
}
else
{
asset = null;
ret = BackendResponse.NotFound;
}
server.MetricsProvider.LogAssetMetadataFetch(EXTENSION_NAME, ret, assetID, DateTime.Now);
server.MetricsProvider.LogAssetDataFetch(EXTENSION_NAME, ret, assetID, (asset != null && asset.Data != null ? asset.Data.Length : 0), DateTime.Now);
return ret;
}
public BackendResponse TryCreateAsset(AssetBase asset, out UUID assetID)
{
assetID = asset.FullID = UUID.Random();
return TryCreateAsset(asset);
}
public BackendResponse TryCreateAsset(AssetBase asset)
{
BackendResponse ret;
AssetMetadata metadata = asset.Metadata;
string path;
string filename = String.Format("{0}.{1}", asset.FullID, Utils.ContentTypeToExtension(metadata.ContentType));
if (asset.Temporary)
path = Path.Combine(TEMP_DATA_DIR, filename);
else
path = Path.Combine(DEFAULT_DATA_DIR, filename);
try
{
File.WriteAllBytes(path, asset.Data);
lock (filenames) filenames[asset.FullID] = path;
// Set the creation date to right now
metadata.CreationDate = DateTime.Now;
lock (metadataStorage)
metadataStorage[asset.FullID] = metadata;
ret = BackendResponse.Success;
}
catch (Exception ex)
{
m_log.ErrorFormat("[SIMPLEASSETSTORAGE]: Failed writing data for asset {0} to {1}: {2}", asset.FullID, filename, ex.Message);
ret = BackendResponse.Failure;
}
server.MetricsProvider.LogAssetCreate(EXTENSION_NAME, ret, asset.FullID, asset.Data.Length, DateTime.Now);
return ret;
}
public int ForEach(Action<AssetMetadata> action, int start, int count)
{
int rowCount = 0;
//lock (metadataStorage)
//{
// foreach (Metadata metadata in metadataStorage.Values)
// {
// action(metadata);
// ++rowCount;
// }
//}
return rowCount;
}
#endregion Required Interfaces
#region IPlugin implementation
public void Initialise(AssetInventoryServer server)
{
this.server = server;
metadataStorage = new Dictionary<UUID, AssetMetadata>();
filenames = new Dictionary<UUID, string>();
LoadFiles(DEFAULT_DATA_DIR, false);
LoadFiles(TEMP_DATA_DIR, true);
m_log.InfoFormat("[SIMPLEASSETSTORAGE]: Initialized the store index with metadata for {0} assets",
metadataStorage.Count);
}
/// <summary>
/// <para>Initialises asset interface</para>
/// </summary>
public void Initialise()
{
m_log.InfoFormat("[SIMPLEASSETSTORAGE]: {0} cannot be default-initialized!", Name);
throw new PluginNotInitialisedException(Name);
}
public void Dispose()
{
WipeTemporary();
}
public string Version
{
// TODO: this should be something meaningful and not hardcoded?
get { return "0.1"; }
}
public string Name
{
get { return "SimpleAssetStorage"; }
}
#endregion IPlugin implementation
public void WipeTemporary()
{
if (Directory.Exists(TEMP_DATA_DIR))
{
try { Directory.Delete(TEMP_DATA_DIR); }
catch (Exception ex) { m_log.Error("[SIMPLEASSETSTORAGE]: " + ex.Message); }
}
}
void LoadFiles(string folder, bool temporary)
{
// Try to create the directory if it doesn't already exist
if (!Directory.Exists(folder))
{
try { Directory.CreateDirectory(folder); }
catch (Exception ex)
{
m_log.Warn("[SIMPLEASSETSTORAGE]: " + ex.Message);
return;
}
}
lock (metadataStorage)
{
try
{
string[] assets = Directory.GetFiles(folder);
for (int i = 0; i < assets.Length; i++)
{
string filename = assets[i];
byte[] data = File.ReadAllBytes(filename);
AssetMetadata metadata = new AssetMetadata();
metadata.CreationDate = File.GetCreationTime(filename);
metadata.Description = String.Empty;
metadata.FullID = SimpleUtils.ParseUUIDFromFilename(filename);
metadata.Name = SimpleUtils.ParseNameFromFilename(filename);
metadata.SHA1 = OpenMetaverse.Utils.SHA1(data);
metadata.Temporary = false;
metadata.ContentType = Utils.ExtensionToContentType(Path.GetExtension(filename).TrimStart('.'));
// Store the loaded data
metadataStorage[metadata.FullID] = metadata;
filenames[metadata.FullID] = filename;
}
}
catch (Exception ex)
{
m_log.Warn("[SIMPLEASSETSTORAGE]: " + ex.Message);
}
}
}
}
}

View File

@ -1,625 +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.Reflection;
using System.Collections.Generic;
using System.IO;
using System.Text;
using OpenMetaverse;
using OpenSim.Framework;
using log4net;
namespace OpenSim.Grid.AssetInventoryServer.Plugins.Simple
{
public class SimpleInventoryStoragePlugin : IInventoryStorageProvider
{
const string EXTENSION_NAME = "SimpleInventoryStorage"; // Used for metrics reporting
const string DEFAULT_INVENTORY_DIR = "SimpleInventory";
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
AssetInventoryServer server;
Dictionary<Uri, InventoryCollection> inventories = new Dictionary<Uri, InventoryCollection>();
Dictionary<Uri, List<InventoryItemBase>> activeGestures = new Dictionary<Uri, List<InventoryItemBase>>();
Utils.InventoryItemSerializer itemSerializer = new Utils.InventoryItemSerializer();
Utils.InventoryFolderSerializer folderSerializer = new Utils.InventoryFolderSerializer();
public SimpleInventoryStoragePlugin()
{
}
#region Required Interfaces
public BackendResponse TryFetchItem(Uri owner, UUID itemID, out InventoryItemBase item)
{
item = null;
BackendResponse ret;
InventoryCollection collection;
if (inventories.TryGetValue(owner, out collection) && collection.Items.TryGetValue(itemID, out item))
ret = BackendResponse.Success;
else
ret = BackendResponse.NotFound;
server.MetricsProvider.LogInventoryFetch(EXTENSION_NAME, ret, owner, itemID, false, DateTime.Now);
return ret;
}
public BackendResponse TryFetchFolder(Uri owner, UUID folderID, out InventoryFolderWithChildren folder)
{
folder = null;
BackendResponse ret;
InventoryCollection collection;
if (inventories.TryGetValue(owner, out collection) && collection.Folders.TryGetValue(folderID, out folder))
ret = BackendResponse.Success;
else
ret = BackendResponse.NotFound;
server.MetricsProvider.LogInventoryFetch(EXTENSION_NAME, ret, owner, folderID, true, DateTime.Now);
return ret;
}
public BackendResponse TryFetchFolderContents(Uri owner, UUID folderID, out InventoryCollection contents)
{
contents = null;
BackendResponse ret;
InventoryCollection collection;
InventoryFolderWithChildren folder;
if (inventories.TryGetValue(owner, out collection) && collection.Folders.TryGetValue(folderID, out folder))
{
contents = new InventoryCollection();
contents.UserID = collection.UserID;
contents.Folders = new Dictionary<UUID, InventoryFolderWithChildren>();
contents.Items = new Dictionary<UUID, InventoryItemBase>();
foreach (InventoryNodeBase invBase in folder.Children.Values)
{
if (invBase is InventoryItemBase)
{
InventoryItemBase invItem = invBase as InventoryItemBase;
contents.Items.Add(invItem.ID, invItem);
}
else
{
InventoryFolderWithChildren invFolder = invBase as InventoryFolderWithChildren;
contents.Folders.Add(invFolder.ID, invFolder);
}
}
ret = BackendResponse.Success;
}
else
{
ret = BackendResponse.NotFound;
}
server.MetricsProvider.LogInventoryFetchFolderContents(EXTENSION_NAME, ret, owner, folderID, DateTime.Now);
return ret;
}
public BackendResponse TryFetchFolderList(Uri owner, out List<InventoryFolderWithChildren> folders)
{
folders = null;
BackendResponse ret;
InventoryCollection collection;
if (inventories.TryGetValue(owner, out collection))
{
folders = new List<InventoryFolderWithChildren>(collection.Folders.Values);
return BackendResponse.Success;
}
else
{
ret = BackendResponse.NotFound;
}
server.MetricsProvider.LogInventoryFetchFolderList(EXTENSION_NAME, ret, owner, DateTime.Now);
return ret;
}
public BackendResponse TryFetchInventory(Uri owner, out InventoryCollection inventory)
{
inventory = null;
BackendResponse ret;
if (inventories.TryGetValue(owner, out inventory))
ret = BackendResponse.Success;
else
ret = BackendResponse.NotFound;
server.MetricsProvider.LogInventoryFetchInventory(EXTENSION_NAME, ret, owner, DateTime.Now);
return ret;
}
public BackendResponse TryFetchActiveGestures(Uri owner, out List<InventoryItemBase> gestures)
{
gestures = null;
BackendResponse ret;
if (activeGestures.TryGetValue(owner, out gestures))
ret = BackendResponse.Success;
else
ret = BackendResponse.NotFound;
server.MetricsProvider.LogInventoryFetchActiveGestures(EXTENSION_NAME, ret, owner, DateTime.Now);
return ret;
}
public BackendResponse TryCreateItem(Uri owner, InventoryItemBase item)
{
BackendResponse ret;
InventoryCollection collection;
if (inventories.TryGetValue(owner, out collection))
{
// Delete this item first if it already exists
InventoryItemBase oldItem;
if (collection.Items.TryGetValue(item.ID, out oldItem))
TryDeleteItem(owner, item.ID);
try
{
// Create the file
SaveItem(item);
// Add the item to the collection
lock (collection) collection.Items[item.ID] = item;
// Add the item to its parent folder
InventoryFolderWithChildren parent;
if (collection.Folders.TryGetValue(item.Folder, out parent))
lock (parent.Children) parent.Children.Add(item.ID, item);
// Add active gestures to our list
if (item.InvType == (int)InventoryType.Gesture && item.Flags == 1)
{
lock (activeGestures)
activeGestures[owner].Add(item);
}
ret = BackendResponse.Success;
}
catch (Exception ex)
{
m_log.Error("[SIMPLEINVENTORYSTORAGE]: " + ex.Message);
ret = BackendResponse.Failure;
}
}
else
{
return BackendResponse.NotFound;
}
server.MetricsProvider.LogInventoryCreate(EXTENSION_NAME, ret, owner, false, DateTime.Now);
return ret;
}
public BackendResponse TryCreateFolder(Uri owner, InventoryFolderWithChildren folder)
{
BackendResponse ret;
InventoryCollection collection;
if (inventories.TryGetValue(owner, out collection))
{
// Delete this folder first if it already exists
InventoryFolderWithChildren oldFolder;
if (collection.Folders.TryGetValue(folder.ID, out oldFolder))
TryDeleteFolder(owner, folder.ID);
try
{
// Create the file
SaveFolder(folder);
// Add the folder to the collection
lock (collection) collection.Folders[folder.ID] = folder;
// Add the folder to its parent folder
InventoryFolderWithChildren parent;
if (collection.Folders.TryGetValue(folder.ParentID, out parent))
lock (parent.Children) parent.Children.Add(folder.ID, folder);
ret = BackendResponse.Success;
}
catch (Exception ex)
{
m_log.Error("[SIMPLEINVENTORYSTORAGE]: " + ex.Message);
ret = BackendResponse.Failure;
}
}
else
{
ret = BackendResponse.NotFound;
}
server.MetricsProvider.LogInventoryCreate(EXTENSION_NAME, ret, owner, true, DateTime.Now);
return ret;
}
public BackendResponse TryCreateInventory(Uri owner, InventoryFolderWithChildren rootFolder)
{
BackendResponse ret;
lock (inventories)
{
if (!inventories.ContainsKey(owner))
{
InventoryCollection collection = new InventoryCollection();
collection.UserID = rootFolder.Owner;
collection.Folders = new Dictionary<UUID, InventoryFolderWithChildren>();
collection.Folders.Add(rootFolder.ID, rootFolder);
collection.Items = new Dictionary<UUID, InventoryItemBase>();
inventories.Add(owner, collection);
ret = BackendResponse.Success;
}
else
{
ret = BackendResponse.Failure;
}
}
if (ret == BackendResponse.Success)
{
string path = Path.Combine(DEFAULT_INVENTORY_DIR, rootFolder.Owner.ToString());
try
{
// Create the directory for this agent
Directory.CreateDirectory(path);
// Create an index.txt containing the UUID and URI for this agent
string[] index = new string[] { rootFolder.Owner.ToString(), owner.ToString() };
File.WriteAllLines(Path.Combine(path, "index.txt"), index);
// Create the root folder file
SaveFolder(rootFolder);
}
catch (Exception ex)
{
m_log.Error("[SIMPLEINVENTORYSTORAGE]: " + ex.Message);
ret = BackendResponse.Failure;
}
}
server.MetricsProvider.LogInventoryCreateInventory(EXTENSION_NAME, ret, DateTime.Now);
return ret;
}
public BackendResponse TryDeleteItem(Uri owner, UUID itemID)
{
BackendResponse ret;
InventoryCollection collection;
InventoryItemBase item;
if (inventories.TryGetValue(owner, out collection) && collection.Items.TryGetValue(itemID, out item))
{
// Remove the item from its parent folder
InventoryFolderWithChildren parent;
if (collection.Folders.TryGetValue(item.Folder, out parent))
lock (parent.Children) parent.Children.Remove(itemID);
// Remove the item from the collection
lock (collection) collection.Items.Remove(itemID);
// Remove from the active gestures list if applicable
if (item.InvType == (int)InventoryType.Gesture)
{
lock (activeGestures)
{
for (int i = 0; i < activeGestures[owner].Count; i++)
{
if (activeGestures[owner][i].ID == itemID)
{
activeGestures[owner].RemoveAt(i);
break;
}
}
}
}
// Delete the file. We don't know exactly what the file name is,
// so search for it
string path = PathFromURI(owner);
string[] matches = Directory.GetFiles(path, String.Format("*{0}.item", itemID), SearchOption.TopDirectoryOnly);
foreach (string match in matches)
{
try { File.Delete(match); }
catch (Exception ex) { m_log.ErrorFormat("[SIMPLEINVENTORYSTORAGE]: Failed to delete file {0}: {1}", match, ex.Message); }
}
ret = BackendResponse.Success;
}
else
{
ret = BackendResponse.NotFound;
}
server.MetricsProvider.LogInventoryDelete(EXTENSION_NAME, ret, owner, itemID, false, DateTime.Now);
return ret;
}
public BackendResponse TryDeleteFolder(Uri owner, UUID folderID)
{
BackendResponse ret;
InventoryCollection collection;
InventoryFolderWithChildren folder;
if (inventories.TryGetValue(owner, out collection) && collection.Folders.TryGetValue(folderID, out folder))
{
// Remove the folder from its parent folder
InventoryFolderWithChildren parent;
if (collection.Folders.TryGetValue(folder.ParentID, out parent))
lock (parent.Children) parent.Children.Remove(folderID);
// Remove the folder from the collection
lock (collection) collection.Items.Remove(folderID);
// Delete the folder file. We don't know exactly what the file name is,
// so search for it
string path = PathFromURI(owner);
string[] matches = Directory.GetFiles(path, String.Format("*{0}.folder", folderID), SearchOption.TopDirectoryOnly);
foreach (string match in matches)
{
try { File.Delete(match); }
catch (Exception ex) { m_log.ErrorFormat("[SIMPLEINVENTORYSTORAGE]: Failed to delete folder file {0}: {1}", match, ex.Message); }
}
ret = BackendResponse.Success;
}
else
{
ret = BackendResponse.NotFound;
}
server.MetricsProvider.LogInventoryDelete(EXTENSION_NAME, ret, owner, folderID, true, DateTime.Now);
return ret;
}
public BackendResponse TryPurgeFolder(Uri owner, UUID folderID)
{
BackendResponse ret;
InventoryCollection collection;
InventoryFolderWithChildren folder;
if (inventories.TryGetValue(owner, out collection) && collection.Folders.TryGetValue(folderID, out folder))
{
// Delete all of the folder children
foreach (InventoryNodeBase obj in new List<InventoryNodeBase>(folder.Children.Values))
{
if (obj is InventoryItemBase)
{
TryDeleteItem(owner, (obj as InventoryItemBase).ID);
}
else
{
InventoryFolderWithChildren childFolder = obj as InventoryFolderWithChildren;
TryPurgeFolder(owner, childFolder.ID);
TryDeleteFolder(owner, childFolder.ID);
}
}
ret = BackendResponse.Success;
}
else
{
ret = BackendResponse.NotFound;
}
server.MetricsProvider.LogInventoryPurgeFolder(EXTENSION_NAME, ret, owner, folderID, DateTime.Now);
return ret;
}
#endregion Required Interfaces
void SaveItem(InventoryItemBase item)
{
string filename = String.Format("{0}-{1}.item", SanitizeFilename(item.Name), item.ID);
string path = Path.Combine(DEFAULT_INVENTORY_DIR, item.Owner.ToString());
path = Path.Combine(path, filename);
using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write))
{
itemSerializer.Serialize(stream, item);
stream.Flush();
}
}
void SaveFolder(InventoryFolderWithChildren folder)
{
string filename = String.Format("{0}-{1}.folder", SanitizeFilename(folder.Name), folder.ID);
string path = Path.Combine(DEFAULT_INVENTORY_DIR, folder.Owner.ToString());
path = Path.Combine(path, filename);
using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write))
{
folderSerializer.Serialize(stream, folder);
stream.Flush();
}
}
string SanitizeFilename(string filename)
{
string output = filename;
if (output.Length > 64)
output = output.Substring(0, 64);
foreach (char i in Path.GetInvalidFileNameChars())
output = output.Replace(i, '_');
return output;
}
static string PathFromURI(Uri uri)
{
byte[] hash = OpenMetaverse.Utils.SHA1(Encoding.UTF8.GetBytes(uri.ToString()));
StringBuilder digest = new StringBuilder(40);
// Convert the hash to a hex string
foreach (byte b in hash)
digest.AppendFormat(OpenMetaverse.Utils.EnUsCulture, "{0:x2}", b);
return Path.Combine(DEFAULT_INVENTORY_DIR, digest.ToString());
}
void LoadFiles(string folder)
{
// Try to create the directory if it doesn't already exist
if (!Directory.Exists(folder))
{
try { Directory.CreateDirectory(folder); }
catch (Exception ex)
{
m_log.Warn("[SIMPLEINVENTORYSTORAGE]: " + ex.Message);
return;
}
}
try
{
string[] agentFolders = Directory.GetDirectories(DEFAULT_INVENTORY_DIR);
for (int i = 0; i < agentFolders.Length; i++)
{
string foldername = agentFolders[i];
string indexPath = Path.Combine(foldername, "index.txt");
UUID ownerID = UUID.Zero;
Uri owner = null;
try
{
string[] index = File.ReadAllLines(indexPath);
ownerID = UUID.Parse(index[0]);
owner = new Uri(index[1]);
}
catch (Exception ex)
{
m_log.WarnFormat("[SIMPLEINVENTORYSTORAGE]: Failed loading the index file {0}: {1}", indexPath, ex.Message);
}
if (ownerID != UUID.Zero && owner != null)
{
// Initialize the active gestures list for this agent
activeGestures.Add(owner, new List<InventoryItemBase>());
InventoryCollection collection = new InventoryCollection();
collection.UserID = ownerID;
// Load all of the folders for this agent
string[] folders = Directory.GetFiles(foldername, "*.folder", SearchOption.TopDirectoryOnly);
collection.Folders = new Dictionary<UUID,InventoryFolderWithChildren>(folders.Length);
for (int j = 0; j < folders.Length; j++)
{
InventoryFolderWithChildren invFolder = (InventoryFolderWithChildren)folderSerializer.Deserialize(
new FileStream(folders[j], FileMode.Open, FileAccess.Read));
collection.Folders[invFolder.ID] = invFolder;
}
// Iterate over the folders collection, adding children to their parents
foreach (InventoryFolderWithChildren invFolder in collection.Folders.Values)
{
InventoryFolderWithChildren parent;
if (collection.Folders.TryGetValue(invFolder.ParentID, out parent))
parent.Children[invFolder.ID] = invFolder;
}
// Load all of the items for this agent
string[] files = Directory.GetFiles(foldername, "*.item", SearchOption.TopDirectoryOnly);
collection.Items = new Dictionary<UUID, InventoryItemBase>(files.Length);
for (int j = 0; j < files.Length; j++)
{
InventoryItemBase invItem = (InventoryItemBase)itemSerializer.Deserialize(
new FileStream(files[j], FileMode.Open, FileAccess.Read));
collection.Items[invItem.ID] = invItem;
// Add items to their parent folders
InventoryFolderWithChildren parent;
if (collection.Folders.TryGetValue(invItem.Folder, out parent))
parent.Children[invItem.ID] = invItem;
// Add active gestures to our list
if (invItem.InvType == (int)InventoryType.Gesture && invItem.Flags != 0)
activeGestures[owner].Add(invItem);
}
inventories.Add(owner, collection);
}
}
}
catch (Exception ex)
{
m_log.ErrorFormat("[SIMPLEINVENTORYSTORAGE]: Failed loading inventory from {0}: {1}", folder, ex.Message);
}
}
#region IPlugin implementation
public void Initialise(AssetInventoryServer server)
{
this.server = server;
LoadFiles(DEFAULT_INVENTORY_DIR);
m_log.InfoFormat("[SIMPLEINVENTORYSTORAGE]: Initialized the inventory index with data for {0} avatars",
inventories.Count);
}
/// <summary>
/// <para>Initialises asset interface</para>
/// </summary>
public void Initialise()
{
m_log.InfoFormat("[SIMPLEINVENTORYSTORAGE]: {0} cannot be default-initialized!", Name);
throw new PluginNotInitialisedException(Name);
}
public void Dispose()
{
}
public string Version
{
// TODO: this should be something meaningful and not hardcoded?
get { return "0.1"; }
}
public string Name
{
get { return "SimpleInventoryStorage"; }
}
#endregion IPlugin implementation
}
}

View File

@ -1,71 +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.IO;
using OpenMetaverse;
namespace OpenSim.Grid.AssetInventoryServer.Plugins.Simple
{
public static class SimpleUtils
{
public static string ParseNameFromFilename(string filename)
{
filename = Path.GetFileName(filename);
int dot = filename.LastIndexOf('.');
int firstDash = filename.IndexOf('-');
if (dot - 37 > 0 && firstDash > 0)
return filename.Substring(0, firstDash);
else
return String.Empty;
}
public static UUID ParseUUIDFromFilename(string filename)
{
int dot = filename.LastIndexOf('.');
if (dot > 35)
{
// Grab the last 36 characters of the filename
string uuidString = filename.Substring(dot - 36, 36);
UUID uuid;
UUID.TryParse(uuidString, out uuid);
return uuid;
}
else
{
UUID uuid;
if (UUID.TryParse(Path.GetFileName(filename), out uuid))
return uuid;
else
return UUID.Zero;
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -140,7 +140,7 @@ namespace OpenSim.Grid.AssetServer
protected void StoreAsset(AssetBase asset) protected void StoreAsset(AssetBase asset)
{ {
m_assetProvider.CreateAsset(asset); m_assetProvider.StoreAsset(asset);
} }
} }
} }

View File

@ -206,11 +206,11 @@ namespace OpenSim.Grid.GridServer.Modules
{ {
if (existingSim == null) if (existingSim == null)
{ {
insertResponse = plugin.AddProfile(sim); insertResponse = plugin.StoreProfile(sim);
} }
else else
{ {
insertResponse = plugin.UpdateProfile(sim); insertResponse = plugin.StoreProfile(sim);
} }
} }
catch (Exception e) catch (Exception e)
@ -259,7 +259,7 @@ namespace OpenSim.Grid.GridServer.Modules
if ((reserveData != null && reserveData.gridRecvKey == theSim.regionRecvKey) || if ((reserveData != null && reserveData.gridRecvKey == theSim.regionRecvKey) ||
(reserveData == null && authkeynode.InnerText != theSim.regionRecvKey)) (reserveData == null && authkeynode.InnerText != theSim.regionRecvKey))
{ {
plugin.AddProfile(theSim); plugin.StoreProfile(theSim);
m_log.Info("[grid]: New sim added to grid (" + theSim.regionName + ")"); m_log.Info("[grid]: New sim added to grid (" + theSim.regionName + ")");
logToDB(theSim.ToString(), "RestSetSimMethod", String.Empty, 5, logToDB(theSim.ToString(), "RestSetSimMethod", String.Empty, 5,
"Region successfully updated and connected to grid."); "Region successfully updated and connected to grid.");

View File

@ -31,6 +31,7 @@ using System.IO;
using System.Reflection; using System.Reflection;
using System.Timers; using System.Timers;
using log4net; using log4net;
using Nini.Config;
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Framework.Console; using OpenSim.Framework.Console;
using OpenSim.Framework.Servers; using OpenSim.Framework.Servers;
@ -46,6 +47,9 @@ namespace OpenSim.Grid.GridServer
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected GridConfig m_config; protected GridConfig m_config;
public string m_consoleType = "local";
public IConfigSource m_configSource = null;
public string m_configFile = "GridServer_Config.xml";
public GridConfig Config public GridConfig Config
{ {
@ -71,16 +75,36 @@ namespace OpenSim.Grid.GridServer
public GridServerBase() public GridServerBase()
{ {
m_console = new LocalConsole("Grid");
MainConsole.Instance = m_console;
} }
protected override void StartupSpecific() protected override void StartupSpecific()
{ {
m_config = new GridConfig("GRID SERVER", (Path.Combine(Util.configDir(), "GridServer_Config.xml"))); switch (m_consoleType)
{
case "rest":
m_console = new RemoteConsole("Grid");
break;
case "basic":
m_console = new CommandConsole("Grid");
break;
default:
m_console = new LocalConsole("Grid");
break;
}
MainConsole.Instance = m_console;
m_config = new GridConfig("GRID SERVER", (Path.Combine(Util.configDir(), m_configFile)));
m_log.Info("[GRID]: Starting HTTP process"); m_log.Info("[GRID]: Starting HTTP process");
m_httpServer = new BaseHttpServer(m_config.HttpPort); m_httpServer = new BaseHttpServer(m_config.HttpPort);
if (m_console is RemoteConsole)
{
RemoteConsole c = (RemoteConsole)m_console;
c.SetServer(m_httpServer);
IConfig netConfig = m_configSource.AddConfig("Network");
netConfig.Set("ConsoleUser", m_config.ConsoleUser);
netConfig.Set("ConsolePass", m_config.ConsolePass);
c.ReadConfig(m_configSource);
}
LoadPlugins(); LoadPlugins();

View File

@ -26,6 +26,7 @@
*/ */
using log4net.Config; using log4net.Config;
using Nini.Config;
namespace OpenSim.Grid.GridServer namespace OpenSim.Grid.GridServer
{ {
@ -33,10 +34,23 @@ namespace OpenSim.Grid.GridServer
{ {
public static void Main(string[] args) public static void Main(string[] args)
{ {
ArgvConfigSource argvSource = new ArgvConfigSource(args);
argvSource.AddSwitch("Startup", "console", "c");
argvSource.AddSwitch("Startup", "xmlfile", "x");
XmlConfigurator.Configure(); XmlConfigurator.Configure();
GridServerBase app = new GridServerBase(); GridServerBase app = new GridServerBase();
IConfig startupConfig = argvSource.Configs["Startup"];
if (startupConfig != null)
{
app.m_consoleType = startupConfig.GetString("console", "local");
app.m_configFile = startupConfig.GetString("xmlfile", "GridServer_Config.xml");
}
app.m_configSource = argvSource;
// if (args.Length > 0 && args[0] == "-setuponly") // if (args.Length > 0 && args[0] == "-setuponly")
// { // {
// app.Config(); // app.Config();

View File

@ -28,7 +28,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace OpenSim.Framework.Communications.Cache namespace OpenSim.Grid.InventoryServer
{ {
public class AuthedSessionCache public class AuthedSessionCache
{ {

View File

@ -30,8 +30,10 @@ using System.Reflection;
using log4net; using log4net;
using OpenMetaverse; using OpenMetaverse;
using OpenSim.Data; using OpenSim.Data;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
namespace OpenSim.Framework.Communications namespace OpenSim.Grid.InventoryServer
{ {
/// <summary> /// <summary>
/// Abstract base class used by local and grid implementations of an inventory service. /// Abstract base class used by local and grid implementations of an inventory service.

View File

@ -30,6 +30,7 @@ using System.Collections.Generic;
using System.IO; using System.IO;
using System.Reflection; using System.Reflection;
using log4net; using log4net;
using Nini.Config;
using log4net.Config; using log4net.Config;
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Framework.Console; using OpenSim.Framework.Console;
@ -56,8 +57,25 @@ namespace OpenSim.Grid.MessagingServer
// private UUID m_lastCreatedUser = UUID.Random(); // private UUID m_lastCreatedUser = UUID.Random();
protected static string m_consoleType = "local";
protected static IConfigSource m_config = null;
protected static string m_configFile = "MessagingServer_Config.xml";
public static void Main(string[] args) public static void Main(string[] args)
{ {
ArgvConfigSource argvSource = new ArgvConfigSource(args);
argvSource.AddSwitch("Startup", "console", "c");
argvSource.AddSwitch("Startup", "xmlfile", "x");
IConfig startupConfig = argvSource.Configs["Startup"];
if (startupConfig != null)
{
m_consoleType = startupConfig.GetString("console", "local");
m_configFile = startupConfig.GetString("xmlfile", "MessagingServer_Config.xml");
}
m_config = argvSource;
XmlConfigurator.Configure(); XmlConfigurator.Configure();
m_log.Info("[SERVER]: Launching MessagingServer..."); m_log.Info("[SERVER]: Launching MessagingServer...");
@ -70,7 +88,18 @@ namespace OpenSim.Grid.MessagingServer
public OpenMessage_Main() public OpenMessage_Main()
{ {
m_console = new LocalConsole("Messaging"); switch (m_consoleType)
{
case "rest":
m_console = new RemoteConsole("Messaging");
break;
case "basic":
m_console = new CommandConsole("Messaging");
break;
default:
m_console = new LocalConsole("Messaging");
break;
}
MainConsole.Instance = m_console; MainConsole.Instance = m_console;
} }
@ -88,20 +117,33 @@ namespace OpenSim.Grid.MessagingServer
{ {
if (m_userServerModule.registerWithUserServer()) if (m_userServerModule.registerWithUserServer())
{ {
m_log.Info("[SERVER]: Starting HTTP process"); if (m_httpServer == null)
m_httpServer = new BaseHttpServer(Cfg.HttpPort); {
m_log.Info("[SERVER]: Starting HTTP process");
m_httpServer = new BaseHttpServer(Cfg.HttpPort);
m_httpServer.AddXmlRPCHandler("login_to_simulator", msgsvc.UserLoggedOn); if (m_console is RemoteConsole)
m_httpServer.AddXmlRPCHandler("logout_of_simulator", msgsvc.UserLoggedOff); {
m_httpServer.AddXmlRPCHandler("get_presence_info_bulk", msgsvc.GetPresenceInfoBulk); RemoteConsole c = (RemoteConsole)m_console;
m_httpServer.AddXmlRPCHandler("process_region_shutdown", msgsvc.ProcessRegionShutdown); c.SetServer(m_httpServer);
m_httpServer.AddXmlRPCHandler("agent_location", msgsvc.AgentLocation); IConfig netConfig = m_config.AddConfig("Network");
m_httpServer.AddXmlRPCHandler("agent_leaving", msgsvc.AgentLeaving); netConfig.Set("ConsoleUser", Cfg.ConsoleUser);
netConfig.Set("ConsolePass", Cfg.ConsolePass);
c.ReadConfig(m_config);
}
m_httpServer.AddXmlRPCHandler("region_startup", m_regionModule.RegionStartup); m_httpServer.AddXmlRPCHandler("login_to_simulator", msgsvc.UserLoggedOn);
m_httpServer.AddXmlRPCHandler("region_shutdown", m_regionModule.RegionShutdown); m_httpServer.AddXmlRPCHandler("logout_of_simulator", msgsvc.UserLoggedOff);
m_httpServer.AddXmlRPCHandler("get_presence_info_bulk", msgsvc.GetPresenceInfoBulk);
m_httpServer.AddXmlRPCHandler("process_region_shutdown", msgsvc.ProcessRegionShutdown);
m_httpServer.AddXmlRPCHandler("agent_location", msgsvc.AgentLocation);
m_httpServer.AddXmlRPCHandler("agent_leaving", msgsvc.AgentLeaving);
m_httpServer.Start(); m_httpServer.AddXmlRPCHandler("region_startup", m_regionModule.RegionStartup);
m_httpServer.AddXmlRPCHandler("region_shutdown", m_regionModule.RegionShutdown);
m_httpServer.Start();
}
m_log.Info("[SERVER]: Userserver registration was successful"); m_log.Info("[SERVER]: Userserver registration was successful");
} }
else else
@ -114,18 +156,18 @@ namespace OpenSim.Grid.MessagingServer
private void deregisterFromUserServer() private void deregisterFromUserServer()
{ {
m_userServerModule.deregisterWithUserServer(); m_userServerModule.deregisterWithUserServer();
if (m_httpServer != null) // if (m_httpServer != null)
{ // {
// try a completely fresh registration, with fresh handlers, too // try a completely fresh registration, with fresh handlers, too
m_httpServer.Stop(); // m_httpServer.Stop();
m_httpServer = null; // m_httpServer = null;
} // }
m_console.Output("[SERVER]: Deregistered from userserver."); m_console.Output("[SERVER]: Deregistered from userserver.");
} }
protected override void StartupSpecific() protected override void StartupSpecific()
{ {
Cfg = new MessageServerConfig("MESSAGING SERVER", (Path.Combine(Util.configDir(), "MessagingServer_Config.xml"))); Cfg = new MessageServerConfig("MESSAGING SERVER", (Path.Combine(Util.configDir(), m_configFile)));
m_userDataBaseService = new UserDataBaseService(); m_userDataBaseService = new UserDataBaseService();
m_userDataBaseService.AddPlugin(Cfg.DatabaseProvider, Cfg.DatabaseConnect); m_userDataBaseService.AddPlugin(Cfg.DatabaseProvider, Cfg.DatabaseConnect);

View File

@ -43,6 +43,7 @@ using OpenSim.Framework.Statistics;
using OpenSim.Grid.Communications.OGS1; using OpenSim.Grid.Communications.OGS1;
using OpenSim.Grid.Framework; using OpenSim.Grid.Framework;
using OpenSim.Grid.UserServer.Modules; using OpenSim.Grid.UserServer.Modules;
using Nini.Config;
namespace OpenSim.Grid.UserServer namespace OpenSim.Grid.UserServer
{ {
@ -73,8 +74,25 @@ namespace OpenSim.Grid.UserServer
protected AvatarCreationModule m_appearanceModule; protected AvatarCreationModule m_appearanceModule;
protected static string m_consoleType = "local";
protected static IConfigSource m_config = null;
protected static string m_configFile = "UserServer_Config.xml";
public static void Main(string[] args) public static void Main(string[] args)
{ {
ArgvConfigSource argvSource = new ArgvConfigSource(args);
argvSource.AddSwitch("Startup", "console", "c");
argvSource.AddSwitch("Startup", "xmlfile", "x");
IConfig startupConfig = argvSource.Configs["Startup"];
if (startupConfig != null)
{
m_consoleType = startupConfig.GetString("console", "local");
m_configFile = startupConfig.GetString("xmlfile", "UserServer_Config.xml");
}
m_config = argvSource;
XmlConfigurator.Configure(); XmlConfigurator.Configure();
m_log.Info("Launching UserServer..."); m_log.Info("Launching UserServer...");
@ -87,7 +105,18 @@ namespace OpenSim.Grid.UserServer
public OpenUser_Main() public OpenUser_Main()
{ {
m_console = new LocalConsole("User"); switch (m_consoleType)
{
case "rest":
m_console = new RemoteConsole("User");
break;
case "basic":
m_console = new CommandConsole("User");
break;
default:
m_console = new LocalConsole("User");
break;
}
MainConsole.Instance = m_console; MainConsole.Instance = m_console;
} }
@ -125,10 +154,20 @@ namespace OpenSim.Grid.UserServer
protected virtual IInterServiceInventoryServices StartupCoreComponents() protected virtual IInterServiceInventoryServices StartupCoreComponents()
{ {
Cfg = new UserConfig("USER SERVER", (Path.Combine(Util.configDir(), "UserServer_Config.xml"))); Cfg = new UserConfig("USER SERVER", (Path.Combine(Util.configDir(), m_configFile)));
m_httpServer = new BaseHttpServer(Cfg.HttpPort); m_httpServer = new BaseHttpServer(Cfg.HttpPort);
if (m_console is RemoteConsole)
{
RemoteConsole c = (RemoteConsole)m_console;
c.SetServer(m_httpServer);
IConfig netConfig = m_config.AddConfig("Network");
netConfig.Set("ConsoleUser", Cfg.ConsoleUser);
netConfig.Set("ConsolePass", Cfg.ConsolePass);
c.ReadConfig(m_config);
}
RegisterInterface<CommandConsole>(m_console); RegisterInterface<CommandConsole>(m_console);
RegisterInterface<UserConfig>(Cfg); RegisterInterface<UserConfig>(Cfg);

View File

@ -2177,7 +2177,9 @@ namespace OpenSim.Region.ClientStack.LindenUDP
bulkUpdate.AgentData.AgentID = AgentId; bulkUpdate.AgentData.AgentID = AgentId;
bulkUpdate.AgentData.TransactionID = transactionId; bulkUpdate.AgentData.TransactionID = transactionId;
bulkUpdate.FolderData = folderDataBlocks.ToArray(); bulkUpdate.FolderData = folderDataBlocks.ToArray();
List<BulkUpdateInventoryPacket.ItemDataBlock> foo = new List<BulkUpdateInventoryPacket.ItemDataBlock>();
bulkUpdate.ItemData = foo.ToArray();
//m_log.Debug("SendBulkUpdateInventory :" + bulkUpdate); //m_log.Debug("SendBulkUpdateInventory :" + bulkUpdate);
OutPacket(bulkUpdate, ThrottleOutPacketType.Asset); OutPacket(bulkUpdate, ThrottleOutPacketType.Asset);
} }
@ -6633,9 +6635,9 @@ namespace OpenSim.Region.ClientStack.LindenUDP
} }
else // Agent else // Agent
{ {
//InventoryItemBase assetRequestItem = userInfo.RootFolder.FindItem(itemID);
IInventoryService invService = m_scene.RequestModuleInterface<IInventoryService>(); IInventoryService invService = m_scene.RequestModuleInterface<IInventoryService>();
InventoryItemBase assetRequestItem = invService.GetItem(new InventoryItemBase(itemID)); InventoryItemBase assetRequestItem = new InventoryItemBase(itemID, AgentId);
assetRequestItem = invService.GetItem(assetRequestItem);
if (assetRequestItem == null) if (assetRequestItem == null)
{ {
assetRequestItem = ((Scene)m_scene).CommsManager.UserProfileCacheService.LibraryRoot.FindItem(itemID); assetRequestItem = ((Scene)m_scene).CommsManager.UserProfileCacheService.LibraryRoot.FindItem(itemID);
@ -7027,14 +7029,21 @@ namespace OpenSim.Region.ClientStack.LindenUDP
if (OnMoveInventoryItem != null) if (OnMoveInventoryItem != null)
{ {
handlerMoveInventoryItem = null; handlerMoveInventoryItem = null;
InventoryItemBase itm = null;
List<InventoryItemBase> items = new List<InventoryItemBase>();
foreach (MoveInventoryItemPacket.InventoryDataBlock datablock in moveitem.InventoryData) foreach (MoveInventoryItemPacket.InventoryDataBlock datablock in moveitem.InventoryData)
{ {
handlerMoveInventoryItem = OnMoveInventoryItem; itm = new InventoryItemBase(datablock.ItemID, AgentId);
if (handlerMoveInventoryItem != null) itm.Folder = datablock.FolderID;
{ itm.Name = Util.FieldToString(datablock.NewName);
handlerMoveInventoryItem(this, datablock.FolderID, datablock.ItemID, datablock.Length, // weird, comes out as empty string
Util.FieldToString(datablock.NewName)); //m_log.DebugFormat("[XXX] new name: {0}", itm.Name);
} items.Add(itm);
}
handlerMoveInventoryItem = OnMoveInventoryItem;
if (handlerMoveInventoryItem != null)
{
handlerMoveInventoryItem(this, items);
} }
} }
break; break;
@ -7053,14 +7062,17 @@ namespace OpenSim.Region.ClientStack.LindenUDP
if (OnRemoveInventoryItem != null) if (OnRemoveInventoryItem != null)
{ {
handlerRemoveInventoryItem = null; handlerRemoveInventoryItem = null;
List<UUID> uuids = new List<UUID>();
foreach (RemoveInventoryItemPacket.InventoryDataBlock datablock in removeItem.InventoryData) foreach (RemoveInventoryItemPacket.InventoryDataBlock datablock in removeItem.InventoryData)
{ {
handlerRemoveInventoryItem = OnRemoveInventoryItem; uuids.Add(datablock.ItemID);
if (handlerRemoveInventoryItem != null)
{
handlerRemoveInventoryItem(this, datablock.ItemID);
}
} }
handlerRemoveInventoryItem = OnRemoveInventoryItem;
if (handlerRemoveInventoryItem != null)
{
handlerRemoveInventoryItem(this, uuids);
}
} }
break; break;
case PacketType.RemoveInventoryFolder: case PacketType.RemoveInventoryFolder:
@ -7078,14 +7090,15 @@ namespace OpenSim.Region.ClientStack.LindenUDP
if (OnRemoveInventoryFolder != null) if (OnRemoveInventoryFolder != null)
{ {
handlerRemoveInventoryFolder = null; handlerRemoveInventoryFolder = null;
List<UUID> uuids = new List<UUID>();
foreach (RemoveInventoryFolderPacket.FolderDataBlock datablock in removeFolder.FolderData) foreach (RemoveInventoryFolderPacket.FolderDataBlock datablock in removeFolder.FolderData)
{ {
handlerRemoveInventoryFolder = OnRemoveInventoryFolder; uuids.Add(datablock.FolderID);
}
if (handlerRemoveInventoryFolder != null) handlerRemoveInventoryFolder = OnRemoveInventoryFolder;
{ if (handlerRemoveInventoryFolder != null)
handlerRemoveInventoryFolder(this, datablock.FolderID); {
} handlerRemoveInventoryFolder(this, uuids);
} }
} }
break; break;
@ -7102,27 +7115,30 @@ namespace OpenSim.Region.ClientStack.LindenUDP
if (OnRemoveInventoryFolder != null) if (OnRemoveInventoryFolder != null)
{ {
handlerRemoveInventoryFolder = null; handlerRemoveInventoryFolder = null;
List<UUID> uuids = new List<UUID>();
foreach (RemoveInventoryObjectsPacket.FolderDataBlock datablock in removeObject.FolderData) foreach (RemoveInventoryObjectsPacket.FolderDataBlock datablock in removeObject.FolderData)
{ {
handlerRemoveInventoryFolder = OnRemoveInventoryFolder; uuids.Add(datablock.FolderID);
}
if (handlerRemoveInventoryFolder != null) handlerRemoveInventoryFolder = OnRemoveInventoryFolder;
{ if (handlerRemoveInventoryFolder != null)
handlerRemoveInventoryFolder(this, datablock.FolderID); {
} handlerRemoveInventoryFolder(this, uuids);
} }
} }
if (OnRemoveInventoryItem != null) if (OnRemoveInventoryItem != null)
{ {
handlerRemoveInventoryItem = null; handlerRemoveInventoryItem = null;
List<UUID> uuids = new List<UUID>();
foreach (RemoveInventoryObjectsPacket.ItemDataBlock datablock in removeObject.ItemData) foreach (RemoveInventoryObjectsPacket.ItemDataBlock datablock in removeObject.ItemData)
{ {
handlerRemoveInventoryItem = OnRemoveInventoryItem; uuids.Add(datablock.ItemID);
if (handlerRemoveInventoryItem != null) }
{ handlerRemoveInventoryItem = OnRemoveInventoryItem;
handlerRemoveInventoryItem(this, datablock.ItemID); if (handlerRemoveInventoryItem != null)
} {
handlerRemoveInventoryItem(this, uuids);
} }
} }
break; break;

View File

@ -128,28 +128,36 @@ namespace OpenSim.Region.ClientStack.LindenUDP
// Store the throttle multiplier for posterity. // Store the throttle multiplier for posterity.
throttleMultiplier = userSettings.ClientThrottleMultipler; throttleMultiplier = userSettings.ClientThrottleMultipler;
int throttleMaxBPS = 1500000;
if (userSettings.TotalThrottleSettings != null)
throttleMaxBPS = userSettings.TotalThrottleSettings.Max;
// Set up the throttle classes (min, max, current) in bits per second // Set up the throttle classes (min, max, current) in bits per second
ResendThrottle = new LLPacketThrottle(5000, 100000, 16000, userSettings.ClientThrottleMultipler); ResendThrottle = new LLPacketThrottle(5000, throttleMaxBPS / 15, 16000, userSettings.ClientThrottleMultipler);
LandThrottle = new LLPacketThrottle(1000, 100000, 2000, userSettings.ClientThrottleMultipler); LandThrottle = new LLPacketThrottle(1000, throttleMaxBPS / 15, 2000, userSettings.ClientThrottleMultipler);
WindThrottle = new LLPacketThrottle(0, 100000, 0, userSettings.ClientThrottleMultipler); WindThrottle = new LLPacketThrottle(0, throttleMaxBPS / 15, 0, userSettings.ClientThrottleMultipler);
CloudThrottle = new LLPacketThrottle(0, 100000, 0, userSettings.ClientThrottleMultipler); CloudThrottle = new LLPacketThrottle(0, throttleMaxBPS / 15, 0, userSettings.ClientThrottleMultipler);
TaskThrottle = new LLPacketThrottle(1000, 800000, 3000, userSettings.ClientThrottleMultipler); TaskThrottle = new LLPacketThrottle(1000, throttleMaxBPS / 2, 3000, userSettings.ClientThrottleMultipler);
AssetThrottle = new LLPacketThrottle(1000, 800000, 1000, userSettings.ClientThrottleMultipler); AssetThrottle = new LLPacketThrottle(1000, throttleMaxBPS / 2, 1000, userSettings.ClientThrottleMultipler);
TextureThrottle = new LLPacketThrottle(1000, 800000, 4000, userSettings.ClientThrottleMultipler); TextureThrottle = new LLPacketThrottle(1000, throttleMaxBPS / 2, 4000, userSettings.ClientThrottleMultipler);
// Total Throttle trumps all - it is the number of bits in total that are allowed to go out per second.
// Total Throttle trumps all - it is the number of bits in total that are allowed to go out per second.
ThrottleSettings totalThrottleSettings = userSettings.TotalThrottleSettings; ThrottleSettings totalThrottleSettings = userSettings.TotalThrottleSettings;
if (null == totalThrottleSettings) if (null == totalThrottleSettings)
{ {
totalThrottleSettings = new ThrottleSettings(0, 1500000, 28000); totalThrottleSettings = new ThrottleSettings(0, throttleMaxBPS, 28000);
} }
TotalThrottle TotalThrottle
= new LLPacketThrottle( = new LLPacketThrottle(
totalThrottleSettings.Min, totalThrottleSettings.Max, totalThrottleSettings.Current, totalThrottleSettings.Min, totalThrottleSettings.Max, totalThrottleSettings.Current,
userSettings.ClientThrottleMultipler); userSettings.ClientThrottleMultipler);
throttleTimer = new Timer((int) (throttletimems/throttleTimeDivisor)); throttleTimer = new Timer((int)(throttletimems / throttleTimeDivisor));
throttleTimer.Elapsed += ThrottleTimerElapsed; throttleTimer.Elapsed += ThrottleTimerElapsed;
throttleTimer.Start(); throttleTimer.Start();

View File

@ -152,11 +152,18 @@ namespace OpenSim.Region.ClientStack.LindenUDP
ClientStackUserSettings userSettings = new ClientStackUserSettings(); ClientStackUserSettings userSettings = new ClientStackUserSettings();
IConfig config = configSource.Configs["ClientStack.LindenUDP"]; IConfig config = configSource.Configs["ClientStack.LindenUDP"];
if (config != null) if (config != null)
{ {
if (config.Contains("client_throttle_max_bps"))
{
int maxBPS = config.GetInt("client_throttle_max_bps", 1500000);
userSettings.TotalThrottleSettings = new ThrottleSettings(0, maxBPS,
maxBPS > 28000 ? maxBPS : 28000);
}
if (config.Contains("client_throttle_multiplier")) if (config.Contains("client_throttle_multiplier"))
userSettings.ClientThrottleMultipler = config.GetFloat("client_throttle_multiplier"); userSettings.ClientThrottleMultipler = config.GetFloat("client_throttle_multiplier");
if (config.Contains("client_socket_rcvbuf_size")) if (config.Contains("client_socket_rcvbuf_size"))
m_clientSocketReceiveBuffer = config.GetInt("client_socket_rcvbuf_size"); m_clientSocketReceiveBuffer = config.GetInt("client_socket_rcvbuf_size");
} }

View File

@ -130,7 +130,8 @@ namespace OpenSim.Region.CoreModules.Avatar.AvatarFactory
} }
else else
{ {
InventoryItemBase baseItem = invService.GetItem(new InventoryItemBase(appearance.Wearables[i].ItemID)); InventoryItemBase baseItem = new InventoryItemBase(appearance.Wearables[i].ItemID, userID);
baseItem = invService.GetItem(baseItem);
if (baseItem != null) if (baseItem != null)
{ {

View File

@ -65,7 +65,8 @@ namespace OpenSim.Region.CoreModules.Avatar.Gestures
{ {
IInventoryService invService = m_scene.InventoryService; IInventoryService invService = m_scene.InventoryService;
InventoryItemBase item = invService.GetItem(new InventoryItemBase(gestureId)); InventoryItemBase item = new InventoryItemBase(gestureId, client.AgentId);
item = invService.GetItem(item);
if (item != null) if (item != null)
{ {
item.Flags = 1; item.Flags = 1;
@ -80,7 +81,8 @@ namespace OpenSim.Region.CoreModules.Avatar.Gestures
{ {
IInventoryService invService = m_scene.InventoryService; IInventoryService invService = m_scene.InventoryService;
InventoryItemBase item = invService.GetItem(new InventoryItemBase(gestureId)); InventoryItemBase item = new InventoryItemBase(gestureId, client.AgentId);
item = invService.GetItem(item);
if (item != null) if (item != null)
{ {
item.Flags = 0; item.Flags = 0;

View File

@ -56,7 +56,10 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
if (cnf != null && cnf.GetString( if (cnf != null && cnf.GetString(
"MessageTransferModule", "MessageTransferModule") != "MessageTransferModule", "MessageTransferModule") !=
"MessageTransferModule") "MessageTransferModule")
{
m_log.Debug("[MESSAGE TRANSFER]: Disabled by configuration");
return; return;
}
cnf = config.Configs["Startup"]; cnf = config.Configs["Startup"];
if (cnf != null) if (cnf != null)
@ -72,6 +75,7 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
"grid_instant_message", processXMLRPCGridInstantMessage); "grid_instant_message", processXMLRPCGridInstantMessage);
} }
m_log.Debug("[MESSAGE TRANSFER]: Message transfer module active");
scene.RegisterModuleInterface<IMessageTransferModule>(this); scene.RegisterModuleInterface<IMessageTransferModule>(this);
m_Scenes.Add(scene); m_Scenes.Add(scene);
} }

View File

@ -67,13 +67,6 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Transfer
if (!m_Scenelist.Contains(scene)) if (!m_Scenelist.Contains(scene))
{ {
if (m_Scenelist.Count == 0)
{
m_TransferModule = scene.RequestModuleInterface<IMessageTransferModule>();
if (m_TransferModule == null)
m_log.Error("[INVENTORY TRANSFER] No Message transfer module found, transfers will be local only");
}
m_Scenelist.Add(scene); m_Scenelist.Add(scene);
scene.RegisterModuleInterface<IInventoryTransferModule>(this); scene.RegisterModuleInterface<IInventoryTransferModule>(this);
@ -86,6 +79,12 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Transfer
public void PostInitialise() public void PostInitialise()
{ {
if (m_Scenelist.Count > 0)
{
m_TransferModule = m_Scenelist[0].RequestModuleInterface<IMessageTransferModule>();
if (m_TransferModule == null)
m_log.Error("[INVENTORY TRANSFER] No Message transfer module found, transfers will be local only");
}
} }
public void Close() public void Close()
@ -257,8 +256,9 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Transfer
invService.GetFolderForType(client.AgentId, AssetType.TrashFolder); invService.GetFolderForType(client.AgentId, AssetType.TrashFolder);
UUID inventoryEntityID = new UUID(im.imSessionID); // The inventory item/folder, back from it's trip UUID inventoryEntityID = new UUID(im.imSessionID); // The inventory item/folder, back from it's trip
InventoryItemBase item = invService.GetItem(new InventoryItemBase(inventoryEntityID)); InventoryItemBase item = new InventoryItemBase(inventoryEntityID, client.AgentId);
item = invService.GetItem(item);
InventoryFolderBase folder = null; InventoryFolderBase folder = null;
if (item != null && trashFolder != null) if (item != null && trashFolder != null)
@ -266,12 +266,15 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Transfer
item.Folder = trashFolder.ID; item.Folder = trashFolder.ID;
// Diva comment: can't we just update this item??? // Diva comment: can't we just update this item???
invService.DeleteItem(item); List<UUID> uuids = new List<UUID>();
uuids.Add(item.ID);
invService.DeleteItems(item.Owner, uuids);
scene.AddInventoryItem(client, item); scene.AddInventoryItem(client, item);
} }
else else
{ {
folder = invService.GetFolder(new InventoryFolderBase(inventoryEntityID)); folder = new InventoryFolderBase(inventoryEntityID, client.AgentId);
folder = invService.GetFolder(folder);
if (folder != null & trashFolder != null) if (folder != null & trashFolder != null)
{ {
@ -451,10 +454,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Transfer
else else
{ {
UUID itemID = new UUID(msg.binaryBucket, 1); UUID itemID = new UUID(msg.binaryBucket, 1);
InventoryItemBase item = new InventoryItemBase(); InventoryItemBase item = new InventoryItemBase(itemID, user.ControllingClient.AgentId);
item.ID = itemID;
item.Owner = user.ControllingClient.AgentId;
// Fetch from service // Fetch from service
// //

View File

@ -26,31 +26,15 @@
*/ */
using OpenMetaverse; using OpenMetaverse;
using OpenSim.Framework; using OpenSim.Region.Framework.Scenes;
using OpenSim.Framework.Communications;
using OpenSim.Data;
namespace OpenSim.Grid.AssetInventoryServer.Plugins.OpenSim namespace OpenSim.Region.CoreModules.Avatar.NPC
{ {
public class OpenSimInventoryService : InventoryServiceBase public interface INPCModule
{ {
public InventoryFolderWithChildren GetInventoryFolder(UUID folderID) UUID CreateNPC(string firstname, string lastname, Vector3 position, Scene scene, UUID cloneAppearanceFrom);
{ void Autopilot(UUID agentID, Scene scene, Vector3 pos);
InventoryFolderBase baseFolder = null; void Say(UUID agentID, Scene scene, string text);
InventoryFolderWithChildren folder = null; void DeleteNPC(UUID agentID, Scene scene);
foreach (IInventoryDataPlugin plugin in m_plugins)
{
baseFolder = plugin.getInventoryFolder(folderID);
}
if (null != baseFolder)
{
folder = new InventoryFolderWithChildren(baseFolder);
folder.Children = null; // This call only returns data for the folder itself, no children data
}
return folder;
}
} }
} }

View File

@ -443,7 +443,16 @@ namespace OpenSim.Region.CoreModules.Scripting.VectorRender
endPoint.X = (int) x; endPoint.X = (int) x;
endPoint.Y = (int) y; endPoint.Y = (int) y;
Image image = ImageHttpRequest(nextLine); Image image = ImageHttpRequest(nextLine);
graph.DrawImage(image, (float) startPoint.X, (float) startPoint.Y, x, y); if (image != null)
{
graph.DrawImage(image, (float)startPoint.X, (float)startPoint.Y, x, y);
}
else
{
graph.DrawString("URL couldn't be resolved or is", new Font("Arial",6), myBrush, startPoint);
graph.DrawString("not an image. Please check URL.", new Font("Arial", 6), myBrush, new Point(startPoint.X, 12 + startPoint.Y));
graph.DrawRectangle(drawPen, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y);
}
startPoint.X += endPoint.X; startPoint.X += endPoint.X;
startPoint.Y += endPoint.Y; startPoint.Y += endPoint.Y;
} }
@ -469,13 +478,19 @@ namespace OpenSim.Region.CoreModules.Scripting.VectorRender
startPoint.X += endPoint.X; startPoint.X += endPoint.X;
startPoint.Y += endPoint.Y; startPoint.Y += endPoint.Y;
} }
else if (nextLine.StartsWith("FillPolygon"))
{
PointF[] points = null;
GetParams(partsDelimiter, ref nextLine, 11, ref points);
graph.FillPolygon(myBrush, points);
}
else if (nextLine.StartsWith("Ellipse")) else if (nextLine.StartsWith("Ellipse"))
{ {
float x = 0; float x = 0;
float y = 0; float y = 0;
GetParams(partsDelimiter, ref nextLine, 7, ref x, ref y); GetParams(partsDelimiter, ref nextLine, 7, ref x, ref y);
endPoint.X = (int) x; endPoint.X = (int)x;
endPoint.Y = (int) y; endPoint.Y = (int)y;
graph.DrawEllipse(drawPen, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y); graph.DrawEllipse(drawPen, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y);
startPoint.X += endPoint.X; startPoint.X += endPoint.X;
startPoint.Y += endPoint.Y; startPoint.Y += endPoint.Y;
@ -492,30 +507,31 @@ namespace OpenSim.Region.CoreModules.Scripting.VectorRender
nextLine = nextLine.Remove(0, 8); nextLine = nextLine.Remove(0, 8);
nextLine = nextLine.Trim(); nextLine = nextLine.Trim();
string [] fprops = nextLine.Split(partsDelimiter); string[] fprops = nextLine.Split(partsDelimiter);
foreach (string prop in fprops) { foreach (string prop in fprops)
{
switch (prop) switch (prop)
{ {
case "B": case "B":
if (!(myFont.Bold)) if (!(myFont.Bold))
myFont = new Font(myFont, myFont.Style | FontStyle.Bold); myFont = new Font(myFont, myFont.Style | FontStyle.Bold);
break; break;
case "I": case "I":
if (!(myFont.Italic)) if (!(myFont.Italic))
myFont = new Font(myFont, myFont.Style | FontStyle.Italic); myFont = new Font(myFont, myFont.Style | FontStyle.Italic);
break; break;
case "U": case "U":
if (!(myFont.Underline)) if (!(myFont.Underline))
myFont = new Font(myFont, myFont.Style | FontStyle.Underline); myFont = new Font(myFont, myFont.Style | FontStyle.Underline);
break; break;
case "S": case "S":
if (!(myFont.Strikeout)) if (!(myFont.Strikeout))
myFont = new Font(myFont, myFont.Style | FontStyle.Strikeout); myFont = new Font(myFont, myFont.Style | FontStyle.Strikeout);
break; break;
case "R": case "R":
myFont = new Font(myFont, FontStyle.Regular); myFont = new Font(myFont, FontStyle.Regular);
break; break;
} }
} }
} }
@ -532,6 +548,57 @@ namespace OpenSim.Region.CoreModules.Scripting.VectorRender
float size = Convert.ToSingle(nextLine, CultureInfo.InvariantCulture); float size = Convert.ToSingle(nextLine, CultureInfo.InvariantCulture);
drawPen.Width = size; drawPen.Width = size;
} }
else if (nextLine.StartsWith("PenCap"))
{
bool start = true, end = true;
nextLine = nextLine.Remove(0, 6);
nextLine = nextLine.Trim();
string[] cap = nextLine.Split(partsDelimiter);
if (cap[0].ToLower() == "start")
end = false;
else if (cap[0].ToLower() == "end")
start = false;
else if (cap[0].ToLower() != "both")
return;
string type = cap[1].ToLower();
if (end)
{
switch (type)
{
case "arrow":
drawPen.EndCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor;
break;
case "round":
drawPen.EndCap = System.Drawing.Drawing2D.LineCap.RoundAnchor;
break;
case "diamond":
drawPen.EndCap = System.Drawing.Drawing2D.LineCap.DiamondAnchor;
break;
case "flat":
drawPen.EndCap = System.Drawing.Drawing2D.LineCap.Flat;
break;
}
}
if (start)
{
switch (type)
{
case "arrow":
drawPen.StartCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor;
break;
case "round":
drawPen.StartCap = System.Drawing.Drawing2D.LineCap.RoundAnchor;
break;
case "diamond":
drawPen.StartCap = System.Drawing.Drawing2D.LineCap.DiamondAnchor;
break;
case "flat":
drawPen.StartCap = System.Drawing.Drawing2D.LineCap.Flat;
break;
}
}
}
else if (nextLine.StartsWith("PenColour")) else if (nextLine.StartsWith("PenColour"))
{ {
nextLine = nextLine.Remove(0, 9); nextLine = nextLine.Remove(0, 9);
@ -542,7 +609,7 @@ namespace OpenSim.Region.CoreModules.Scripting.VectorRender
if (Int32.TryParse(nextLine, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out hex)) if (Int32.TryParse(nextLine, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out hex))
{ {
newColour = Color.FromArgb(hex); newColour = Color.FromArgb(hex);
} }
else else
{ {
// this doesn't fail, it just returns black if nothing is found // this doesn't fail, it just returns black if nothing is found
@ -582,18 +649,40 @@ namespace OpenSim.Region.CoreModules.Scripting.VectorRender
} }
} }
private static void GetParams(char[] partsDelimiter, ref string line, int startLength, ref PointF[] points)
{
line = line.Remove(0, startLength);
string[] parts = line.Split(partsDelimiter);
if (parts.Length > 1 && parts.Length % 2 == 0)
{
points = new PointF[parts.Length / 2];
for (int i = 0; i < parts.Length; i = i + 2)
{
string xVal = parts[i].Trim();
string yVal = parts[i+1].Trim();
float x = Convert.ToSingle(xVal, CultureInfo.InvariantCulture);
float y = Convert.ToSingle(yVal, CultureInfo.InvariantCulture);
PointF point = new PointF(x, y);
points[i / 2] = point;
}
}
}
private Bitmap ImageHttpRequest(string url) private Bitmap ImageHttpRequest(string url)
{ {
try
{
WebRequest request = HttpWebRequest.Create(url); WebRequest request = HttpWebRequest.Create(url);
//Ckrinke: Comment out for now as 'str' is unused. Bring it back into play later when it is used. //Ckrinke: Comment out for now as 'str' is unused. Bring it back into play later when it is used.
//Ckrinke Stream str = null; //Ckrinke Stream str = null;
HttpWebResponse response = (HttpWebResponse) (request).GetResponse(); HttpWebResponse response = (HttpWebResponse)(request).GetResponse();
if (response.StatusCode == HttpStatusCode.OK) if (response.StatusCode == HttpStatusCode.OK)
{ {
Bitmap image = new Bitmap(response.GetResponseStream()); Bitmap image = new Bitmap(response.GetResponseStream());
return image; return image;
}
} }
catch { }
return null; return null;
} }
} }

View File

@ -138,6 +138,11 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
/// <returns>true if the folder was successfully moved</returns> /// <returns>true if the folder was successfully moved</returns>
public abstract bool MoveFolder(InventoryFolderBase folder); public abstract bool MoveFolder(InventoryFolderBase folder);
/// <summary>
/// Delete a list of inventory folders (from trash)
/// </summary>
public abstract bool DeleteFolders(UUID ownerID, List<UUID> folderIDs);
/// <summary> /// <summary>
/// Purge an inventory folder of all its items and subfolders. /// Purge an inventory folder of all its items and subfolders.
/// </summary> /// </summary>
@ -181,12 +186,14 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
/// <returns>true if the item was successfully updated</returns> /// <returns>true if the item was successfully updated</returns>
public abstract bool UpdateItem(InventoryItemBase item); public abstract bool UpdateItem(InventoryItemBase item);
public abstract bool MoveItems(UUID ownerID, List<InventoryItemBase> items);
/// <summary> /// <summary>
/// Delete an item from the user's inventory /// Delete an item from the user's inventory
/// </summary> /// </summary>
/// <param name="item"></param> /// <param name="item"></param>
/// <returns>true if the item was successfully deleted</returns> /// <returns>true if the item was successfully deleted</returns>
public abstract bool DeleteItem(InventoryItemBase item); public abstract bool DeleteItems(UUID ownerID, List<UUID> itemIDs);
public abstract InventoryItemBase GetItem(InventoryItemBase item); public abstract InventoryItemBase GetItem(InventoryItemBase item);

View File

@ -290,7 +290,14 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
public override List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID) public override List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID)
{ {
return new List<InventoryItemBase>(); if (IsLocalGridUser(userID))
return m_GridService.GetFolderItems(userID, folderID);
else
{
UUID sessionID = GetSessionID(userID);
string uri = GetUserInventoryURI(userID) + "/" + userID;
return m_HGService.GetFolderItems(uri, folderID, sessionID);
}
} }
public override bool AddFolder(InventoryFolderBase folder) public override bool AddFolder(InventoryFolderBase folder)
@ -323,6 +330,23 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
} }
} }
public override bool DeleteFolders(UUID ownerID, List<UUID> folderIDs)
{
if (folderIDs == null)
return false;
if (folderIDs.Count == 0)
return false;
if (IsLocalGridUser(ownerID))
return m_GridService.DeleteFolders(ownerID, folderIDs);
else
{
UUID sessionID = GetSessionID(ownerID);
string uri = GetUserInventoryURI(ownerID) + "/" + ownerID.ToString();
return m_HGService.DeleteFolders(uri, folderIDs, sessionID);
}
}
public override bool MoveFolder(InventoryFolderBase folder) public override bool MoveFolder(InventoryFolderBase folder)
{ {
if (folder == null) if (folder == null)
@ -386,18 +410,39 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
} }
} }
public override bool DeleteItem(InventoryItemBase item) public override bool MoveItems(UUID ownerID, List<InventoryItemBase> items)
{ {
if (item == null) if (items == null)
return false; return false;
if (items.Count == 0)
return true;
if (IsLocalGridUser(item.Owner)) if (IsLocalGridUser(ownerID))
return m_GridService.DeleteItem(item); return m_GridService.MoveItems(ownerID, items);
else else
{ {
UUID sessionID = GetSessionID(item.Owner); UUID sessionID = GetSessionID(ownerID);
string uri = GetUserInventoryURI(item.Owner) + "/" + item.Owner.ToString(); string uri = GetUserInventoryURI(ownerID) + "/" + ownerID.ToString();
return m_HGService.DeleteItem(uri, item, sessionID); return m_HGService.MoveItems(uri, items, sessionID);
}
}
public override bool DeleteItems(UUID ownerID, List<UUID> itemIDs)
{
m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Delete {0} items for user {1}", itemIDs.Count, ownerID);
if (itemIDs == null)
return false;
if (itemIDs.Count == 0)
return true;
if (IsLocalGridUser(ownerID))
return m_GridService.DeleteItems(ownerID, itemIDs);
else
{
UUID sessionID = GetSessionID(ownerID);
string uri = GetUserInventoryURI(ownerID) + "/" + ownerID.ToString();
return m_HGService.DeleteItems(uri, itemIDs, sessionID);
} }
} }
@ -483,12 +528,11 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
string userInventoryServerURI = HGNetworkServersInfo.ServerURI(uinfo.UserProfile.UserInventoryURI); string userInventoryServerURI = HGNetworkServersInfo.ServerURI(uinfo.UserProfile.UserInventoryURI);
string uri = m_LocalGridInventoryURI.TrimEnd('/'); string uri = m_LocalGridInventoryURI.TrimEnd('/');
m_log.DebugFormat("[HG INVENTORY CONNECTOR]: IsLocalGridUser, comparing {0} to {1}.", userInventoryServerURI, uri);
if ((userInventoryServerURI == uri) || (userInventoryServerURI == "")) if ((userInventoryServerURI == uri) || (userInventoryServerURI == ""))
{ {
return true; return true;
} }
m_log.DebugFormat("[HG INVENTORY CONNECTOR]: user {0} is foreign({1} - {2})", userID, userInventoryServerURI, uri);
return false; return false;
} }

View File

@ -191,7 +191,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
public override Dictionary<AssetType, InventoryFolderBase> GetSystemFolders(UUID userID) public override Dictionary<AssetType, InventoryFolderBase> GetSystemFolders(UUID userID)
{ {
InventoryFolderBase root = GetRootFolder(userID); InventoryFolderBase root = m_InventoryService.GetRootFolder(userID);
if (root != null) if (root != null)
{ {
InventoryCollection content = GetFolderContent(userID, root.ID); InventoryCollection content = GetFolderContent(userID, root.ID);
@ -202,13 +202,13 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
{ {
if ((folder.Type != (short)AssetType.Folder) && (folder.Type != (short)AssetType.Unknown)) if ((folder.Type != (short)AssetType.Folder) && (folder.Type != (short)AssetType.Unknown))
{ {
m_log.InfoFormat("[INVENTORY CONNECTOR]: folder type {0} ", folder.Type); //m_log.InfoFormat("[INVENTORY CONNECTOR]: folder type {0} ", folder.Type);
folders[(AssetType)folder.Type] = folder; folders[(AssetType)folder.Type] = folder;
} }
} }
// Put the root folder there, as type Folder // Put the root folder there, as type Folder
folders[AssetType.Folder] = root; folders[AssetType.Folder] = root;
m_log.InfoFormat("[INVENTORY CONNECTOR]: root folder is type {0} ", root.Type); //m_log.InfoFormat("[INVENTORY CONNECTOR]: root folder is type {0} ", root.Type);
return folders; return folders;
} }
@ -258,6 +258,11 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
return m_InventoryService.MoveFolder(folder); return m_InventoryService.MoveFolder(folder);
} }
public override bool DeleteFolders(UUID ownerID, List<UUID> folderIDs)
{
return m_InventoryService.DeleteFolders(ownerID, folderIDs);
}
/// <summary> /// <summary>
/// Purge an inventory folder of all its items and subfolders. /// Purge an inventory folder of all its items and subfolders.
/// </summary> /// </summary>
@ -289,14 +294,20 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
return m_InventoryService.UpdateItem(item); return m_InventoryService.UpdateItem(item);
} }
public override bool MoveItems(UUID ownerID, List<InventoryItemBase> items)
{
return m_InventoryService.MoveItems(ownerID, items);
}
/// <summary> /// <summary>
/// Delete an item from the user's inventory /// Delete an item from the user's inventory
/// </summary> /// </summary>
/// <param name="item"></param> /// <param name="item"></param>
/// <returns>true if the item was successfully deleted</returns> /// <returns>true if the item was successfully deleted</returns>
public override bool DeleteItem(InventoryItemBase item) public override bool DeleteItems(UUID ownerID, List<UUID> itemIDs)
{ {
return m_InventoryService.DeleteItem(item); return m_InventoryService.DeleteItems(ownerID, itemIDs);
} }
public override InventoryItemBase GetItem(InventoryItemBase item) public override InventoryItemBase GetItem(InventoryItemBase item)

View File

@ -212,7 +212,8 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
public override List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID) public override List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID)
{ {
return new List<InventoryItemBase>(); UUID sessionID = GetSessionID(userID);
return m_RemoteConnector.GetFolderItems(userID.ToString(), folderID, sessionID);
} }
public override bool AddFolder(InventoryFolderBase folder) public override bool AddFolder(InventoryFolderBase folder)
@ -242,6 +243,18 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
return m_RemoteConnector.MoveFolder(folder.Owner.ToString(), folder, sessionID); return m_RemoteConnector.MoveFolder(folder.Owner.ToString(), folder, sessionID);
} }
public override bool DeleteFolders(UUID ownerID, List<UUID> folderIDs)
{
if (folderIDs == null)
return false;
if (folderIDs.Count == 0)
return false;
UUID sessionID = GetSessionID(ownerID);
return m_RemoteConnector.DeleteFolders(ownerID.ToString(), folderIDs, sessionID);
}
public override bool PurgeFolder(InventoryFolderBase folder) public override bool PurgeFolder(InventoryFolderBase folder)
{ {
if (folder == null) if (folder == null)
@ -272,13 +285,25 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
return m_RemoteConnector.UpdateItem(item.Owner.ToString(), item, sessionID); return m_RemoteConnector.UpdateItem(item.Owner.ToString(), item, sessionID);
} }
public override bool DeleteItem(InventoryItemBase item) public override bool MoveItems(UUID ownerID, List<InventoryItemBase> items)
{ {
if (item == null) if (items == null)
return false; return false;
UUID sessionID = GetSessionID(item.Owner); UUID sessionID = GetSessionID(ownerID);
return m_RemoteConnector.DeleteItem(item.Owner.ToString(), item, sessionID); return m_RemoteConnector.MoveItems(ownerID.ToString(), items, sessionID);
}
public override bool DeleteItems(UUID ownerID, List<UUID> itemIDs)
{
if (itemIDs == null)
return false;
if (itemIDs.Count == 0)
return true;
UUID sessionID = GetSessionID(ownerID);
return m_RemoteConnector.DeleteItems(ownerID.ToString(), itemIDs, sessionID);
} }
public override InventoryItemBase GetItem(InventoryItemBase item) public override InventoryItemBase GetItem(InventoryItemBase item)
@ -320,14 +345,14 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
private UUID GetSessionID(UUID userID) private UUID GetSessionID(UUID userID)
{ {
if (m_Scene == null) //if (m_Scene == null)
{ //{
m_log.Debug("[INVENTORY CONNECTOR]: OOPS! scene is null"); // m_log.Debug("[INVENTORY CONNECTOR]: OOPS! scene is null");
} //}
if (m_UserProfileService == null) if (m_UserProfileService == null)
{ {
m_log.Debug("[INVENTORY CONNECTOR]: OOPS! UserProfileCacheService is null"); //m_log.Debug("[INVENTORY CONNECTOR]: OOPS! UserProfileCacheService is null");
return UUID.Zero; return UUID.Zero;
} }

View File

@ -966,7 +966,8 @@ namespace OpenSim.Region.CoreModules.World.Permissions
if (objectID == UUID.Zero) // User inventory if (objectID == UUID.Zero) // User inventory
{ {
IInventoryService invService = m_scene.InventoryService; IInventoryService invService = m_scene.InventoryService;
InventoryItemBase assetRequestItem = invService.GetItem(new InventoryItemBase(notecard)); InventoryItemBase assetRequestItem = new InventoryItemBase(notecard, user);
assetRequestItem = invService.GetItem(assetRequestItem);
if (assetRequestItem == null) // Library item if (assetRequestItem == null) // Library item
{ {
assetRequestItem = scene.CommsManager.UserProfileCacheService.LibraryRoot.FindItem(notecard); assetRequestItem = scene.CommsManager.UserProfileCacheService.LibraryRoot.FindItem(notecard);
@ -1385,7 +1386,8 @@ namespace OpenSim.Region.CoreModules.World.Permissions
if (objectID == UUID.Zero) // User inventory if (objectID == UUID.Zero) // User inventory
{ {
IInventoryService invService = m_scene.InventoryService; IInventoryService invService = m_scene.InventoryService;
InventoryItemBase assetRequestItem = invService.GetItem(new InventoryItemBase(script)); InventoryItemBase assetRequestItem = new InventoryItemBase(script, user);
assetRequestItem = invService.GetItem(assetRequestItem);
if (assetRequestItem == null) // Library item if (assetRequestItem == null) // Library item
{ {
assetRequestItem = m_scene.CommsManager.UserProfileCacheService.LibraryRoot.FindItem(script); assetRequestItem = m_scene.CommsManager.UserProfileCacheService.LibraryRoot.FindItem(script);
@ -1479,7 +1481,8 @@ namespace OpenSim.Region.CoreModules.World.Permissions
if (objectID == UUID.Zero) // User inventory if (objectID == UUID.Zero) // User inventory
{ {
IInventoryService invService = m_scene.InventoryService; IInventoryService invService = m_scene.InventoryService;
InventoryItemBase assetRequestItem = invService.GetItem(new InventoryItemBase(notecard)); InventoryItemBase assetRequestItem = new InventoryItemBase(notecard, user);
assetRequestItem = invService.GetItem(assetRequestItem);
if (assetRequestItem == null) // Library item if (assetRequestItem == null) // Library item
{ {
assetRequestItem = m_scene.CommsManager.UserProfileCacheService.LibraryRoot.FindItem(notecard); assetRequestItem = m_scene.CommsManager.UserProfileCacheService.LibraryRoot.FindItem(notecard);

View File

@ -140,7 +140,8 @@ namespace OpenSim.Region.Framework.Scenes
/// <returns></returns> /// <returns></returns>
public virtual UUID CapsUpdateInventoryItemAsset(IClientAPI remoteClient, UUID itemID, byte[] data) public virtual UUID CapsUpdateInventoryItemAsset(IClientAPI remoteClient, UUID itemID, byte[] data)
{ {
InventoryItemBase item = InventoryService.GetItem(new InventoryItemBase(itemID)); InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId);
item = InventoryService.GetItem(item);
if (item != null) if (item != null)
{ {
@ -178,8 +179,8 @@ namespace OpenSim.Region.Framework.Scenes
else else
{ {
m_log.ErrorFormat( m_log.ErrorFormat(
"[AGENT INVENTORY]: Could not resolve user {0} for caps inventory update", "[AGENT INVENTORY]: Could not find item {0} for caps inventory update",
remoteClient.AgentId); itemID);
} }
return UUID.Zero; return UUID.Zero;
@ -315,7 +316,8 @@ namespace OpenSim.Region.Framework.Scenes
public void UpdateInventoryItemAsset(IClientAPI remoteClient, UUID transactionID, public void UpdateInventoryItemAsset(IClientAPI remoteClient, UUID transactionID,
UUID itemID, InventoryItemBase itemUpd) UUID itemID, InventoryItemBase itemUpd)
{ {
InventoryItemBase item = InventoryService.GetItem(new InventoryItemBase(itemID)); InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId);
item = InventoryService.GetItem(item);
if (item != null) if (item != null)
{ {
@ -408,7 +410,8 @@ namespace OpenSim.Region.Framework.Scenes
{ {
Console.WriteLine("Scene.Inventory.cs: GiveInventoryItem"); Console.WriteLine("Scene.Inventory.cs: GiveInventoryItem");
InventoryItemBase item = InventoryService.GetItem(new InventoryItemBase(itemId)); InventoryItemBase item = new InventoryItemBase(itemId, senderId);
item = InventoryService.GetItem(item);
if ((item != null) && (item.Owner == senderId)) if ((item != null) && (item.Owner == senderId))
{ {
@ -474,7 +477,11 @@ namespace OpenSim.Region.Framework.Scenes
if (!Permissions.BypassPermissions()) if (!Permissions.BypassPermissions())
{ {
if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0) if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
InventoryService.DeleteItem(new InventoryItemBase(itemId)); {
List<UUID> items = new List<UUID>();
items.Add(itemId);
InventoryService.DeleteItems(senderId, items);
}
} }
return itemCopy; return itemCopy;
@ -558,7 +565,8 @@ namespace OpenSim.Region.Framework.Scenes
if (item == null) if (item == null)
{ {
item = InventoryService.GetItem(new InventoryItemBase(oldItemID)); item = new InventoryItemBase(oldItemID, remoteClient.AgentId);
item = InventoryService.GetItem(item);
if (item == null) if (item == null)
{ {
@ -630,33 +638,13 @@ namespace OpenSim.Region.Framework.Scenes
/// <param name="itemID"></param> /// <param name="itemID"></param>
/// <param name="length"></param> /// <param name="length"></param>
/// <param name="newName"></param> /// <param name="newName"></param>
public void MoveInventoryItem(IClientAPI remoteClient, UUID folderID, UUID itemID, int length, public void MoveInventoryItem(IClientAPI remoteClient, List<InventoryItemBase> items)
string newName)
{ {
m_log.DebugFormat( m_log.DebugFormat(
"[AGENT INVENTORY]: Moving item {0} to {1} for {2}", itemID, folderID, remoteClient.AgentId); "[AGENT INVENTORY]: Moving {0} items for user {1}", items.Count, remoteClient.AgentId);
InventoryItemBase item = InventoryService.GetItem(new InventoryItemBase(itemID)); if (!InventoryService.MoveItems(remoteClient.AgentId, items))
m_log.Warn("[AGENT INVENTORY]: Failed to move items for user " + remoteClient.AgentId);
if (item != null)
{
if (newName != String.Empty)
{
item.Name = newName;
}
item.Folder = folderID;
// Diva comment: can't we just update?
InventoryService.DeleteItem(item);
AddInventoryItem(remoteClient, item);
}
else
{
m_log.Warn("[AGENT INVENTORY]: Failed to find item " + itemID.ToString());
return;
}
} }
/// <summary> /// <summary>
@ -794,29 +782,22 @@ namespace OpenSim.Region.Framework.Scenes
/// </summary> /// </summary>
/// <param name="remoteClient"></param> /// <param name="remoteClient"></param>
/// <param name="itemID"></param> /// <param name="itemID"></param>
private void RemoveInventoryItem(IClientAPI remoteClient, UUID itemID) private void RemoveInventoryItem(IClientAPI remoteClient, List<UUID> itemIDs)
{ {
InventoryService.DeleteItem(new InventoryItemBase(itemID)); //m_log.Debug("[SCENE INVENTORY]: user " + remoteClient.AgentId);
InventoryService.DeleteItems(remoteClient.AgentId, itemIDs);
} }
/// <summary> /// <summary>
/// Removes an inventory folder. Although there is a packet in the Linden protocol for this, it may be /// Removes an inventory folder. This packet is sent when the user
/// legacy and not currently used (purge folder is used to remove folders from trash instead). /// right-clicks a folder that's already in trash and chooses "purge"
/// </summary> /// </summary>
/// <param name="remoteClient"></param> /// <param name="remoteClient"></param>
/// <param name="folderID"></param> /// <param name="folderID"></param>
private void RemoveInventoryFolder(IClientAPI remoteClient, UUID folderID) private void RemoveInventoryFolder(IClientAPI remoteClient, List<UUID> folderIDs)
{ {
// Unclear is this handler is ever called by the Linden client, but it might m_log.DebugFormat("[SCENE INVENTORY]: RemoveInventoryFolders count {0}", folderIDs.Count);
InventoryService.DeleteFolders(remoteClient.AgentId, folderIDs);
InventoryFolderBase folder = new InventoryFolderBase(folderID);
folder.Owner = remoteClient.AgentId;
InventoryFolderBase trash = InventoryService.GetFolderForType(remoteClient.AgentId, AssetType.TrashFolder);
if (trash != null)
{
folder.ParentID = trash.ID;
InventoryService.MoveFolder(folder);
}
} }
private SceneObjectGroup GetGroupByPrim(uint localID) private SceneObjectGroup GetGroupByPrim(uint localID)
@ -1224,7 +1205,8 @@ namespace OpenSim.Region.Framework.Scenes
UUID copyID = UUID.Random(); UUID copyID = UUID.Random();
if (itemID != UUID.Zero) if (itemID != UUID.Zero)
{ {
InventoryItemBase item = InventoryService.GetItem(new InventoryItemBase(itemID)); InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId);
item = InventoryService.GetItem(item);
// Try library // Try library
if (null == item) if (null == item)
@ -1242,7 +1224,11 @@ namespace OpenSim.Region.Framework.Scenes
if (!Permissions.BypassPermissions()) if (!Permissions.BypassPermissions())
{ {
if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0) if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
RemoveInventoryItem(remoteClient, itemID); {
List<UUID> uuids = new List<UUID>();
uuids.Add(itemID);
RemoveInventoryItem(remoteClient, uuids);
}
} }
} }
else else
@ -1287,7 +1273,8 @@ namespace OpenSim.Region.Framework.Scenes
if (itemID != UUID.Zero) // transferred from an avatar inventory to the prim's inventory if (itemID != UUID.Zero) // transferred from an avatar inventory to the prim's inventory
{ {
InventoryItemBase item = InventoryService.GetItem(new InventoryItemBase(itemID)); InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId);
item = InventoryService.GetItem(item);
// Try library // Try library
// XXX clumsy, possibly should be one call // XXX clumsy, possibly should be one call
@ -1672,7 +1659,7 @@ namespace OpenSim.Region.Framework.Scenes
if (DeRezAction.SaveToExistingUserInventoryItem == action) if (DeRezAction.SaveToExistingUserInventoryItem == action)
{ {
item = new InventoryItemBase(objectGroup.RootPart.FromUserInventoryItemID); item = new InventoryItemBase(objectGroup.RootPart.FromUserInventoryItemID, userID);
item = InventoryService.GetItem(item); item = InventoryService.GetItem(item);
//item = userInfo.RootFolder.FindItem( //item = userInfo.RootFolder.FindItem(
@ -1834,7 +1821,8 @@ namespace OpenSim.Region.Framework.Scenes
string sceneObjectXml = SceneObjectSerializer.ToOriginalXmlFormat(objectGroup); string sceneObjectXml = SceneObjectSerializer.ToOriginalXmlFormat(objectGroup);
InventoryItemBase item = InventoryService.GetItem(new InventoryItemBase(itemID)); InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId);
item = InventoryService.GetItem(item);
if (item != null) if (item != null)
{ {
@ -1984,7 +1972,8 @@ namespace OpenSim.Region.Framework.Scenes
BypassRayCast, bRayEndIsIntersection,true,scale, false); BypassRayCast, bRayEndIsIntersection,true,scale, false);
// Rez object // Rez object
InventoryItemBase item = InventoryService.GetItem(new InventoryItemBase(itemID)); InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId);
item = InventoryService.GetItem(item);
if (item != null) if (item != null)
{ {
@ -2135,7 +2124,11 @@ namespace OpenSim.Region.Framework.Scenes
// copy ones will be lost, so avoid it // copy ones will be lost, so avoid it
// //
if (!attachment) if (!attachment)
InventoryService.DeleteItem(item); {
List<UUID> uuids = new List<UUID>();
uuids.Add(item.ID);
InventoryService.DeleteItems(item.Owner, uuids);
}
} }
} }
@ -2309,7 +2302,8 @@ namespace OpenSim.Region.Framework.Scenes
ScenePresence presence; ScenePresence presence;
if (TryGetAvatar(remoteClient.AgentId, out presence)) if (TryGetAvatar(remoteClient.AgentId, out presence))
{ {
InventoryItemBase item = InventoryService.GetItem(new InventoryItemBase(itemID, remoteClient.AgentId)); InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId);
item = InventoryService.GetItem(item);
presence.Appearance.SetAttachment((int)AttachmentPt, itemID, item.AssetID /*att.UUID*/); presence.Appearance.SetAttachment((int)AttachmentPt, itemID, item.AssetID /*att.UUID*/);
IAvatarFactory ava = RequestModuleInterface<IAvatarFactory>(); IAvatarFactory ava = RequestModuleInterface<IAvatarFactory>();
@ -2360,7 +2354,8 @@ namespace OpenSim.Region.Framework.Scenes
if (TryGetAvatar(remoteClient.AgentId, out presence)) if (TryGetAvatar(remoteClient.AgentId, out presence))
{ {
// XXYY!! // XXYY!!
InventoryItemBase item = InventoryService.GetItem(new InventoryItemBase(itemID)); InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId);
item = InventoryService.GetItem(item);
presence.Appearance.SetAttachment((int)AttachmentPt, itemID, item.AssetID /*att.UUID*/); presence.Appearance.SetAttachment((int)AttachmentPt, itemID, item.AssetID /*att.UUID*/);
IAvatarFactory ava = RequestModuleInterface<IAvatarFactory>(); IAvatarFactory ava = RequestModuleInterface<IAvatarFactory>();
if (ava != null) if (ava != null)
@ -2393,7 +2388,9 @@ namespace OpenSim.Region.Framework.Scenes
} }
part.ParentGroup.DetachToGround(); part.ParentGroup.DetachToGround();
InventoryService.DeleteItem(new InventoryItemBase(inventoryID)); List<UUID> uuids = new List<UUID>();
uuids.Add(inventoryID);
InventoryService.DeleteItems(remoteClient.AgentId, uuids);
remoteClient.SendRemoveInventoryItem(inventoryID); remoteClient.SendRemoveInventoryItem(inventoryID);
} }
SendAttachEvent(part.ParentGroup.LocalId, itemID, UUID.Zero); SendAttachEvent(part.ParentGroup.LocalId, itemID, UUID.Zero);

View File

@ -25,6 +25,7 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading; using System.Threading;
using OpenMetaverse; using OpenMetaverse;
@ -404,7 +405,8 @@ namespace OpenSim.Region.Framework.Scenes
return; return;
} }
InventoryItemBase item = InventoryService.GetItem(new InventoryItemBase(itemID)); InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId);
item = InventoryService.GetItem(item);
if (item != null) if (item != null)
{ {
@ -439,9 +441,24 @@ namespace OpenSim.Region.Framework.Scenes
return; return;
} }
// We're going to send the reply async, because there may be
// an enormous quantity of packets -- basically the entire inventory!
// We don't want to block the client thread while all that is happening.
SendInventoryDelegate d = SendInventoryAsync;
d.BeginInvoke(remoteClient, folderID, ownerID, fetchFolders, fetchItems, sortOrder, SendInventoryComplete, d);
}
delegate void SendInventoryDelegate(IClientAPI remoteClient, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder);
void SendInventoryAsync(IClientAPI remoteClient, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder)
{
SendInventoryUpdate(remoteClient, new InventoryFolderBase(folderID), fetchFolders, fetchItems); SendInventoryUpdate(remoteClient, new InventoryFolderBase(folderID), fetchFolders, fetchItems);
} }
void SendInventoryComplete(IAsyncResult iar)
{
}
/// <summary> /// <summary>
/// Handle the caps inventory descendents fetch. /// Handle the caps inventory descendents fetch.
/// ///
@ -517,27 +534,25 @@ namespace OpenSim.Region.Framework.Scenes
// m_log.DebugFormat( // m_log.DebugFormat(
// "[AGENT INVENTORY]: Updating inventory folder {0} {1} for {2} {3}", folderID, name, remoteClient.Name, remoteClient.AgentId); // "[AGENT INVENTORY]: Updating inventory folder {0} {1} for {2} {3}", folderID, name, remoteClient.Name, remoteClient.AgentId);
CachedUserInfo userProfile = CommsManager.UserProfileCacheService.GetUserDetails(remoteClient.AgentId); InventoryFolderBase folder = new InventoryFolderBase(folderID, remoteClient.AgentId);
folder = InventoryService.GetFolder(folder);
if (null == userProfile) if (folder != null)
{ {
m_log.ErrorFormat( folder.Name = name;
"[AGENT INVENTORY]: Could not find user profile for {0} {1}", folder.Type = (short)type;
remoteClient.Name, remoteClient.AgentId); folder.ParentID = parentID;
return; if (!InventoryService.UpdateFolder(folder))
} {
m_log.ErrorFormat(
if (!userProfile.UpdateFolder(name, folderID, type, parentID)) "[AGENT INVENTORY]: Failed to update folder for user {0} {1}",
{ remoteClient.Name, remoteClient.AgentId);
m_log.ErrorFormat( }
"[AGENT INVENTORY]: Failed to update folder for user {0} {1}",
remoteClient.Name, remoteClient.AgentId);
} }
} }
public void HandleMoveInventoryFolder(IClientAPI remoteClient, UUID folderID, UUID parentID) public void HandleMoveInventoryFolder(IClientAPI remoteClient, UUID folderID, UUID parentID)
{ {
InventoryFolderBase folder = new InventoryFolderBase(folderID); InventoryFolderBase folder = new InventoryFolderBase(folderID, remoteClient.AgentId);
folder = InventoryService.GetFolder(folder); folder = InventoryService.GetFolder(folder);
if (folder != null) if (folder != null)
{ {
@ -559,15 +574,34 @@ namespace OpenSim.Region.Framework.Scenes
/// <param name="remoteClient"></param> /// <param name="remoteClient"></param>
/// <param name="folderID"></param> /// <param name="folderID"></param>
delegate void PurgeFolderDelegate(UUID userID, UUID folder);
public void HandlePurgeInventoryDescendents(IClientAPI remoteClient, UUID folderID) public void HandlePurgeInventoryDescendents(IClientAPI remoteClient, UUID folderID)
{ {
InventoryFolderBase folder = new InventoryFolderBase(folderID); PurgeFolderDelegate d = PurgeFolderAsync;
try
{
d.BeginInvoke(remoteClient.AgentId, folderID, PurgeFolderCompleted, d);
}
catch (Exception e)
{
m_log.WarnFormat("[AGENT INVENTORY]: Exception on purge folder for user {0}: {1}", remoteClient.AgentId, e.Message);
}
}
private void PurgeFolderAsync(UUID userID, UUID folderID)
{
InventoryFolderBase folder = new InventoryFolderBase(folderID, userID);
if (InventoryService.PurgeFolder(folder)) if (InventoryService.PurgeFolder(folder))
m_log.DebugFormat("[AGENT INVENTORY]: folder {0} purged successfully", folderID); m_log.DebugFormat("[AGENT INVENTORY]: folder {0} purged successfully", folderID);
else else
m_log.WarnFormat("[AGENT INVENTORY]: could not purge folder {0}", folderID); m_log.WarnFormat("[AGENT INVENTORY]: could not purge folder {0}", folderID);
} }
private void PurgeFolderCompleted(IAsyncResult iar)
{
}
} }
} }

View File

@ -2044,9 +2044,14 @@ namespace OpenSim.Region.Framework.Scenes
{ {
AgentCircuitData aCircuit = m_authenticateHandler.GetAgentCircuitData(client.CircuitCode); AgentCircuitData aCircuit = m_authenticateHandler.GetAgentCircuitData(client.CircuitCode);
m_log.DebugFormat( m_log.Debug("[Scene] Adding new agent " + client.Name + " to scene " + RegionInfo.RegionName);
"[SCENE]: Adding new {0} agent for {1} in {2}", /*
((aCircuit.child == true) ? "child" : "root"), client.Name, RegionInfo.RegionName); string logMsg = string.Format("[SCENE]: Adding new {0} agent for {1} in {2}",
((aCircuit.child == true) ? "child" : "root"), client.Name,
RegionInfo.RegionName);
m_log.Debug(logMsg);
*/
CommsManager.UserProfileCacheService.AddNewUser(client.AgentId); CommsManager.UserProfileCacheService.AddNewUser(client.AgentId);
@ -2055,7 +2060,7 @@ namespace OpenSim.Region.Framework.Scenes
// HERE!!! Do the initial attachments right here // HERE!!! Do the initial attachments right here
// first agent upon login is a root agent by design. // first agent upon login is a root agent by design.
// All other AddNewClient calls find aCircuit.child to be true // All other AddNewClient calls find aCircuit.child to be true
if (aCircuit.child == false) if (aCircuit == null || aCircuit.child == false)
{ {
sp.IsChildAgent = false; sp.IsChildAgent = false;
sp.RezAttachments(); sp.RezAttachments();

View File

@ -225,7 +225,14 @@ namespace OpenSim.Region.Framework.Scenes.Tests
Assert.That(presence.AbsolutePosition, Is.EqualTo(pos), "Position is not the same one entered"); Assert.That(presence.AbsolutePosition, Is.EqualTo(pos), "Position is not the same one entered");
} }
[Test] // I'm commenting this test because it does not represent
// crossings. The Thread.Sleep's in here are not meaningful mocks,
// and they sometimes fail in panda.
// We need to talk in order to develop a test
// that really tests region crossings. There are 3 async components,
// but things are synchronous among them. So there should be
// 3 threads in here.
//[Test]
public void T021_TestCrossToNewRegion() public void T021_TestCrossToNewRegion()
{ {
TestHelper.InMethod(); TestHelper.InMethod();

View File

@ -213,7 +213,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Chat
m_log.DebugFormat("[IRC-Channel-{0}] AccessPassword : <{1}>", cs.idn, cs.AccessPassword); m_log.DebugFormat("[IRC-Channel-{0}] AccessPassword : <{1}>", cs.idn, cs.AccessPassword);
string[] excludes = config.GetString("exclude_list", "").Trim().Split(new Char[] { ',' }); string[] excludes = config.GetString("exclude_list", "").Trim().Split(new Char[] { ',' });
cs.ExcludeList = new List<string>(excludes.Length); cs.ExcludeList = new List<string>(excludes.Length);
foreach(string name in excludes) foreach (string name in excludes)
{ {
cs.ExcludeList.Add(name.Trim().ToLower()); cs.ExcludeList.Add(name.Trim().ToLower());
} }

View File

@ -25,26 +25,158 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
using System.Collections.Generic;
using System.Threading;
using OpenMetaverse; using OpenMetaverse;
using Nini.Config; using Nini.Config;
using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.CoreModules.Avatar.NPC;
using OpenSim.Framework;
using Timer=System.Timers.Timer;
namespace OpenSim.Region.OptionalModules.World.NPC namespace OpenSim.Region.OptionalModules.World.NPC
{ {
public class NPCModule : IRegionModule public class NPCModule : IRegionModule, INPCModule
{ {
// private const bool m_enabled = false; // private const bool m_enabled = false;
private Mutex m_createMutex = new Mutex(false);
private Timer m_timer = new Timer(500);
private Dictionary<UUID,NPCAvatar> m_avatars = new Dictionary<UUID, NPCAvatar>();
private Dictionary<UUID,AvatarAppearance> m_appearanceCache = new Dictionary<UUID, AvatarAppearance>();
// Timer vars.
private bool p_inUse = false;
private readonly object p_lock = new object();
// Private Temporary Variables.
private string p_firstname;
private string p_lastname;
private Vector3 p_position;
private Scene p_scene;
private UUID p_cloneAppearanceFrom;
private UUID p_returnUuid;
private AvatarAppearance GetAppearance(UUID target, Scene scene)
{
if (m_appearanceCache.ContainsKey(target))
return m_appearanceCache[target];
AvatarAppearance x = scene.CommsManager.AvatarService.GetUserAppearance(target);
m_appearanceCache.Add(target, x);
return x;
}
public UUID CreateNPC(string firstname, string lastname,Vector3 position, Scene scene, UUID cloneAppearanceFrom)
{
// Block.
m_createMutex.WaitOne();
// Copy Temp Variables for Timer to pick up.
lock (p_lock)
{
p_firstname = firstname;
p_lastname = lastname;
p_position = position;
p_scene = scene;
p_cloneAppearanceFrom = cloneAppearanceFrom;
p_inUse = true;
p_returnUuid = UUID.Zero;
}
while (p_returnUuid == UUID.Zero)
{
Thread.Sleep(250);
}
m_createMutex.ReleaseMutex();
return p_returnUuid;
}
public void Autopilot(UUID agentID, Scene scene, Vector3 pos)
{
lock (m_avatars)
{
if (m_avatars.ContainsKey(agentID))
{
ScenePresence sp;
scene.TryGetAvatar(agentID, out sp);
sp.DoAutoPilot(0, pos, m_avatars[agentID]);
}
}
}
public void Say(UUID agentID, Scene scene, string text)
{
lock (m_avatars)
{
if (m_avatars.ContainsKey(agentID))
{
m_avatars[agentID].Say(text);
}
}
}
public void DeleteNPC(UUID agentID, Scene scene)
{
lock (m_avatars)
{
if (m_avatars.ContainsKey(agentID))
{
scene.RemoveClient(agentID);
m_avatars.Remove(agentID);
}
}
}
public void Initialise(Scene scene, IConfigSource source) public void Initialise(Scene scene, IConfigSource source)
{ {
// if (m_enabled) scene.RegisterModuleInterface<INPCModule>(this);
// {
// NPCAvatar testAvatar = new NPCAvatar("Jack", "NPC", new Vector3(128, 128, 40), scene); m_timer.Elapsed += m_timer_Elapsed;
// NPCAvatar testAvatar2 = new NPCAvatar("Jill", "NPC", new Vector3(136, 128, 40), scene); m_timer.Start();
// scene.AddNewClient(testAvatar); }
// scene.AddNewClient(testAvatar2);
// } void m_timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
lock (p_lock)
{
if (p_inUse)
{
p_inUse = false;
NPCAvatar npcAvatar = new NPCAvatar(p_firstname, p_lastname, p_position, p_scene);
npcAvatar.CircuitCode = (uint) Util.RandomClass.Next(0, int.MaxValue);
p_scene.ClientManager.Add(npcAvatar.CircuitCode, npcAvatar);
p_scene.AddNewClient(npcAvatar);
ScenePresence sp;
if (p_scene.TryGetAvatar(npcAvatar.AgentId, out sp))
{
AvatarAppearance x = GetAppearance(p_cloneAppearanceFrom, p_scene);
List<byte> wearbyte = new List<byte>();
for (int i = 0; i < x.VisualParams.Length; i++)
{
wearbyte.Add(x.VisualParams[i]);
}
sp.SetAppearance(x.Texture.GetBytes(), wearbyte);
}
m_avatars.Add(npcAvatar.AgentId, npcAvatar);
p_returnUuid = npcAvatar.AgentId;
}
}
} }
public void PostInitialise() public void PostInitialise()

View File

@ -1978,6 +1978,32 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
return new LSL_Rotation(q.X, q.Y, q.Z, q.W); return new LSL_Rotation(q.X, q.Y, q.Z, q.W);
} }
private LSL_Rotation GetPartRot(SceneObjectPart part)
{
Quaternion q;
if (part.LinkNum == 0 || part.LinkNum == 1) // unlinked or root prim
{
if (part.ParentGroup.RootPart.AttachmentPoint != 0)
{
ScenePresence avatar = World.GetScenePresence(part.AttachedAvatar);
if (avatar != null)
{
if ((avatar.AgentControlFlags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_MOUSELOOK) != 0)
q = avatar.CameraRotation; // Mouselook
else
q = avatar.Rotation; // Currently infrequently updated so may be inaccurate
}
else
q = part.ParentGroup.GroupRotation; // Likely never get here but just in case
}
else
q = part.ParentGroup.GroupRotation; // just the group rotation
return new LSL_Rotation(q.X, q.Y, q.Z, q.W);
}
q = part.GetWorldRotation();
return new LSL_Rotation(q.X, q.Y, q.Z, q.W);
}
public LSL_Rotation llGetLocalRot() public LSL_Rotation llGetLocalRot()
{ {
m_host.AddScriptLPS(1); m_host.AddScriptLPS(1);
@ -7299,7 +7325,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
break; break;
case (int)ScriptBaseClass.PRIM_ROTATION: case (int)ScriptBaseClass.PRIM_ROTATION:
res.Add(llGetRot()); res.Add(GetPartRot(part));
break; break;
case (int)ScriptBaseClass.PRIM_TYPE: case (int)ScriptBaseClass.PRIM_TYPE:

View File

@ -31,12 +31,14 @@ using System.Collections.Generic;
using System.Runtime.Remoting.Lifetime; using System.Runtime.Remoting.Lifetime;
using System.Text; using System.Text;
using System.Net; using System.Net;
using System.Threading;
using OpenMetaverse; using OpenMetaverse;
using Nini.Config; using Nini.Config;
using OpenSim; using OpenSim;
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Framework.Communications.Cache; using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Console; using OpenSim.Framework.Console;
using OpenSim.Region.CoreModules.Avatar.NPC;
using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Hypergrid; using OpenSim.Region.Framework.Scenes.Hypergrid;
@ -831,6 +833,25 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
return drawList; return drawList;
} }
public string osDrawFilledPolygon(string drawList, LSL_List x, LSL_List y)
{
CheckThreatLevel(ThreatLevel.None, "osDrawFilledPolygon");
m_host.AddScriptLPS(1);
if (x.Length != y.Length || x.Length < 3)
{
return "";
}
drawList += "FillPolygon " + x.GetLSLStringItem(0) + "," + y.GetLSLStringItem(0);
for (int i = 1; i < x.Length; i++)
{
drawList += "," + x.GetLSLStringItem(i) + "," + y.GetLSLStringItem(i);
}
drawList += "; ";
return drawList;
}
public string osSetFontSize(string drawList, int fontSize) public string osSetFontSize(string drawList, int fontSize)
{ {
CheckThreatLevel(ThreatLevel.None, "osSetFontSize"); CheckThreatLevel(ThreatLevel.None, "osSetFontSize");
@ -858,6 +879,15 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
return drawList; return drawList;
} }
public string osSetPenCap(string drawList, string direction, string type)
{
CheckThreatLevel(ThreatLevel.None, "osSetPenColour");
m_host.AddScriptLPS(1);
drawList += "PenCap " + direction + "," + type + "; ";
return drawList;
}
public string osDrawImage(string drawList, int width, int height, string imageUrl) public string osDrawImage(string drawList, int width, int height, string imageUrl)
{ {
CheckThreatLevel(ThreatLevel.None, "osDrawImage"); CheckThreatLevel(ThreatLevel.None, "osDrawImage");
@ -1762,5 +1792,57 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
return retVal; return retVal;
} }
public LSL_Key osNpcCreate(string firstname, string lastname, LSL_Vector position, LSL_Key cloneFrom)
{
CheckThreatLevel(ThreatLevel.High, "osNpcCreate");
//QueueUserWorkItem
INPCModule module = World.RequestModuleInterface<INPCModule>();
if (module != null)
{
UUID x = module.CreateNPC(firstname,
lastname,
new Vector3((float) position.x, (float) position.y, (float) position.z),
World,
new UUID(cloneFrom));
return new LSL_Key(x.ToString());
}
return new LSL_Key(UUID.Zero.ToString());
}
public void osNpcMoveTo(LSL_Key npc, LSL_Vector position)
{
CheckThreatLevel(ThreatLevel.High, "osNpcMoveTo");
INPCModule module = World.RequestModuleInterface<INPCModule>();
if (module != null)
{
Vector3 pos = new Vector3((float) position.x, (float) position.y, (float) position.z);
module.Autopilot(new UUID(npc.m_string), World, pos);
}
}
public void osNpcSay(LSL_Key npc, string message)
{
CheckThreatLevel(ThreatLevel.High, "osNpcSay");
INPCModule module = World.RequestModuleInterface<INPCModule>();
if (module != null)
{
module.Say(new UUID(npc.m_string), World, message);
}
}
public void osNpcRemove(LSL_Key npc)
{
CheckThreatLevel(ThreatLevel.High, "osNpcRemove");
INPCModule module = World.RequestModuleInterface<INPCModule>();
if (module != null)
{
module.DeleteNPC(new UUID(npc.m_string), World);
}
}
} }
} }

View File

@ -97,9 +97,11 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api.Interfaces
string osDrawEllipse(string drawList, int width, int height); string osDrawEllipse(string drawList, int width, int height);
string osDrawRectangle(string drawList, int width, int height); string osDrawRectangle(string drawList, int width, int height);
string osDrawFilledRectangle(string drawList, int width, int height); string osDrawFilledRectangle(string drawList, int width, int height);
string osDrawFilledPolygon(string drawList, LSL_List x, LSL_List y);
string osSetFontSize(string drawList, int fontSize); string osSetFontSize(string drawList, int fontSize);
string osSetPenSize(string drawList, int penSize); string osSetPenSize(string drawList, int penSize);
string osSetPenColour(string drawList, string colour); string osSetPenColour(string drawList, string colour);
string osSetPenCap(string drawList, string direction, string type);
string osDrawImage(string drawList, int width, int height, string imageUrl); string osDrawImage(string drawList, int width, int height, string imageUrl);
vector osGetDrawStringSize(string contentType, string text, string fontName, int fontSize); vector osGetDrawStringSize(string contentType, string text, string fontName, int fontSize);
void osSetStateEvents(int events); void osSetStateEvents(int events);
@ -149,5 +151,11 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api.Interfaces
LSL_List osGetLinkPrimitiveParams(int linknumber, LSL_List rules); LSL_List osGetLinkPrimitiveParams(int linknumber, LSL_List rules);
key osNpcCreate(string user, string name, vector position, key cloneFrom);
void osNpcMoveTo(key npc, vector position);
void osNpcSay(key npc, string message);
void osNpcRemove(key npc);
} }
} }

View File

@ -267,6 +267,11 @@ namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase
return m_OSSL_Functions.osDrawFilledRectangle(drawList, width, height); return m_OSSL_Functions.osDrawFilledRectangle(drawList, width, height);
} }
public string osDrawFilledPolygon(string drawList, LSL_List x, LSL_List y)
{
return m_OSSL_Functions.osDrawFilledPolygon(drawList, x, y);
}
public string osSetFontSize(string drawList, int fontSize) public string osSetFontSize(string drawList, int fontSize)
{ {
return m_OSSL_Functions.osSetFontSize(drawList, fontSize); return m_OSSL_Functions.osSetFontSize(drawList, fontSize);
@ -277,6 +282,11 @@ namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase
return m_OSSL_Functions.osSetPenSize(drawList, penSize); return m_OSSL_Functions.osSetPenSize(drawList, penSize);
} }
public string osSetPenCap(string drawList, string direction, string type)
{
return m_OSSL_Functions.osSetPenCap(drawList, direction, type);
}
public string osSetPenColour(string drawList, string colour) public string osSetPenColour(string drawList, string colour)
{ {
return m_OSSL_Functions.osSetPenColour(drawList, colour); return m_OSSL_Functions.osSetPenColour(drawList, colour);
@ -393,6 +403,25 @@ namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase
return m_OSSL_Functions.osGetLinkPrimitiveParams(linknumber, rules); return m_OSSL_Functions.osGetLinkPrimitiveParams(linknumber, rules);
} }
public key osNpcCreate(string user, string name, vector position, key cloneFrom)
{
return m_OSSL_Functions.osNpcCreate(user, name, position, cloneFrom);
}
public void osNpcMoveTo(key npc, vector position)
{
m_OSSL_Functions.osNpcMoveTo(npc, position);
}
public void osNpcSay(key npc, string message)
{
m_OSSL_Functions.osNpcSay(npc, message);
}
public void osNpcRemove(key npc)
{
m_OSSL_Functions.osNpcRemove(npc);
}
public OSSLPrim Prim; public OSSLPrim Prim;

View File

@ -439,6 +439,13 @@ namespace OpenSim.Region.ScriptEngine.Shared
set {m_data = value; } set {m_data = value; }
} }
// Function to obtain LSL type from an index. This is needed
// because LSL lists allow for multiple types, and safely
// iterating in them requires a type check.
public Type GetLSLListItemType(int itemIndex)
{
return m_data[itemIndex].GetType();
}
// Member functions to obtain item as specific types. // Member functions to obtain item as specific types.
// For cases where implicit conversions would apply if items // For cases where implicit conversions would apply if items
@ -465,6 +472,10 @@ namespace OpenSim.Region.ScriptEngine.Shared
{ {
return new LSL_Types.LSLFloat((Double)m_data[itemIndex]); return new LSL_Types.LSLFloat((Double)m_data[itemIndex]);
} }
else if (m_data[itemIndex] is LSL_Types.LSLString)
{
return new LSL_Types.LSLFloat(m_data[itemIndex].ToString());
}
else else
{ {
return (LSL_Types.LSLFloat)m_data[itemIndex]; return (LSL_Types.LSLFloat)m_data[itemIndex];
@ -481,20 +492,32 @@ namespace OpenSim.Region.ScriptEngine.Shared
{ {
return new LSL_Types.LSLString((string)m_data[itemIndex]); return new LSL_Types.LSLString((string)m_data[itemIndex]);
} }
else if (m_data[itemIndex] is LSL_Types.LSLFloat)
{
return new LSL_Types.LSLString((LSLFloat)m_data[itemIndex]);
}
else if (m_data[itemIndex] is LSL_Types.LSLInteger)
{
return new LSL_Types.LSLString((LSLInteger)m_data[itemIndex]);
}
else else
{ {
return (LSL_Types.LSLString)m_data[itemIndex]; return (LSL_Types.LSLString)m_data[itemIndex];
} }
} }
public LSL_Types.LSLInteger GetLSLIntegerItem(int itemIndex) public LSL_Types.LSLInteger GetLSLIntegerItem(int itemIndex)
{ {
if (m_data[itemIndex] is LSL_Types.LSLInteger) if (m_data[itemIndex] is LSL_Types.LSLInteger)
return (LSL_Types.LSLInteger)m_data[itemIndex]; return (LSL_Types.LSLInteger)m_data[itemIndex];
else if (m_data[itemIndex] is Int32) if (m_data[itemIndex] is LSL_Types.LSLFloat)
return new LSLInteger((int)m_data[itemIndex]); return new LSLInteger((int)m_data[itemIndex]);
else else if (m_data[itemIndex] is Int32)
throw new InvalidCastException(); return new LSLInteger((int)m_data[itemIndex]);
else if (m_data[itemIndex] is LSL_Types.LSLString)
return new LSLInteger((string)m_data[itemIndex]);
else
throw new InvalidCastException();
} }
public LSL_Types.Vector3 GetVector3Item(int itemIndex) public LSL_Types.Vector3 GetVector3Item(int itemIndex)
@ -1331,6 +1354,12 @@ namespace OpenSim.Region.ScriptEngine.Shared
m_string=s; m_string=s;
} }
public LSLString(LSLInteger i)
{
string s = String.Format("{0}", i);
m_string = s;
}
#endregion #endregion
#region Operators #region Operators

View File

@ -65,6 +65,10 @@ namespace OpenSim.Server.Base
// //
private bool m_Running = true; private bool m_Running = true;
// PID file
//
private string m_pidFile = String.Empty;
// Handle all the automagical stuff // Handle all the automagical stuff
// //
public ServicesServerBase(string prompt, string[] args) public ServicesServerBase(string prompt, string[] args)
@ -211,6 +215,11 @@ namespace OpenSim.Server.Base
} }
} }
if (startupConfig.GetString("PIDFile", String.Empty) != String.Empty)
{
CreatePIDFile(startupConfig.GetString("PIDFile"));
}
// Register the quit command // Register the quit command
// //
MainConsole.Instance.Commands.AddCommand("base", false, "quit", MainConsole.Instance.Commands.AddCommand("base", false, "quit",
@ -230,6 +239,8 @@ namespace OpenSim.Server.Base
MainConsole.Instance.Prompt(); MainConsole.Instance.Prompt();
} }
if (m_pidFile != String.Empty)
File.Delete(m_pidFile);
return 0; return 0;
} }
@ -246,5 +257,22 @@ namespace OpenSim.Server.Base
protected virtual void Initialise() protected virtual void Initialise()
{ {
} }
protected void CreatePIDFile(string path)
{
try
{
string pidstring = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
FileStream fs = File.Create(path);
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
Byte[] buf = enc.GetBytes(pidstring);
fs.Write(buf, 0, buf.Length);
fs.Close();
m_pidFile = path;
}
catch (Exception)
{
}
}
} }
} }

View File

@ -105,8 +105,12 @@ namespace OpenSim.Server.Handlers.Inventory
"POST", "/PurgeFolder/", m_InventoryService.PurgeFolder, CheckAuthSession)); "POST", "/PurgeFolder/", m_InventoryService.PurgeFolder, CheckAuthSession));
m_httpServer.AddStreamHandler( m_httpServer.AddStreamHandler(
new RestDeserialiseSecureHandler<InventoryItemBase, bool>( new RestDeserialiseSecureHandler<List<Guid>, bool>(
"POST", "/DeleteItem/", m_InventoryService.DeleteItem, CheckAuthSession)); "POST", "/DeleteFolders/", DeleteFolders, CheckAuthSession));
m_httpServer.AddStreamHandler(
new RestDeserialiseSecureHandler<List<Guid>, bool>(
"POST", "/DeleteItem/", DeleteItems, CheckAuthSession));
m_httpServer.AddStreamHandler( m_httpServer.AddStreamHandler(
new RestDeserialiseSecureHandler<InventoryItemBase, InventoryItemBase>( new RestDeserialiseSecureHandler<InventoryItemBase, InventoryItemBase>(
@ -125,8 +129,8 @@ namespace OpenSim.Server.Handlers.Inventory
"POST", "/NewFolder/", m_InventoryService.AddFolder, CheckAuthSession)); "POST", "/NewFolder/", m_InventoryService.AddFolder, CheckAuthSession));
m_httpServer.AddStreamHandler( m_httpServer.AddStreamHandler(
new RestDeserialiseTrustedHandler<InventoryFolderBase, bool>( new RestDeserialiseSecureHandler<InventoryFolderBase, bool>(
"POST", "/CreateFolder/", m_InventoryService.AddFolder, CheckTrustSource)); "POST", "/CreateFolder/", m_InventoryService.AddFolder, CheckAuthSession));
m_httpServer.AddStreamHandler( m_httpServer.AddStreamHandler(
new RestDeserialiseSecureHandler<InventoryItemBase, bool>( new RestDeserialiseSecureHandler<InventoryItemBase, bool>(
@ -137,9 +141,16 @@ namespace OpenSim.Server.Handlers.Inventory
"POST", "/AddNewItem/", m_InventoryService.AddItem, CheckTrustSource)); "POST", "/AddNewItem/", m_InventoryService.AddItem, CheckTrustSource));
m_httpServer.AddStreamHandler( m_httpServer.AddStreamHandler(
new RestDeserialiseTrustedHandler<Guid, List<InventoryItemBase>>( new RestDeserialiseSecureHandler<Guid, List<InventoryItemBase>>(
"POST", "/GetItems/", GetFolderItems, CheckTrustSource)); "POST", "/GetItems/", GetFolderItems, CheckAuthSession));
m_httpServer.AddStreamHandler(
new RestDeserialiseSecureHandler<List<InventoryItemBase>, bool>(
"POST", "/MoveItems/", MoveItems, CheckAuthSession));
m_httpServer.AddStreamHandler(new InventoryServerMoveItemsHandler(m_InventoryService));
// for persistent active gestures // for persistent active gestures
m_httpServer.AddStreamHandler( m_httpServer.AddStreamHandler(
new RestDeserialiseTrustedHandler<Guid, List<InventoryItemBase>> new RestDeserialiseTrustedHandler<Guid, List<InventoryItemBase>>
@ -247,6 +258,33 @@ namespace OpenSim.Server.Handlers.Inventory
return m_InventoryService.GetAssetPermissions(item.Owner, item.AssetID); return m_InventoryService.GetAssetPermissions(item.Owner, item.AssetID);
} }
public bool DeleteFolders(List<Guid> items)
{
List<UUID> uuids = new List<UUID>();
foreach (Guid g in items)
uuids.Add(new UUID(g));
// oops we lost the user info here. Bad bad handlers
return m_InventoryService.DeleteFolders(UUID.Zero, uuids);
}
public bool DeleteItems(List<Guid> items)
{
List<UUID> uuids = new List<UUID>();
foreach (Guid g in items)
uuids.Add(new UUID(g));
// oops we lost the user info here. Bad bad handlers
return m_InventoryService.DeleteItems(UUID.Zero, uuids);
}
public bool MoveItems(List<InventoryItemBase> items)
{
// oops we lost the user info here. Bad bad handlers
// let's peek at one item
UUID ownerID = UUID.Zero;
if (items.Count > 0)
ownerID = items[0].Owner;
return m_InventoryService.MoveItems(ownerID, items);
}
#endregion #endregion
/// <summary> /// <summary>

View File

@ -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. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
@ -25,71 +25,57 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
using System; using Nini.Config;
using System.Reflection;
using OpenMetaverse;
using OpenSim.Framework;
using log4net; using log4net;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Serialization;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenMetaverse;
namespace OpenSim.Grid.AssetInventoryServer.Plugins namespace OpenSim.Server.Handlers.Inventory
{ {
public class NullAuthenticationPlugin : IAuthenticationProvider public class InventoryServerMoveItemsHandler : BaseStreamHandler
{ {
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
//private AssetInventoryServer m_server;
public NullAuthenticationPlugin() private IInventoryService m_InventoryService;
public InventoryServerMoveItemsHandler(IInventoryService service) :
base("PUT", "/inventory")
{ {
m_InventoryService = service;
} }
#region IPlugin implementation public override byte[] Handle(string path, Stream request,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
public void Initialise(AssetInventoryServer server)
{ {
//m_server = server; XmlSerializer xs = new XmlSerializer(typeof (List<InventoryItemBase>));
List<InventoryItemBase> items = (List<InventoryItemBase>)xs.Deserialize(request);
m_log.Info("[NULLAUTHENTICATION]: Null Authentication loaded."); bool result = false;
} string[] p = SplitParams(path);
/// <summary> if (p.Length > 0)
/// <para>Initialises asset interface</para> {
/// </summary> UUID ownerID = UUID.Zero;
public void Initialise() UUID.TryParse(p[0], out ownerID);
{ result = m_InventoryService.MoveItems(ownerID, items);
m_log.InfoFormat("[NULLAUTHENTICATION]: {0} cannot be default-initialized!", Name); }
throw new PluginNotInitialisedException(Name); else
} m_log.WarnFormat("[MOVEITEMS HANDLER]: ownerID not provided in request. Unable to serve.");
public void Dispose() xs = new XmlSerializer(typeof(bool));
{ return ServerUtils.SerializeResult(xs, result);
}
public string Version
{
// TODO: this should be something meaningful and not hardcoded?
get { return "0.1"; }
}
public string Name
{
get { return "NullAuthentication"; }
}
#endregion IPlugin implementation
public void AddIdentifier(UUID authToken, Uri identifier)
{
}
public bool RemoveIdentifier(UUID authToken)
{
return true;
}
public bool TryGetIdentifier(UUID authToken, out Uri identifier)
{
identifier = null;
return true;
} }
} }
} }

View File

@ -83,7 +83,7 @@ namespace OpenSim.Services.AssetService
if (!UUID.TryParse(id, out assetID)) if (!UUID.TryParse(id, out assetID))
return null; return null;
return m_Database.FetchAsset(assetID); return m_Database.GetAsset(assetID);
} }
public AssetMetadata GetMetadata(string id) public AssetMetadata GetMetadata(string id)
@ -93,7 +93,7 @@ namespace OpenSim.Services.AssetService
if (!UUID.TryParse(id, out assetID)) if (!UUID.TryParse(id, out assetID))
return null; return null;
AssetBase asset = m_Database.FetchAsset(assetID); AssetBase asset = m_Database.GetAsset(assetID);
return asset.Metadata; return asset.Metadata;
} }
@ -104,7 +104,7 @@ namespace OpenSim.Services.AssetService
if (!UUID.TryParse(id, out assetID)) if (!UUID.TryParse(id, out assetID))
return null; return null;
AssetBase asset = m_Database.FetchAsset(assetID); AssetBase asset = m_Database.GetAsset(assetID);
return asset.Data; return asset.Data;
} }
@ -117,7 +117,7 @@ namespace OpenSim.Services.AssetService
if (!UUID.TryParse(id, out assetID)) if (!UUID.TryParse(id, out assetID))
return false; return false;
AssetBase asset = m_Database.FetchAsset(assetID); AssetBase asset = m_Database.GetAsset(assetID);
//m_log.DebugFormat("[AssetService]: Got asset {0}", asset); //m_log.DebugFormat("[AssetService]: Got asset {0}", asset);
@ -129,7 +129,7 @@ namespace OpenSim.Services.AssetService
public string Store(AssetBase asset) public string Store(AssetBase asset)
{ {
//m_log.DebugFormat("[ASSET SERVICE]: Store asset {0} {1}", asset.Name, asset.ID); //m_log.DebugFormat("[ASSET SERVICE]: Store asset {0} {1}", asset.Name, asset.ID);
m_Database.CreateAsset(asset); m_Database.StoreAsset(asset);
return asset.ID; return asset.ID;
} }

View File

@ -201,6 +201,19 @@ namespace OpenSim.Services.Connectors.Inventory
return false; return false;
} }
public bool DeleteFolders(string id, List<UUID> folders, UUID sessionID)
{
string url = string.Empty;
string userID = string.Empty;
if (StringToUrlAndUserID(id, out url, out userID))
{
ISessionAuthInventoryService connector = GetConnector(url);
return connector.DeleteFolders(userID, folders, sessionID);
}
return false;
}
public bool PurgeFolder(string id, InventoryFolderBase folder, UUID sessionID) public bool PurgeFolder(string id, InventoryFolderBase folder, UUID sessionID)
{ {
string url = string.Empty; string url = string.Empty;
@ -214,6 +227,19 @@ namespace OpenSim.Services.Connectors.Inventory
return false; return false;
} }
public List<InventoryItemBase> GetFolderItems(string id, UUID folderID, UUID sessionID)
{
string url = string.Empty;
string userID = string.Empty;
if (StringToUrlAndUserID(id, out url, out userID))
{
ISessionAuthInventoryService connector = GetConnector(url);
return connector.GetFolderItems(userID, folderID, sessionID);
}
return new List<InventoryItemBase>();
}
public bool AddItem(string id, InventoryItemBase item, UUID sessionID) public bool AddItem(string id, InventoryItemBase item, UUID sessionID)
{ {
string url = string.Empty; string url = string.Empty;
@ -240,7 +266,7 @@ namespace OpenSim.Services.Connectors.Inventory
return false; return false;
} }
public bool DeleteItem(string id, InventoryItemBase item, UUID sessionID) public bool MoveItems(string id, List<InventoryItemBase> items, UUID sessionID)
{ {
string url = string.Empty; string url = string.Empty;
string userID = string.Empty; string userID = string.Empty;
@ -248,7 +274,20 @@ namespace OpenSim.Services.Connectors.Inventory
if (StringToUrlAndUserID(id, out url, out userID)) if (StringToUrlAndUserID(id, out url, out userID))
{ {
ISessionAuthInventoryService connector = GetConnector(url); ISessionAuthInventoryService connector = GetConnector(url);
return connector.UpdateItem(userID, item, sessionID); return connector.MoveItems(userID, items, sessionID);
}
return false;
}
public bool DeleteItems(string id, List<UUID> itemIDs, UUID sessionID)
{
string url = string.Empty;
string userID = string.Empty;
if (StringToUrlAndUserID(id, out url, out userID))
{
ISessionAuthInventoryService connector = GetConnector(url);
return connector.DeleteItems(userID, itemIDs, sessionID);
} }
return false; return false;
} }

View File

@ -88,6 +88,11 @@ namespace OpenSim.Services.Connectors
/// <returns>true if the folder was successfully moved</returns> /// <returns>true if the folder was successfully moved</returns>
bool MoveFolder(string userID, InventoryFolderBase folder, UUID session_id); bool MoveFolder(string userID, InventoryFolderBase folder, UUID session_id);
/// <summary>
/// Delete a list of inventory folders (from trash)
/// </summary>
bool DeleteFolders(string userID, List<UUID> folders, UUID session_id);
/// <summary> /// <summary>
/// Purge an inventory folder of all its items and subfolders. /// Purge an inventory folder of all its items and subfolders.
/// </summary> /// </summary>
@ -95,6 +100,13 @@ namespace OpenSim.Services.Connectors
/// <returns>true if the folder was successfully purged</returns> /// <returns>true if the folder was successfully purged</returns>
bool PurgeFolder(string userID, InventoryFolderBase folder, UUID session_id); bool PurgeFolder(string userID, InventoryFolderBase folder, UUID session_id);
/// <summary>
/// Get items from a folder.
/// </summary>
/// <param name="folder"></param>
/// <returns>true if the folder was successfully purged</returns>
List<InventoryItemBase> GetFolderItems(string userID, UUID folderID, UUID session_id);
/// <summary> /// <summary>
/// Add a new item to the user's inventory /// Add a new item to the user's inventory
/// </summary> /// </summary>
@ -109,12 +121,14 @@ namespace OpenSim.Services.Connectors
/// <returns>true if the item was successfully updated</returns> /// <returns>true if the item was successfully updated</returns>
bool UpdateItem(string userID, InventoryItemBase item, UUID session_id); bool UpdateItem(string userID, InventoryItemBase item, UUID session_id);
bool MoveItems(string userID, List<InventoryItemBase> items, UUID session_id);
/// <summary> /// <summary>
/// Delete an item from the user's inventory /// Delete an item from the user's inventory
/// </summary> /// </summary>
/// <param name="item"></param> /// <param name="item"></param>
/// <returns>true if the item was successfully deleted</returns> /// <returns>true if the item was successfully deleted</returns>
bool DeleteItem(string userID, InventoryItemBase item, UUID session_id); bool DeleteItems(string userID, List<UUID> itemIDs, UUID session_id);
InventoryItemBase QueryItem(string userID, InventoryItemBase item, UUID session_id); InventoryItemBase QueryItem(string userID, InventoryItemBase item, UUID session_id);

View File

@ -178,30 +178,36 @@ namespace OpenSim.Services.Connectors
catch (Exception e) catch (Exception e)
{ {
// Maybe we're talking to an old inventory server. Try this other thing. // Maybe we're talking to an old inventory server. Try this other thing.
m_log.ErrorFormat("[INVENTORY CONNECTOR]: GetSystemFolders operation failed, {0} {1}. Trying RootFolders.", m_log.ErrorFormat("[INVENTORY CONNECTOR]: GetSystemFolders operation failed, {0} {1} (old sever?). Trying GetInventory.",
e.Source, e.Message); e.Source, e.Message);
try try
{ {
folders = SynchronousRestSessionObjectPoster<Guid, List<InventoryFolderBase>>.BeginPostObject( InventoryCollection inventory = SynchronousRestSessionObjectPoster<Guid, InventoryCollection>.BeginPostObject(
"POST", m_ServerURI + "/RootFolders/", new Guid(userID), sessionID.ToString(), userID.ToString()); "POST", m_ServerURI + "/GetInventory/", new Guid(userID), sessionID.ToString(), userID.ToString());
folders = inventory.Folders;
} }
catch (Exception ex) catch (Exception ex)
{ {
m_log.ErrorFormat("[INVENTORY CONNECTOR]: RootFolders operation also failed, {0} {1}. Give up.", m_log.ErrorFormat("[INVENTORY CONNECTOR]: GetInventory operation also failed, {0} {1}. Giving up.",
e.Source, ex.Message); e.Source, ex.Message);
} }
if ((folders != null) && (folders.Count > 0)) if ((folders != null) && (folders.Count > 0))
{ {
dFolders[AssetType.Folder] = folders[0]; // Root folder is the first one m_log.DebugFormat("[INVENTORY CONNECTOR]: Received entire inventory ({0} folders) for user {1}",
folders.RemoveAt(0); folders.Count, userID);
foreach (InventoryFolderBase f in folders) foreach (InventoryFolderBase f in folders)
{ {
if ((f.Type != (short)AssetType.Folder) && (f.Type != (short)AssetType.Unknown)) if ((f.Type != (short)AssetType.Folder) && (f.Type != (short)AssetType.Unknown))
dFolders[(AssetType)f.Type] = f; dFolders[(AssetType)f.Type] = f;
} }
UUID rootFolderID = dFolders[AssetType.Animation].ParentID;
InventoryFolderBase rootFolder = new InventoryFolderBase(rootFolderID, new UUID(userID));
rootFolder = QueryFolder(userID, rootFolder, sessionID);
dFolders[AssetType.Folder] = rootFolder;
m_log.DebugFormat("[INVENTORY CONNECTOR]: {0} system folders for user {1}", dFolders.Count, userID);
return dFolders; return dFolders;
} }
} }
@ -223,51 +229,56 @@ namespace OpenSim.Services.Connectors
return SynchronousRestSessionObjectPoster<Guid, InventoryCollection>.BeginPostObject( return SynchronousRestSessionObjectPoster<Guid, InventoryCollection>.BeginPostObject(
"POST", m_ServerURI + "/GetFolderContent/", folderID.Guid, sessionID.ToString(), userID.ToString()); "POST", m_ServerURI + "/GetFolderContent/", folderID.Guid, sessionID.ToString(), userID.ToString());
} }
catch (TimeoutException e)
{
m_log.ErrorFormat("[INVENTORY CONNECTOR]: GetFolderContent operation to {0} timed out {0} {1}.", m_ServerURI,
e.Source, e.Message);
}
catch (Exception e) catch (Exception e)
{ {
// Maybe we're talking to an old inventory server. Try this other thing. // Maybe we're talking to an old inventory server. Try this other thing.
m_log.ErrorFormat("[INVENTORY CONNECTOR]: GetFolderForType operation failed, {0} {1}. Trying RootFolders and GetItems.", m_log.ErrorFormat("[INVENTORY CONNECTOR]: GetFolderContent operation failed, {0} {1} (old server?). Trying GetInventory.",
e.Source, e.Message); e.Source, e.Message);
InventoryCollection inventory;
List<InventoryFolderBase> folders = null; List<InventoryFolderBase> folders = null;
try try
{ {
folders = SynchronousRestSessionObjectPoster<Guid, List<InventoryFolderBase>>.BeginPostObject( inventory = SynchronousRestSessionObjectPoster<Guid, InventoryCollection>.BeginPostObject(
"POST", m_ServerURI + "/RootFolders/", new Guid(userID), sessionID.ToString(), userID.ToString()); "POST", m_ServerURI + "/GetInventory/", new Guid(userID), sessionID.ToString(), userID.ToString());
if (inventory != null)
folders = inventory.Folders;
} }
catch (Exception ex) catch (Exception ex)
{ {
m_log.ErrorFormat("[INVENTORY CONNECTOR]: RootFolders operation also failed, {0} {1}. Give up.", m_log.ErrorFormat("[INVENTORY CONNECTOR]: GetInventory operation also failed, {0} {1}. Giving up.",
e.Source, ex.Message); e.Source, ex.Message);
return new InventoryCollection();
} }
if ((folders != null) && (folders.Count > 0)) if ((folders != null) && (folders.Count > 0))
{ {
folders = folders.FindAll(delegate (InventoryFolderBase f) { return f.ParentID == folderID ; }); m_log.DebugFormat("[INVENTORY CONNECTOR]: Received entire inventory ({0} folders) for user {1}",
folders.Count, userID);
try folders = folders.FindAll(delegate(InventoryFolderBase f) { return f.ParentID == folderID; });
List<InventoryItemBase> items = inventory.Items;
if (items != null)
{ {
List<InventoryItemBase> items = SynchronousRestSessionObjectPoster<Guid, List<InventoryItemBase>>.BeginPostObject( items = items.FindAll(delegate(InventoryItemBase i) { return i.Folder == folderID; });
"POST", m_ServerURI + "/GetItems/", folderID.Guid, sessionID.ToString(), userID.ToString()); }
if (items != null) inventory.Items = items;
{ inventory.Folders = folders;
InventoryCollection result = new InventoryCollection(); return inventory;
result.Folders = folders;
result.Items = items;
result.UserID = new UUID(userID);
return result;
}
}
catch (Exception ex)
{
m_log.ErrorFormat("[INVENTORY CONNECTOR]: QueryFolder and GetItems operation failed, {0} {1}. Give up.",
e.Source, ex.Message);
}
} }
} }
return null; InventoryCollection nullCollection = new InventoryCollection();
nullCollection.Folders = new List<InventoryFolderBase>();
nullCollection.Items = new List<InventoryItemBase>();
nullCollection.UserID = new UUID(userID);
return nullCollection;
} }
public bool AddFolder(string userID, InventoryFolderBase folder, UUID sessionID) public bool AddFolder(string userID, InventoryFolderBase folder, UUID sessionID)
@ -302,6 +313,25 @@ namespace OpenSim.Services.Connectors
return false; return false;
} }
public bool DeleteFolders(string userID, List<UUID> folderIDs, UUID sessionID)
{
try
{
List<Guid> guids = new List<Guid>();
foreach (UUID u in folderIDs)
guids.Add(u.Guid);
return SynchronousRestSessionObjectPoster<List<Guid>, bool>.BeginPostObject(
"POST", m_ServerURI + "/DeleteFolders/", guids, sessionID.ToString(), userID);
}
catch (Exception e)
{
m_log.ErrorFormat("[INVENTORY CONNECTOR]: Delete inventory folders operation failed, {0} {1}",
e.Source, e.Message);
}
return false;
}
public bool MoveFolder(string userID, InventoryFolderBase folder, UUID sessionID) public bool MoveFolder(string userID, InventoryFolderBase folder, UUID sessionID)
{ {
try try
@ -334,6 +364,23 @@ namespace OpenSim.Services.Connectors
return false; return false;
} }
public List<InventoryItemBase> GetFolderItems(string userID, UUID folderID, UUID sessionID)
{
try
{
InventoryFolderBase folder = new InventoryFolderBase(folderID, new UUID(userID));
return SynchronousRestSessionObjectPoster<InventoryFolderBase, List<InventoryItemBase>>.BeginPostObject(
"POST", m_ServerURI + "/GetItems/", folder, sessionID.ToString(), userID);
}
catch (Exception e)
{
m_log.ErrorFormat("[INVENTORY CONNECTOR]: Get folder items operation failed, {0} {1}",
e.Source, e.Message);
}
return null;
}
public bool AddItem(string userID, InventoryItemBase item, UUID sessionID) public bool AddItem(string userID, InventoryItemBase item, UUID sessionID)
{ {
try try
@ -366,12 +413,72 @@ namespace OpenSim.Services.Connectors
return false; return false;
} }
public bool DeleteItem(string userID, InventoryItemBase item, UUID sessionID) /**
* MoveItems Async group
*/
delegate void MoveItemsDelegate(string userID, List<InventoryItemBase> items, UUID sessionID);
private void MoveItemsAsync(string userID, List<InventoryItemBase> items, UUID sessionID)
{
if (items == null)
{
m_log.WarnFormat("[INVENTORY CONNECTOR]: request to move items got a null list.");
return;
}
try
{
//SynchronousRestSessionObjectPoster<List<InventoryItemBase>, bool>.BeginPostObject(
// "POST", m_ServerURI + "/MoveItems/", items, sessionID.ToString(), userID.ToString());
//// Success
//return;
string uri = m_ServerURI + "/inventory/" + userID;
if (SynchronousRestObjectRequester.
MakeRequest<List<InventoryItemBase>, bool>("PUT", uri, items))
m_log.DebugFormat("[INVENTORY CONNECTOR]: move {0} items poster succeeded {1}", items.Count, uri);
else
m_log.DebugFormat("[INVENTORY CONNECTOR]: move {0} items poster failed {1}", items.Count, uri); ;
return;
}
catch (Exception e)
{
m_log.ErrorFormat("[INVENTORY CONNECTOR]: Move inventory items operation failed, {0} {1} (old server?). Trying slow way.",
e.Source, e.Message);
}
foreach (InventoryItemBase item in items)
{
InventoryItemBase itm = this.QueryItem(userID, item, sessionID);
itm.Name = item.Name;
itm.Folder = item.Folder;
this.UpdateItem(userID, itm, sessionID);
}
}
private void MoveItemsCompleted(IAsyncResult iar)
{
}
public bool MoveItems(string userID, List<InventoryItemBase> items, UUID sessionID)
{
MoveItemsDelegate d = MoveItemsAsync;
d.BeginInvoke(userID, items, sessionID, MoveItemsCompleted, d);
return true;
}
public bool DeleteItems(string userID, List<UUID> items, UUID sessionID)
{ {
try try
{ {
return SynchronousRestSessionObjectPoster<InventoryItemBase, bool>.BeginPostObject( List<Guid> guids = new List<Guid>();
"POST", m_ServerURI + "/DeleteItem/", item, sessionID.ToString(), item.Owner.ToString()); foreach (UUID u in items)
guids.Add(u.Guid);
return SynchronousRestSessionObjectPoster<List<Guid>, bool>.BeginPostObject(
"POST", m_ServerURI + "/DeleteItem/", guids, sessionID.ToString(), userID);
} }
catch (Exception e) catch (Exception e)
{ {
@ -398,12 +505,12 @@ namespace OpenSim.Services.Connectors
return null; return null;
} }
public InventoryFolderBase QueryFolder(string userID, InventoryFolderBase item, UUID sessionID) public InventoryFolderBase QueryFolder(string userID, InventoryFolderBase folder, UUID sessionID)
{ {
try try
{ {
return SynchronousRestSessionObjectPoster<InventoryFolderBase, InventoryFolderBase>.BeginPostObject( return SynchronousRestSessionObjectPoster<InventoryFolderBase, InventoryFolderBase>.BeginPostObject(
"POST", m_ServerURI + "/QueryFolder/", item, sessionID.ToString(), item.Owner.ToString()); "POST", m_ServerURI + "/QueryFolder/", folder, sessionID.ToString(), userID);
} }
catch (Exception e) catch (Exception e)
{ {

View File

@ -136,6 +136,12 @@ namespace OpenSim.Services.Connectors
return false; return false;
} }
public bool DeleteFolders(UUID ownerID, List<UUID> folderIDs)
{
return false;
}
public bool PurgeFolder(InventoryFolderBase folder) public bool PurgeFolder(InventoryFolderBase folder)
{ {
return false; return false;
@ -151,7 +157,12 @@ namespace OpenSim.Services.Connectors
return false; return false;
} }
public bool DeleteItem(InventoryItemBase item) public bool MoveItems(UUID ownerID, List<InventoryItemBase> items)
{
return false;
}
public bool DeleteItems(UUID owner, List<UUID> itemIDs)
{ {
return false; return false;
} }

View File

@ -121,6 +121,14 @@ namespace OpenSim.Services.Interfaces
/// <returns>true if the folder was successfully moved</returns> /// <returns>true if the folder was successfully moved</returns>
bool MoveFolder(InventoryFolderBase folder); bool MoveFolder(InventoryFolderBase folder);
/// <summary>
/// Delete an item from the user's inventory
/// </summary>
/// <param name="item"></param>
/// <returns>true if the item was successfully deleted</returns>
//bool DeleteItem(InventoryItemBase item);
bool DeleteFolders(UUID userID, List<UUID> folderIDs);
/// <summary> /// <summary>
/// Purge an inventory folder of all its items and subfolders. /// Purge an inventory folder of all its items and subfolders.
/// </summary> /// </summary>
@ -142,12 +150,15 @@ namespace OpenSim.Services.Interfaces
/// <returns>true if the item was successfully updated</returns> /// <returns>true if the item was successfully updated</returns>
bool UpdateItem(InventoryItemBase item); bool UpdateItem(InventoryItemBase item);
bool MoveItems(UUID ownerID, List<InventoryItemBase> items);
/// <summary> /// <summary>
/// Delete an item from the user's inventory /// Delete an item from the user's inventory
/// </summary> /// </summary>
/// <param name="item"></param> /// <param name="item"></param>
/// <returns>true if the item was successfully deleted</returns> /// <returns>true if the item was successfully deleted</returns>
bool DeleteItem(InventoryItemBase item); //bool DeleteItem(InventoryItemBase item);
bool DeleteItems(UUID userID, List<UUID> itemIDs);
/// <summary> /// <summary>
/// Get an item, given by its UUID /// Get an item, given by its UUID

View File

@ -235,8 +235,6 @@ namespace OpenSim.Services.InventoryService
public InventoryCollection GetFolderContent(UUID userID, UUID folderID) public InventoryCollection GetFolderContent(UUID userID, UUID folderID)
{ {
m_log.Info("[INVENTORY SERVICE]: Processing request for folder " + folderID);
// Uncomment me to simulate a slow responding inventory server // Uncomment me to simulate a slow responding inventory server
//Thread.Sleep(16000); //Thread.Sleep(16000);
@ -249,7 +247,7 @@ namespace OpenSim.Services.InventoryService
invCollection.Folders = folders; invCollection.Folders = folders;
invCollection.Items = items; invCollection.Items = items;
m_log.DebugFormat("[INVENTORY SERVICE]: Found {0} items and {1} folders", items.Count, folders.Count); m_log.DebugFormat("[INVENTORY SERVICE]: Found {0} items and {1} folders in folder {2}", items.Count, folders.Count, folderID);
return invCollection; return invCollection;
} }
@ -386,13 +384,33 @@ namespace OpenSim.Services.InventoryService
return true; return true;
} }
// See IInventoryServices public virtual bool MoveItems(UUID ownerID, List<InventoryItemBase> items)
public virtual bool DeleteItem(InventoryItemBase item)
{ {
m_log.InfoFormat( m_log.InfoFormat(
"[INVENTORY SERVICE]: Deleting item {0} {1} from folder {2}", item.Name, item.ID, item.Folder); "[INVENTORY SERVICE]: Moving {0} items from user {1}", items.Count, ownerID);
m_Database.deleteInventoryItem(item.ID); InventoryItemBase itm = null;
foreach (InventoryItemBase item in items)
{
itm = GetInventoryItem(item.ID);
itm.Folder = item.Folder;
if ((item.Name != null) && !item.Name.Equals(string.Empty))
itm.Name = item.Name;
m_Database.updateInventoryItem(itm);
}
return true;
}
// See IInventoryServices
public virtual bool DeleteItems(UUID owner, List<UUID> itemIDs)
{
m_log.InfoFormat(
"[INVENTORY SERVICE]: Deleting {0} items from user {1}", itemIDs.Count, owner);
// uhh.....
foreach (UUID uuid in itemIDs)
m_Database.deleteInventoryItem(uuid);
// FIXME: Should return false on failure // FIXME: Should return false on failure
return true; return true;
@ -400,22 +418,34 @@ namespace OpenSim.Services.InventoryService
public virtual InventoryItemBase GetItem(InventoryItemBase item) public virtual InventoryItemBase GetItem(InventoryItemBase item)
{ {
InventoryItemBase result = m_Database.queryInventoryItem(item.ID); InventoryItemBase result = m_Database.getInventoryItem(item.ID);
if (result != null) if (result != null)
return result; return result;
m_log.DebugFormat("[INVENTORY SERVICE]: GetItem failed to find item {0}", item.ID);
return null; return null;
} }
public virtual InventoryFolderBase GetFolder(InventoryFolderBase item) public virtual InventoryFolderBase GetFolder(InventoryFolderBase folder)
{ {
InventoryFolderBase result = m_Database.queryInventoryFolder(item.ID); InventoryFolderBase result = m_Database.getInventoryFolder(folder.ID);
if (result != null) if (result != null)
return result; return result;
m_log.DebugFormat("[INVENTORY SERVICE]: GetFolder failed to find folder {0}", folder.ID);
return null; return null;
} }
public virtual bool DeleteFolders(UUID ownerID, List<UUID> folderIDs)
{
foreach (UUID id in folderIDs)
{
InventoryFolderBase folder = new InventoryFolderBase(id, ownerID);
PurgeFolder(folder);
m_Database.deleteInventoryFolder(id);
}
return true;
}
/// <summary> /// <summary>
/// Purge a folder of all items items and subfolders. /// Purge a folder of all items items and subfolders.
/// ///
@ -439,10 +469,12 @@ namespace OpenSim.Services.InventoryService
List<InventoryItemBase> items = GetFolderItems(folder.Owner, folder.ID); List<InventoryItemBase> items = GetFolderItems(folder.Owner, folder.ID);
List<UUID> uuids = new List<UUID>();
foreach (InventoryItemBase item in items) foreach (InventoryItemBase item in items)
{ {
DeleteItem(item); uuids.Add(item.ID);
} }
DeleteItems(folder.Owner, uuids);
// FIXME: Should return false on failure // FIXME: Should return false on failure
return true; return true;

View File

@ -25,6 +25,7 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
using System;
using System.Collections.Generic; using System.Collections.Generic;
using OpenMetaverse; using OpenMetaverse;
using OpenSim.Framework; using OpenSim.Framework;
@ -46,6 +47,18 @@ namespace OpenSim.Tests.Common.Mock
public void Initialise(string connect) {} public void Initialise(string connect) {}
public void Dispose() {} public void Dispose() {}
private readonly List<AssetBase> assets = new List<AssetBase>();
public AssetBase GetAsset(UUID uuid)
{
return assets.Find(x=>x.FullID == uuid);
}
public void StoreAsset(AssetBase asset)
{
assets.Add(asset);
}
public List<AssetMetadata> FetchAssetMetadataSet(int start, int count) { return new List<AssetMetadata>(count); } public List<AssetMetadata> FetchAssetMetadataSet(int start, int count) { return new List<AssetMetadata>(count); }
} }
} }

View File

@ -128,6 +128,11 @@ namespace OpenSim.Tests.Common.Mock
return false; return false;
} }
public bool DeleteFolders(UUID ownerID, List<UUID> ids)
{
return false;
}
public bool PurgeFolder(InventoryFolderBase folder) public bool PurgeFolder(InventoryFolderBase folder)
{ {
return false; return false;
@ -143,7 +148,12 @@ namespace OpenSim.Tests.Common.Mock
return false; return false;
} }
public bool DeleteItem(InventoryItemBase item) public bool MoveItems(UUID ownerID, List<InventoryItemBase> items)
{
return false;
}
public bool DeleteItems(UUID ownerID, List<UUID> itemIDs)
{ {
return false; return false;
} }

Some files were not shown because too many files have changed in this diff Show More