Exemplo n.º 1
0
        /// <summary>
        /// Add a notecard item to the given part.
        /// </summary>
        /// <param name="assetService"></param>
        /// <param name="part"></param>
        /// <param name="itemName"></param>
        /// <param name="itemID"></param>
        /// <param name="assetID"></param>
        /// <param name="text">The tex to put in the notecard.</param>
        /// <returns>The item that was added</returns>
        public static TaskInventoryItem AddNotecard(
            IAssetService assetService, SceneObjectPart part, string itemName, UUID itemID, UUID assetID, string text)
        {
            AssetNotecard nc = new AssetNotecard();

            nc.BodyText = text;
            nc.Encode();

            AssetBase ncAsset
                = AssetHelpers.CreateAsset(assetID, AssetType.Notecard, nc.AssetData, UUID.Zero);

            assetService.Store(ncAsset);

            TaskInventoryItem ncItem
                = new TaskInventoryItem
                {
                Name    = itemName,
                AssetID = assetID,
                ItemID  = itemID,
                Type    = (int)AssetType.Notecard,
                InvType = (int)InventoryType.Notecard
                };

            part.Inventory.AddInventoryItem(ncItem, true);

            return(ncItem);
        }
Exemplo n.º 2
0
        //Separate thread
        private void Assets_OnAssetReceived(AssetDownload transfer, Asset asset)
        {
            if (InvokeRequired)
            {
                BeginInvoke(new MethodInvoker(delegate()
                {
                    Assets_OnAssetReceived(transfer, asset);
                }
                                              ));

                return;
            }

            //if (transfer.AssetType != AssetType.Notecard) return;

            if (!transfer.Success)
            {
                notecardContent = "Unable to download notecard.";
                SetNotecardText(notecardContent, false);
                return;
            }

            receivedAsset   = (AssetNotecard)asset;
            notecardContent = Utils.BytesToString(transfer.AssetData);

            SetNotecardText(notecardContent, false);
        }
Exemplo n.º 3
0
        private void CreateTestObjects(Scene scene, out SceneObjectGroup sog1, out SceneObjectGroup sog2, out UUID ncAssetUuid)
        {
            SceneObjectPart part1 = CreateSceneObjectPart1();

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

            AssetNotecard nc = new AssetNotecard();

            nc.BodyText = "Hello World!";
            nc.Encode();
            ncAssetUuid = UUID.Random();
            UUID      ncItemUuid = UUID.Random();
            AssetBase ncAsset
                = AssetHelpers.CreateAsset(ncAssetUuid, AssetType.Notecard, nc.AssetData, UUID.Zero);

            m_scene.AssetService.Store(ncAsset);

            TaskInventoryItem ncItem
                = new TaskInventoryItem {
                Name = "ncItem", AssetID = ncAssetUuid, ItemID = ncItemUuid
                };
            SceneObjectPart part2 = CreateSceneObjectPart2();

            sog2 = new SceneObjectGroup(part2);
            part2.Inventory.AddInventoryItem(ncItem, true);

            scene.AddNewSceneObject(sog2, false);
        }
Exemplo n.º 4
0
        public bool SendNotecard(string name, string content, UUID sendToUUID)
        {
            bool returnstatus = true;

            name = name + " " + DateTime.Now;
            Client.Inventory.RequestCreateItem(
                Client.Inventory.FindFolderForType(AssetType.Notecard),
                name,
                name + " Created via SecondBot notecard API",
                AssetType.Notecard,
                UUID.Random(),
                InventoryType.Notecard,
                PermissionMask.All,
                (bool Success, InventoryItem item) =>
            {
                if (Success)
                {
                    AssetNotecard empty = new AssetNotecard {
                        BodyText = "\n"
                    };
                    empty.Encode();
                    Client.Inventory.RequestUploadNotecardAsset(empty.AssetData, item.UUID,
                                                                (bool emptySuccess, string emptyStatus, UUID emptyItemID, UUID emptyAssetID) =>
                    {
                        if (emptySuccess)
                        {
                            empty.BodyText = content;
                            empty.Encode();
                            Client.Inventory.RequestUploadNotecardAsset(empty.AssetData, emptyItemID,
                                                                        (bool finalSuccess, string finalStatus, UUID finalItemID, UUID finalID) =>
                            {
                                if (finalSuccess)
                                {
                                    Info("Sending notecard now");
                                    Client.Inventory.GiveItem(finalItemID, name, AssetType.Notecard, sendToUUID, false);
                                }
                                else
                                {
                                    returnstatus = false;
                                    Warn("Unable to request notecard upload");
                                }
                            });
                        }
                        else
                        {
                            Crit("The f**k empty success notecard create");
                            returnstatus = false;
                        }
                    });
                }
                else
                {
                    Warn("Unable to find default notecards folder");
                    returnstatus = false;
                }
            }
                );
            return(returnstatus);
        }
        /// <summary>
        /// Create an asset from the given data.
        /// </summary>
        public static AssetBase CreateAsset(UUID assetUuid, AssetType assetType, string text, UUID creatorID)
        {
            AssetNotecard anc = new AssetNotecard();

            anc.BodyText = text;
            anc.Encode();

            return(CreateAsset(assetUuid, assetType, anc.AssetData, creatorID));
        }
Exemplo n.º 6
0
        private void tbtnSave_Click(object sender, EventArgs e)
        {
            bool          success = false;
            string        message = "";
            AssetNotecard n       = new AssetNotecard
            {
                BodyText      = rtbContent.Text,
                EmbeddedItems = new List <InventoryItem>()
            };

            if (receivedNotecard != null)
            {
                for (var i = 0; i < receivedNotecard.EmbeddedItems.Count; i++)
                {
                    n.EmbeddedItems.Add(receivedNotecard.EmbeddedItems[i]);
                    int indexChar = 0xdc00 + i;
                    n.BodyText += (char)0xdbc0;
                    n.BodyText += (char)indexChar;
                }
            }

            n.Encode();

            UpdateStatus("Saving...");

            InventoryManager.InventoryUploadedAssetCallback handler = delegate(bool uploadSuccess, string status, UUID itemID, UUID assetID)
            {
                success = uploadSuccess;
                if (itemID == notecard.UUID)
                {
                    if (success)
                    {
                        UpdateStatus("OK");
                        notecard.AssetUUID = assetID;
                    }
                    else
                    {
                        UpdateStatus("Failed");
                    }
                }
                message = status ?? "Unknown error uploading notecard asset";
            };

            if (prim == null)
            {
                client.Inventory.RequestUploadNotecardAsset(n.AssetData, notecard.UUID, handler);
            }
            else
            {
                client.Inventory.RequestUpdateNotecardTask(n.AssetData, notecard.UUID, prim.ID, handler);
            }
        }
Exemplo n.º 7
0
        internal override void Start()
        {
            base.Start();
            var transferID = UUID.Random();

            Talker.SayMore("Reading " + asset.Name + ". Just a moment.");
            Client.Assets.RequestInventoryAsset(
                asset,
                true,
                transferID,
                (AssetDownload transfer, Asset asset) =>
            {
                if (transfer.Success && transfer.ID == transferID)
                {
                    AssetNotecard n = (AssetNotecard)asset;
                    n.Decode();
                    AssetNotecard recievedNotecard = n;

                    text = string.Empty;

                    for (int i = 0; i < n.BodyText.Length; i++)
                    {
                        char c = n.BodyText[i];

                        // Special marker for embedded things.
                        if ((int)c == 0xdbc0)
                        {
                            int index       = (int)n.BodyText[++i] - 0xdc00;
                            InventoryItem e = n.EmbeddedItems[index];
                            text           += " (embedded) ";
                        }
                        else
                        {
                            text += c;
                        }
                    }

                    // TODO put in controls to stop, back up etc
                    StopPosition = 0;
                    NextSection();
                    control.instance.MainForm.KeyDown +=
                        new System.Windows.Forms.KeyEventHandler(MainForm_KeyPress);
                }
                else
                {
                    Talker.Say("Failed to download the notecard.", Talk.BeepType.Bad);
                }
            }
                );
        }
Exemplo n.º 8
0
        public void TestOsAgentSaveAppearance()
        {
            TestHelpers.InMethod();
            //            log4net.Config.XmlConfigurator.Configure();

            UUID  ownerId    = TestHelpers.ParseTail(0x1);
            UUID  nonOwnerId = TestHelpers.ParseTail(0x2);
            float newHeight  = 1.9f;

            ScenePresence sp = SceneHelpers.AddScenePresence(m_scene, nonOwnerId);

            sp.Appearance.AvatarHeight = newHeight;
            SceneObjectGroup so   = SceneHelpers.CreateSceneObject(1, ownerId, 0x10);
            SceneObjectPart  part = so.RootPart;

            m_scene.AddSceneObject(so);

            OSSL_Api osslApi = new OSSL_Api();

            osslApi.Initialize(m_engine, part, null, null);

            string notecardName = "appearanceNc";

            osslApi.osAgentSaveAppearance(new LSL_Types.LSLString(nonOwnerId.ToString()), notecardName);

            IList <TaskInventoryItem> items = part.Inventory.GetInventoryItems(notecardName);

            Assert.That(items.Count, Is.EqualTo(1));

            TaskInventoryItem ncItem = items[0];

            Assert.That(ncItem.Name, Is.EqualTo(notecardName));

            AssetBase ncAsset = m_scene.AssetService.Get(ncItem.AssetID.ToString());

            Assert.That(ncAsset, Is.Not.Null);

            AssetNotecard anc = new AssetNotecard(UUID.Zero, ncAsset.Data);

            anc.Decode();
            OSDMap           appearanceOsd   = (OSDMap)OSDParser.DeserializeLLSDXml(anc.BodyText);
            AvatarAppearance savedAppearance = new AvatarAppearance();

            savedAppearance.Unpack(appearanceOsd);

            Assert.That(savedAppearance.AvatarHeight, Is.EqualTo(sp.Appearance.AvatarHeight));
        }
Exemplo n.º 9
0
 public void PrintAsset(Asset asset)
 {
     if (asset is AssetScriptText)
     {
         AssetScriptText script = asset as AssetScriptText;
         Console.WriteLine(script.Source);
     }
     else if (asset is AssetNotecard)
     {
         AssetNotecard note = asset as AssetNotecard;
         Console.WriteLine(note.Text);
     }
     else
     {
         Console.WriteLine("Unable to handle asset type {0}", asset.GetType());
     }
 }
Exemplo n.º 10
0
        /// <summary>
        /// Add a notecard item to the given part.
        /// </summary>
        /// <param name="scene"></param>
        /// <param name="part"></param>
        /// <param name="itemName"></param>
        /// <param name="itemID"></param>
        /// <param name="assetID"></param>
        /// <returns>The item that was added</returns>
        public static TaskInventoryItem AddNotecard(Scene scene, SceneObjectPart part, string itemName, UUID itemID, UUID assetID)
        {
            AssetNotecard nc = new AssetNotecard();
            nc.BodyText = "Hello World!";
            nc.Encode();

            AssetBase ncAsset
                = AssetHelpers.CreateAsset(assetID, AssetType.Notecard, nc.AssetData, UUID.Zero);
            scene.AssetService.Store(ncAsset);

            TaskInventoryItem ncItem 
                = new TaskInventoryItem 
                    { Name = itemName, AssetID = assetID, ItemID = itemID,
                      Type = (int)AssetType.Notecard, InvType = (int)InventoryType.Notecard };
            part.Inventory.AddInventoryItem(ncItem, true); 
            
            return ncItem;
        }
Exemplo n.º 11
0
 /// <summary>
 /// Add a notecard item to the given part.
 /// </summary>
 /// <param name="scene"></param>
 /// <param name="part"></param>
 /// <returns>The item that was added</returns>
 public static TaskInventoryItem AddNotecard(Scene scene, SceneObjectPart part)
 {
     AssetNotecard nc = new AssetNotecard();
     nc.BodyText = "Hello World!";
     nc.Encode();
     UUID ncAssetUuid = new UUID("00000000-0000-0000-1000-000000000000");
     UUID ncItemUuid = new UUID("00000000-0000-0000-1100-000000000000");
     AssetBase ncAsset
         = AssetHelpers.CreateAsset(ncAssetUuid, AssetType.Notecard, nc.AssetData, UUID.Zero);
     scene.AssetService.Store(ncAsset);
     TaskInventoryItem ncItem 
         = new TaskInventoryItem 
             { Name = "ncItem", AssetID = ncAssetUuid, ItemID = ncItemUuid, 
               Type = (int)AssetType.Notecard, InvType = (int)InventoryType.Notecard };
     part.Inventory.AddInventoryItem(ncItem, true); 
     
     return ncItem;
 }
Exemplo n.º 12
0
 /// <summary>
 /// </summary>
 /// <param name="assetData"></param>
 override internal void SetAssetData(byte[] assetData)
 {
     if (_Asset == null)
     {
         if (AssetID != null)
         {
             _Asset = new AssetNotecard(AssetID, assetData);
         }
         else
         {
             _Asset   = new AssetNotecard(LLUUID.Random(), assetData);
             _AssetID = _Asset.AssetID;
         }
     }
     else
     {
         _Asset.SetAssetData(assetData);
     }
 }
Exemplo n.º 13
0
 /// <summary>
 /// </summary>
 /// <param name="assetData"></param>
 override internal void SetAssetData(byte[] assetData)
 {
     if (_Asset == null)
     {
         if (AssetID != null)
         {
             _Asset = new AssetNotecard(AssetID, assetData);
         }
         else
         {
             _Asset   = new AssetNotecard(LLUUID.GenerateUUID(), assetData);
             _AssetID = _Asset.AssetID;
         }
     }
     else
     {
         _Asset.AssetData = assetData;
     }
 }
Exemplo n.º 14
0
        void Assets_OnNotecardReceived(AssetDownload transfer, Asset asset)
        {
            if (transfer.Success)
            {
                AssetNotecard n = (AssetNotecard)asset;
                n.Decode();
                AssetNotecard recievedNotecard = n;

                text = string.Empty;

                for (int i = 0; i < n.BodyText.Length; i++)
                {
                    char c = n.BodyText[i];

                    // Special marker for embedded things.
                    if ((int)c == 0xdbc0)
                    {
                        int           index = (int)n.BodyText[++i] - 0xdc00;
                        InventoryItem e     = n.EmbeddedItems[index];
                        text += " (embedded) ";
                    }
                    else
                    {
                        text += c;
                    }
                }

                // TODO put in controls to stop, back up etc
                StopPosition = 0;
                NextSection();
                control.instance.MainForm.KeyDown +=
                    new System.Windows.Forms.KeyEventHandler(MainForm_KeyPress);
            }
            else
            {
                Talker.Say("Failed to download the notecard.", Talk.BeepType.Bad);
            }
        }
        protected TaskInventoryItem CreateSOItem1(Scene scene, SceneObjectPart part)
        {
            AssetNotecard nc = new AssetNotecard();

            nc.BodyText = "Hello World!";
            nc.Encode();
            UUID      ncAssetUuid = new UUID("00000000-0000-0000-1000-000000000000");
            UUID      ncItemUuid  = new UUID("00000000-0000-0000-1100-000000000000");
            AssetBase ncAsset
                = AssetHelpers.CreateAsset(ncAssetUuid, AssetType.Notecard, nc.AssetData, UUID.Zero);

            scene.AssetService.Store(ncAsset);
            TaskInventoryItem ncItem
                = new TaskInventoryItem
                {
                Name = "ncItem", AssetID = ncAssetUuid, ItemID = ncItemUuid,
                Type = (int)AssetType.Notecard, InvType = (int)InventoryType.Notecard
                };

            part.Inventory.AddInventoryItem(ncItem, true);

            return(ncItem);
        }
        private static bool LoadAsset(string assetPath, byte[] data, AssetLoadedCallback assetCallback, long bytesRead, long totalBytes)
        {
            // Right now we're nastily obtaining the UUID from the filename
            string filename = assetPath.Remove(0, ArchiveConstants.ASSETS_PATH.Length);
            int i = filename.LastIndexOf(ArchiveConstants.ASSET_EXTENSION_SEPARATOR);

            if (i == -1)
            {
                Logger.Log(String.Format(
                    "[OarFile]: Could not find extension information in asset path {0} since it's missing the separator {1}.  Skipping",
                    assetPath, ArchiveConstants.ASSET_EXTENSION_SEPARATOR), Helpers.LogLevel.Warning);
                return false;
            }

            string extension = filename.Substring(i);
            UUID uuid;
            UUID.TryParse(filename.Remove(filename.Length - extension.Length), out uuid);

            if (ArchiveConstants.EXTENSION_TO_ASSET_TYPE.ContainsKey(extension))
            {
                AssetType assetType = ArchiveConstants.EXTENSION_TO_ASSET_TYPE[extension];
                Asset asset = null;

                switch (assetType)
                {
                    case AssetType.Animation:
                        asset = new AssetAnimation(uuid, data);
                        break;
                    case AssetType.Bodypart:
                        asset = new AssetBodypart(uuid, data);
                        break;
                    case AssetType.Clothing:
                        asset = new AssetClothing(uuid, data);
                        break;
                    case AssetType.Gesture:
                        asset = new AssetGesture(uuid, data);
                        break;
                    case AssetType.Landmark:
                        asset = new AssetLandmark(uuid, data);
                        break;
                    case AssetType.LSLBytecode:
                        asset = new AssetScriptBinary(uuid, data);
                        break;
                    case AssetType.LSLText:
                        asset = new AssetScriptText(uuid, data);
                        break;
                    case AssetType.Notecard:
                        asset = new AssetNotecard(uuid, data);
                        break;
                    case AssetType.Object:
                        asset = new AssetPrim(uuid, data);
                        break;
                    case AssetType.Sound:
                        asset = new AssetSound(uuid, data);
                        break;
                    case AssetType.Texture:
                        asset = new AssetTexture(uuid, data);
                        break;
                    default:
                        Logger.Log("[OarFile] Unhandled asset type " + assetType, Helpers.LogLevel.Error);
                        break;
                }

                if (asset != null)
                {
                    assetCallback(asset, bytesRead, totalBytes);
                    return true;
                }
            }

            Logger.Log("[OarFile] Failed to load asset", Helpers.LogLevel.Warning);
            return false;
        }
Exemplo n.º 17
0
        void Assets_OnAssetReceived(AssetDownload transfer, Asset asset)
        {
            if (InvokeRequired)
            {
                if (!instance.MonoRuntime || IsHandleCreated)
                    BeginInvoke(new MethodInvoker(() => Assets_OnAssetReceived(transfer, asset)));
                return;
            }

            if (transfer.Success)
            {
                AssetNotecard n = (AssetNotecard)asset;
                n.Decode();
                receivedNotecard = n;

                string noteText = string.Empty;
                rtbContent.Clear();

                for (int i = 0; i < n.BodyText.Length; i++)
                {
                    char c = n.BodyText[i];

                    if ((int)c == 0xdbc0)
                    {
                        int index = (int)n.BodyText[++i] - 0xdc00;
                        InventoryItem e = n.EmbeddedItems[index];
                        rtbContent.AppendText(noteText);
                        rtbContent.InsertLink(e.Name, string.Format("radegast://embeddedasset/{0}", index));
                        noteText = string.Empty;
                    }
                    else
                    {
                        noteText += c;
                    }
                }

                rtbContent.Text += noteText;

                if (n.EmbeddedItems != null && n.EmbeddedItems.Count > 0)
                {
                    tbtnAttachments.Enabled = true;
                    tbtnAttachments.Visible = true;
                    foreach (InventoryItem item in n.EmbeddedItems)
                    {
                        int ix = InventoryConsole.GetItemImageIndex(item.AssetType.ToString().ToLower());
                        ToolStripMenuItem titem = new ToolStripMenuItem(item.Name);

                        if (ix != -1)
                        {
                            titem.Image = frmMain.ResourceImages.Images[ix];
                            titem.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText;
                        }
                        else
                        {
                            titem.DisplayStyle = ToolStripItemDisplayStyle.Text;
                        }

                        titem.Name = item.UUID.ToString(); ;
                        titem.Tag = item;
                        titem.Click += new EventHandler(attachmentMenuItem_Click);

                        var saveToInv = new ToolStripMenuItem("Save to inventory");
                        saveToInv.Click += (object xsender, EventArgs xe) =>
                            {
                                client.Inventory.RequestCopyItemFromNotecard(UUID.Zero,
                                    notecard.UUID,
                                    client.Inventory.FindFolderForType(item.AssetType),
                                    item.UUID,
                                    Inventory_OnInventoryItemCopied);
                            };

                        titem.DropDownItems.Add(saveToInv);
                        tbtnAttachments.DropDownItems.Add(titem);
                    }
                }
                UpdateStatus("OK");
                rtbContent.Focus();
            }
            else
            {
                UpdateStatus("Failed");
                rtbContent.Text = "Failed to download notecard. " + transfer.Status;
            }
        }
Exemplo n.º 18
0
        private void tbtnSave_Click(object sender, EventArgs e)
        {
            bool success = false;
            string message = "";
            AssetNotecard n = new AssetNotecard();
            n.BodyText = rtbContent.Text;
            n.EmbeddedItems = new List<InventoryItem>();

            if (receivedNotecard != null)
            {
                for (int i = 0; i < receivedNotecard.EmbeddedItems.Count; i++)
                {
                    n.EmbeddedItems.Add(receivedNotecard.EmbeddedItems[i]);
                    int indexChar = 0xdc00 + i;
                    n.BodyText += (char)0xdbc0;
                    n.BodyText += (char)indexChar;
                }
            }

            n.Encode();

            UpdateStatus("Saving...");

            InventoryManager.InventoryUploadedAssetCallback handler = delegate(bool uploadSuccess, string status, UUID itemID, UUID assetID)
                    {
                        success = uploadSuccess;
                        if (itemID == notecard.UUID)
                        {
                            if (success)
                            {
                                UpdateStatus("OK");
                                notecard.AssetUUID = assetID;
                            }
                            else
                            {
                                UpdateStatus("Failed");
                            }

                        }
                        message = status ?? "Unknown error uploading notecard asset";
                    };

            if (prim == null)
            {
                client.Inventory.RequestUploadNotecardAsset(n.AssetData, notecard.UUID, handler);
            }
            else
            {
                client.Inventory.RequestUpdateNotecardTask(n.AssetData, notecard.UUID, prim.ID, handler);
            }
        }
Exemplo n.º 19
0
        private byte[] CopyInventoryFromNotecard(Stream request, UUID agentID)
        {
            OSDMap rm = (OSDMap) OSDParser.DeserializeLLSDXml(request);
            UUID FolderID = rm["folder-id"].AsUUID();
            UUID ItemID = rm["item-id"].AsUUID();
            UUID NotecardID = rm["notecard-id"].AsUUID();
            UUID ObjectID = rm["object-id"].AsUUID();
            InventoryItemBase notecardItem = null;
            if (ObjectID != UUID.Zero)
            {
                ISceneChildEntity part = m_scene.GetSceneObjectPart(ObjectID);
                if (part != null)
                {
                    TaskInventoryItem item = part.Inventory.GetInventoryItem(NotecardID);
                    if (m_scene.Permissions.CanCopyObjectInventory(NotecardID, ObjectID, agentID))
                    {
                        notecardItem = new InventoryItemBase(NotecardID, agentID) {AssetID = item.AssetID};
                    }
                }
            }
            else
                notecardItem = m_scene.InventoryService.GetItem(new InventoryItemBase(NotecardID));
            if (notecardItem != null && notecardItem.Owner == agentID)
            {
                AssetBase asset = m_scene.AssetService.Get(notecardItem.AssetID.ToString());
                if (asset != null)
                {
                    UTF8Encoding enc =
                        new UTF8Encoding();
                    List<string> notecardData = SLUtil.ParseNotecardToList(enc.GetString(asset.Data));
                    AssetNotecard noteCardAsset = new AssetNotecard(UUID.Zero, asset.Data);
                    noteCardAsset.Decode();
                    bool found = false;
                    UUID lastOwnerID = UUID.Zero;
#if (!ISWIN)
                    foreach (InventoryItem notecardObjectItem in noteCardAsset.EmbeddedItems)
                    {
                        if (notecardObjectItem.UUID == ItemID)
                        {
                            //Make sure that it exists
                            found = true;
                            lastOwnerID = notecardObjectItem.OwnerID;
                            break;
                        }
                    }
#else
                    foreach (InventoryItem notecardObjectItem in noteCardAsset.EmbeddedItems.Where(notecardObjectItem => notecardObjectItem.UUID == ItemID))
                    {
                        //Make sure that it exists
                        found = true;
                        lastOwnerID = notecardObjectItem.OwnerID;
                        break;
                    }
#endif
                    if (found)
                    {
                        m_scene.InventoryService.GiveInventoryItemAsync(agentID, lastOwnerID, ItemID, FolderID, false,
                            (item) =>
                        {
                            IClientAPI client;
                            m_scene.ClientManager.TryGetValue(agentID, out client);
                            if (item != null)
                                client.SendBulkUpdateInventory(item);
                            else
                                client.SendAlertMessage("Failed to retrieve item");
                        });
                    }
                }
            }

            return new byte[0];
        }
Exemplo n.º 20
0
        private Hashtable CopyInventoryFromNotecard(Hashtable mDhttpMethod, UUID agentID)
        {
            OSDMap            rm           = (OSDMap)OSDParser.DeserializeLLSDXml((string)mDhttpMethod["requestbody"]);
            UUID              FolderID     = rm["folder-id"].AsUUID();
            UUID              ItemID       = rm["item-id"].AsUUID();
            UUID              NotecardID   = rm["notecard-id"].AsUUID();
            UUID              ObjectID     = rm["object-id"].AsUUID();
            InventoryItemBase notecardItem = null;

            if (ObjectID != UUID.Zero)
            {
                ISceneChildEntity part = m_scene.GetSceneObjectPart(ObjectID);
                if (part != null)
                {
                    TaskInventoryItem item = part.Inventory.GetInventoryItem(NotecardID);
                    if (m_scene.Permissions.CanCopyObjectInventory(NotecardID, ObjectID, agentID))
                    {
                        notecardItem = new InventoryItemBase(NotecardID, agentID)
                        {
                            AssetID = item.AssetID
                        };
                    }
                }
            }
            else
            {
                notecardItem = m_scene.InventoryService.GetItem(new InventoryItemBase(NotecardID));
            }
            if (notecardItem != null && notecardItem.Owner == agentID)
            {
                AssetBase asset = m_scene.AssetService.Get(notecardItem.AssetID.ToString());
                if (asset != null)
                {
                    UTF8Encoding enc =
                        new UTF8Encoding();
                    List <string> notecardData  = SLUtil.ParseNotecardToList(enc.GetString(asset.Data));
                    AssetNotecard noteCardAsset = new AssetNotecard(UUID.Zero, asset.Data);
                    noteCardAsset.Decode();
                    bool found       = false;
                    UUID lastOwnerID = UUID.Zero;
#if (!ISWIN)
                    foreach (InventoryItem notecardObjectItem in noteCardAsset.EmbeddedItems)
                    {
                        if (notecardObjectItem.UUID == ItemID)
                        {
                            //Make sure that it exists
                            found       = true;
                            lastOwnerID = notecardObjectItem.OwnerID;
                            break;
                        }
                    }
#else
                    foreach (InventoryItem notecardObjectItem in noteCardAsset.EmbeddedItems.Where(notecardObjectItem => notecardObjectItem.UUID == ItemID))
                    {
                        //Make sure that it exists
                        found       = true;
                        lastOwnerID = notecardObjectItem.OwnerID;
                        break;
                    }
#endif
                    if (found)
                    {
                        InventoryItemBase  item            = null;
                        ILLClientInventory inventoryModule = m_scene.RequestModuleInterface <ILLClientInventory>();
                        if (inventoryModule != null)
                        {
                            item = inventoryModule.GiveInventoryItem(agentID, lastOwnerID, ItemID, FolderID);
                        }

                        IClientAPI client;
                        m_scene.ClientManager.TryGetValue(agentID, out client);
                        if (item != null)
                        {
                            client.SendBulkUpdateInventory(item);
                        }
                        else
                        {
                            client.SendAlertMessage("Failed to retrieve item");
                        }
                    }
                }
            }

            //Send back data
            Hashtable responsedata = new Hashtable();
            responsedata["int_response_code"]   = 200; //501; //410; //404;
            responsedata["content_type"]        = "text/plain";
            responsedata["keepalive"]           = false;
            responsedata["str_response_string"] = "";
            return(responsedata);
        }
Exemplo n.º 21
0
        public static Asset CreateAssetWrapper(AssetType type, UUID uuid, byte[] data)
        {
            Asset asset;

            switch (type)
            {
                case AssetType.Animation:
                    asset = new AssetAnimation(uuid, data);
                    break;
                case AssetType.Gesture:
                    asset = new AssetGesture(uuid, data);
                    break;
                case AssetType.Landmark:
                    asset = new AssetLandmark(uuid, data);
                    break;
                case AssetType.Bodypart:
                    asset = new AssetBodypart(uuid, data);
                    break;
                case AssetType.Clothing:
                    asset = new AssetClothing(uuid, data);
                    break;
                case AssetType.LSLBytecode:
                    asset = new AssetScriptBinary(uuid, data);
                    break;
                case AssetType.LSLText:
                    asset = new AssetScriptText(uuid, data);
                    break;
                case AssetType.Notecard:
                    asset = new AssetNotecard(uuid, data);
                    break;
                case AssetType.Sound:
                    asset = new AssetSound(uuid, data);
                    break;
                case AssetType.Texture:
                    asset = new AssetTexture(uuid, data);
                    break;
#if COGBOT_LIBOMV
                    case AssetType.CallingCard:
                    asset = new AssetCallingCard(uuid, data);
                    break;
#endif
                default:
#if COGBOT_LIBOMV
                    asset = new AssetMutable(type, uuid, data);
                    Logger.Log("[OarFile] Not Implemented asset type " + type, Helpers.LogLevel.Error);
#else
                    throw new NotImplementedException("Unimplemented asset type: " + type);
#endif
                    break;
            }
            return asset;
        }
Exemplo n.º 22
0
        private void TraverseDir(InventoryNode node, string path)
        {
            var nodes = new List <InventoryNode>(node.Nodes.Values);

            foreach (InventoryNode n in nodes)
            {
                traversed++;
                try
                {
                    backupTaskCancelToken.Token.ThrowIfCancellationRequested();
                    if (IsHandleCreated && (traversed % 13 == 0))
                    {
                        BeginInvoke(new MethodInvoker(() =>
                        {
                            lblStatus.Text = string.Format("Traversed {0} nodes...", traversed);
                        }));
                    }

                    if (n.Data is InventoryFolder)
                    {
                        WriteCSVLine("Folder", path, n.Data.Name, "", "", "", "");
                        TraverseDir(n, Path.Combine(path, RadegastInstance.SafeFileName(n.Data.Name)));
                    }
                    else
                    {
                        InventoryItem item      = (InventoryItem)n.Data;
                        string        creator   = item.CreatorID == UUID.Zero ? string.Empty : instance.Names.Get(item.CreatorID, true);
                        string        lastOwner = item.LastOwnerID == UUID.Zero ? string.Empty : instance.Names.Get(item.LastOwnerID, true);
                        string        type      = item.AssetType.ToString();
                        if (item.InventoryType == InventoryType.Wearable)
                        {
                            type = ((WearableType)item.Flags).ToString();
                        }
                        string created = item.CreationDate.ToString("yyyy-MM-dd HH:mm:ss");
                        WriteCSVLine(type, path, item.Name, item.Description, created, creator, lastOwner);

                        PermissionMask fullPerm = PermissionMask.Modify | PermissionMask.Copy | PermissionMask.Transfer;
                        if ((item.Permissions.OwnerMask & fullPerm) != fullPerm)
                        {
                            continue;
                        }

                        string filePartial = Path.Combine(path, RadegastInstance.SafeFileName(n.Data.Name));
                        string fullName    = folderName + filePartial;
                        switch (item.AssetType)
                        {
                        case AssetType.LSLText:
                            client.Settings.USE_ASSET_CACHE = false;
                            fullName += ".lsl";
                            break;

                        case AssetType.Notecard: fullName += ".txt"; break;

                        case AssetType.Texture: fullName += ".png"; break;

                        default: fullName += ".bin"; break;
                        }
                        string dirName = Path.GetDirectoryName(fullName);
                        bool   dateOK  = item.CreationDate > new DateTime(1970, 1, 2);

                        if (
                            (item.AssetType == AssetType.LSLText && cbScripts.Checked) ||
                            (item.AssetType == AssetType.Notecard && cbNoteCards.Checked) ||
                            (item.AssetType == AssetType.Texture && cbImages.Checked)
                            )
                        {
                            ListViewItem lvi = new ListViewItem
                            {
                                Text = n.Data.Name, Tag = n.Data, Name = n.Data.UUID.ToString()
                            };

                            ListViewItem.ListViewSubItem fileName = new ListViewItem.ListViewSubItem(lvi, filePartial);
                            lvi.SubItems.Add(fileName);

                            ListViewItem.ListViewSubItem status = new ListViewItem.ListViewSubItem(lvi, "Fetching asset");
                            lvi.SubItems.Add(status);

                            //bool cached = dateOK && File.Exists(fullName) && File.GetCreationTimeUtc(fullName) == item.CreationDate;

                            //if (cached)
                            //{
                            //    status.Text = "Cached";
                            //}

                            backupTaskCancelToken.Token.ThrowIfCancellationRequested();

                            BeginInvoke(new MethodInvoker(() =>
                            {
                                lvwFiles.Items.Add(lvi);
                                lvwFiles.EnsureVisible(lvwFiles.Items.Count - 1);
                            }));

                            //if (cached) continue;
                            backupTaskCancelToken.Token.ThrowIfCancellationRequested();

                            Asset receivedAsset = null;
                            using (AutoResetEvent done = new AutoResetEvent(false))
                            {
                                if (item.AssetType == AssetType.Texture)
                                {
                                    client.Assets.RequestImage(item.AssetUUID, (state, asset) =>
                                    {
                                        if (state == TextureRequestState.Finished && asset != null && asset.Decode())
                                        {
                                            receivedAsset = asset;
                                            done.Set();
                                        }
                                    });
                                }
                                else
                                {
                                    var transferID = UUID.Random();
                                    client.Assets.RequestInventoryAsset(item, true, transferID, (transfer, asset) =>
                                    {
                                        if (transfer.Success && transfer.ID == transferID)
                                        {
                                            receivedAsset = asset;
                                        }
                                        done.Set();
                                    }
                                                                        );
                                }

                                backupTaskCancelToken.Token.ThrowIfCancellationRequested();
                                done.WaitOne(30 * 1000, false);
                            }

                            client.Settings.USE_ASSET_CACHE = true;

                            backupTaskCancelToken.Token.ThrowIfCancellationRequested();
                            if (receivedAsset == null)
                            {
                                BeginInvoke(new MethodInvoker(() => status.Text = "Failed to fetch asset"));
                            }
                            else
                            {
                                BeginInvoke(new MethodInvoker(() => status.Text = "Saving..."));

                                try
                                {
                                    backupTaskCancelToken.Token.ThrowIfCancellationRequested();
                                    if (!Directory.Exists(dirName))
                                    {
                                        Directory.CreateDirectory(dirName);
                                    }

                                    switch (item.AssetType)
                                    {
                                    case AssetType.Notecard:
                                        AssetNotecard note = (AssetNotecard)receivedAsset;
                                        if (note.Decode())
                                        {
                                            File.WriteAllText(fullName, note.BodyText, System.Text.Encoding.UTF8);
                                            if (dateOK)
                                            {
                                                File.SetCreationTimeUtc(fullName, item.CreationDate);
                                                File.SetLastWriteTimeUtc(fullName, item.CreationDate);
                                            }
                                        }
                                        else
                                        {
                                            Logger.Log(string.Format("Falied to decode asset for '{0}' - {1}", item.Name, receivedAsset.AssetID), Helpers.LogLevel.Warning, client);
                                        }

                                        break;

                                    case AssetType.LSLText:
                                        AssetScriptText script = (AssetScriptText)receivedAsset;
                                        if (script.Decode())
                                        {
                                            File.WriteAllText(fullName, script.Source, System.Text.Encoding.UTF8);
                                            if (dateOK)
                                            {
                                                File.SetCreationTimeUtc(fullName, item.CreationDate);
                                                File.SetLastWriteTimeUtc(fullName, item.CreationDate);
                                            }
                                        }
                                        else
                                        {
                                            Logger.Log(string.Format("Falied to decode asset for '{0}' - {1}", item.Name, receivedAsset.AssetID), Helpers.LogLevel.Warning, client);
                                        }

                                        break;

                                    case AssetType.Texture:
                                        AssetTexture imgAsset = (AssetTexture)receivedAsset;
                                        var          img      = LoadTGAClass.LoadTGA(new MemoryStream(imgAsset.Image.ExportTGA()));
                                        img.Save(fullName, System.Drawing.Imaging.ImageFormat.Png);
                                        if (dateOK)
                                        {
                                            File.SetCreationTimeUtc(fullName, item.CreationDate);
                                            File.SetLastWriteTimeUtc(fullName, item.CreationDate);
                                        }
                                        break;
                                    }

                                    BeginInvoke(new MethodInvoker(() =>
                                    {
                                        fileName.Text  = fullName;
                                        status.Text    = "Saved";
                                        lblStatus.Text = string.Format("Saved {0} items", ++fetched);
                                    }));
                                }
                                catch (OperationCanceledException)
                                {
                                    BeginInvoke(new MethodInvoker(() => status.Text = "Operation cancelled."));
                                    return;
                                }
                                catch (Exception ex)
                                {
                                    BeginInvoke(new MethodInvoker(() => status.Text = "Failed to save " + Path.GetFileName(fullName) + ": " + ex.Message));
                                }
                            }
                        }
                    }
                }
                catch (OperationCanceledException)
                {
                    return;
                }
                catch { }
            }
        }
Exemplo n.º 23
0
        public void TestSaveOar()
        {
            TestHelper.InMethod();
//            log4net.Config.XmlConfigurator.Configure();

            SceneObjectPart part1 = CreateSceneObjectPart1();
            SceneObjectGroup sog1 = new SceneObjectGroup(part1);
            m_scene.AddNewSceneObject(sog1, false);

            SceneObjectPart part2 = CreateSceneObjectPart2();
            
            AssetNotecard nc = new AssetNotecard();
            nc.BodyText = "Hello World!";
            nc.Encode();
            UUID ncAssetUuid = new UUID("00000000-0000-0000-1000-000000000000");
            UUID ncItemUuid = new UUID("00000000-0000-0000-1100-000000000000");
            AssetBase ncAsset 
                = AssetHelpers.CreateAsset(ncAssetUuid, AssetType.Notecard, nc.AssetData, UUID.Zero);
            m_scene.AssetService.Store(ncAsset);
            SceneObjectGroup sog2 = new SceneObjectGroup(part2);
            TaskInventoryItem ncItem 
                = new TaskInventoryItem { Name = "ncItem", AssetID = ncAssetUuid, ItemID = ncItemUuid };
            part2.Inventory.AddInventoryItem(ncItem, true);
            
            m_scene.AddNewSceneObject(sog2, false);

            MemoryStream archiveWriteStream = new MemoryStream();
            m_scene.EventManager.OnOarFileSaved += SaveCompleted;

            Guid requestId = new Guid("00000000-0000-0000-0000-808080808080");
            
            lock (this)
            {
                m_archiverModule.ArchiveRegion(archiveWriteStream, requestId);
                //AssetServerBase assetServer = (AssetServerBase)scene.CommsManager.AssetCache.AssetServer;
                //while (assetServer.HasWaitingRequests())
                //    assetServer.ProcessNextRequest();
                
                Monitor.Wait(this, 60000);
            }
            
            Assert.That(m_lastRequestId, Is.EqualTo(requestId));

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

            bool gotNcAssetFile = false;
            
            string expectedNcAssetFileName = string.Format("{0}_{1}", ncAssetUuid, "notecard.txt");

            List<string> foundPaths = new List<string>();
            List<string> expectedPaths = new List<string>();
            expectedPaths.Add(ArchiveHelpers.CreateObjectPath(sog1));
            expectedPaths.Add(ArchiveHelpers.CreateObjectPath(sog2));

            string filePath;
            TarArchiveReader.TarEntryType tarEntryType;         

            byte[] data = tar.ReadEntry(out filePath, out tarEntryType);
            Assert.That(filePath, Is.EqualTo(ArchiveConstants.CONTROL_FILE_PATH));
            
            ArchiveReadRequest arr = new ArchiveReadRequest(m_scene, (Stream)null, false, false, Guid.Empty);
            arr.LoadControlFile(filePath, data);
            
            Assert.That(arr.ControlFileLoaded, Is.True);        
            
            while (tar.ReadEntry(out filePath, out tarEntryType) != null)
            {
                if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH))
                {
                    string fileName = filePath.Remove(0, ArchiveConstants.ASSETS_PATH.Length);

                    Assert.That(fileName, Is.EqualTo(expectedNcAssetFileName));
                    gotNcAssetFile = true;
                }
                else if (filePath.StartsWith(ArchiveConstants.OBJECTS_PATH))
                {
                    foundPaths.Add(filePath);
                }
            }

            Assert.That(gotNcAssetFile, Is.True, "No notecard asset file in archive");
            Assert.That(foundPaths, Is.EquivalentTo(expectedPaths));

            // TODO: Test presence of more files and contents of files.
        }
Exemplo n.º 24
0
        public void TestLoadPublishedOar()
        {
            TestHelpers.InMethod();
//            log4net.Config.XmlConfigurator.Configure();

            SceneObjectPart  part1 = CreateSceneObjectPart1();
            SceneObjectGroup sog1  = new SceneObjectGroup(part1);

            m_scene.AddNewSceneObject(sog1, false);

            SceneObjectPart part2 = CreateSceneObjectPart2();

            AssetNotecard nc = new AssetNotecard();

            nc.BodyText = "Hello World!";
            nc.Encode();
            UUID      ncAssetUuid = new UUID("00000000-0000-0000-1000-000000000000");
            UUID      ncItemUuid  = new UUID("00000000-0000-0000-1100-000000000000");
            AssetBase ncAsset
                = AssetHelpers.CreateAsset(ncAssetUuid, AssetType.Notecard, nc.AssetData, UUID.Zero);

            m_scene.AssetService.Store(ncAsset);
            SceneObjectGroup  sog2 = new SceneObjectGroup(part2);
            TaskInventoryItem ncItem
                = new TaskInventoryItem {
                Name = "ncItem", AssetID = ncAssetUuid, ItemID = ncItemUuid
                };

            part2.Inventory.AddInventoryItem(ncItem, true);

            m_scene.AddNewSceneObject(sog2, false);

            MemoryStream archiveWriteStream = new MemoryStream();

            m_scene.EventManager.OnOarFileSaved += SaveCompleted;

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

            lock (this)
            {
                m_archiverModule.ArchiveRegion(
                    archiveWriteStream, requestId, new Dictionary <string, Object>()
                {
                    { "wipe-owners", Boolean.TrueString }
                });

                Monitor.Wait(this, 60000);
            }

            Assert.That(m_lastRequestId, Is.EqualTo(requestId));

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

            {
                UUID estateOwner = TestHelpers.ParseTail(0x4747);
                UUID objectOwner = TestHelpers.ParseTail(0x15);

                // Reload to new scene
                ArchiverModule   archiverModule   = new ArchiverModule();
                SerialiserModule serialiserModule = new SerialiserModule();
                TerrainModule    terrainModule    = new TerrainModule();

                SceneHelpers m_sceneHelpers2 = new SceneHelpers();
                TestScene    scene2          = m_sceneHelpers2.SetupScene();
                SceneHelpers.SetupSceneModules(scene2, archiverModule, serialiserModule, terrainModule);

                // Make sure there's a valid owner for the owner we saved (this should have been wiped if the code is
                // behaving correctly
                UserAccountHelpers.CreateUserWithInventory(scene2, objectOwner);

                scene2.RegionInfo.EstateSettings.EstateOwner = estateOwner;

                lock (this)
                {
                    scene2.EventManager.OnOarFileLoaded += LoadCompleted;
                    archiverModule.DearchiveRegion(archiveReadStream);
                }

                Assert.That(m_lastErrorMessage, Is.Null);

                SceneObjectGroup loadedSog = scene2.GetSceneObjectGroup(part1.Name);
                Assert.That(loadedSog.OwnerID, Is.EqualTo(estateOwner));
                Assert.That(loadedSog.LastOwnerID, Is.EqualTo(estateOwner));
            }
        }
            /// <summary>
            /// Called by the CopyInventoryFromNotecard caps handler.
            /// </summary>
            /// <param name="request"></param>
            /// <param name="path"></param>
            /// <param name="param"></param>
            public string CopyInventoryFromNotecard(string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
            {
                Hashtable response = new Hashtable();
                response["int_response_code"] = 404;
                response["content_type"] = "text/plain";
                response["str_response_string"] = String.Empty;

                IClientAPI client = null;
                m_Scene.TryGetClient(m_Caps.AgentID, out client); 
                if (client == null)
                    return LLSDHelpers.SerializeLLSDReply(response);

                try
                {        
                    OSDMap content = (OSDMap)OSDParser.DeserializeLLSDXml(request);
                    UUID objectID = content["object-id"].AsUUID();
                    UUID notecardID = content["notecard-id"].AsUUID();
                    UUID folderID = content["folder-id"].AsUUID();
                    UUID itemID = content["item-id"].AsUUID();

                    // m_log.InfoFormat("[CAPS]: CopyInventoryFromNotecard, FolderID:{0}, ItemID:{1}, NotecardID:{2}, ObjectID:{3}", folderID, itemID, notecardID, objectID);

                    InventoryItemBase notecardItem = null;
                    IInventoryStorage inventoryService = m_inventoryProviderSelector.GetProvider(m_Caps.AgentID);

                    // Is this an objects task inventory?
                    if (objectID != UUID.Zero)
                    {
                        SceneObjectPart part = m_Scene.GetSceneObjectPart(objectID);
                        if (part != null)
                        {
                            TaskInventoryItem item = part.Inventory.GetInventoryItem(notecardID);
                            if (m_Scene.Permissions.CanCopyObjectInventory(notecardID, objectID, m_Caps.AgentID))
                            {
                                notecardItem = new InventoryItemBase(notecardID, m_agentID) { AssetID = item.AssetID };
                            }
                        }
                    }
                    // else its in inventory directly
                    else
                    {
                        notecardItem = inventoryService.GetItem(notecardID, UUID.Zero);
                    }

                    if ((notecardItem != null) && (notecardItem.Owner == m_agentID))
                    {
                        // Lookup up the notecard asset
                        IAssetCache assetCache = m_Scene.CommsManager.AssetCache;
                        AssetBase asset = assetCache.GetAsset(notecardItem.AssetID, AssetRequestInfo.InternalRequest());

                        if (asset != null)
                        {
                            AssetNotecard notecardAsset = new AssetNotecard(UUID.Zero, asset.Data);
                            notecardAsset.Decode();

                            InventoryItemBase item = null;
                            foreach (InventoryItem notecardObjectItem in notecardAsset.EmbeddedItems)
                            {
                                if (notecardObjectItem.UUID == itemID)
                                {
                                    item = new InventoryItemBase(UUID.Random(), m_Caps.AgentID);
                                    item.CreatorId = notecardObjectItem.CreatorID.ToString();
                                    item.CreationDate = Util.UnixTimeSinceEpoch();
                                    item.GroupID = notecardObjectItem.GroupID;
                                    item.AssetID = notecardObjectItem.AssetUUID;
                                    item.Name = notecardObjectItem.Name;
                                    item.Description = notecardObjectItem.Description;
                                    item.AssetType = (int)notecardObjectItem.AssetType;
                                    item.InvType = (int)notecardObjectItem.InventoryType;
                                    item.Folder = folderID;

                                    //item.BasePermissions = (uint)notecardObjectItem.Permissions.BaseMask;
                                    item.BasePermissions = (uint)(PermissionMask.All | PermissionMask.Export);
                                    item.CurrentPermissions = (uint)(PermissionMask.All | PermissionMask.Export);
                                    item.GroupPermissions = (uint)PermissionMask.None;
                                    item.EveryOnePermissions = (uint)PermissionMask.None;
                                    item.NextPermissions = (uint)PermissionMask.All;
                                    break;
                                }
                            }

                            if (item != null)
                            {
                                m_Scene.AddInventoryItem(m_Caps.AgentID, item);
                                // m_log.InfoFormat("[CAPS]: SendInventoryItemCreateUpdate ItemID:{0}, AssetID:{1}", item.ID, item.AssetID);
                                client.SendInventoryItemCreateUpdate(item,0);
                                response["int_response_code"] = 200;
                                return LLSDHelpers.SerializeLLSDReply(response);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    m_log.ErrorFormat("[CAPS]: CopyInventoryFromNotecard : {0}", e.ToString());
                }

                // Failure case
                client.SendAlertMessage("Failed to retrieve item");
                return LLSDHelpers.SerializeLLSDReply(response);
            }
Exemplo n.º 26
0
        private byte[] CopyInventoryFromNotecard(Stream request, UUID agentID)
        {
            OSDMap rm              = (OSDMap)OSDParser.DeserializeLLSDXml(HttpServerHandlerHelpers.ReadFully(request));
            UUID   FolderID        = rm["folder-id"].AsUUID();
            UUID   ItemID          = rm["item-id"].AsUUID();
            UUID   NotecardID      = rm["notecard-id"].AsUUID();
            UUID   ObjectID        = rm["object-id"].AsUUID();
            UUID   notecardAssetID = UUID.Zero;

            if (ObjectID != UUID.Zero)
            {
                ISceneChildEntity part = m_scene.GetSceneObjectPart(ObjectID);
                if (part != null)
                {
                    TaskInventoryItem item = part.Inventory.GetInventoryItem(NotecardID);
                    if (m_scene.Permissions.CanCopyObjectInventory(NotecardID, ObjectID, agentID))
                    {
                        notecardAssetID = item.AssetID;
                    }
                }
            }
            else
            {
                notecardAssetID = m_scene.InventoryService.GetItemAssetID(agentID, NotecardID);
            }
            if (notecardAssetID != UUID.Zero)
            {
                byte[] asset = m_scene.AssetService.GetData(notecardAssetID.ToString());
                if (asset != null)
                {
                    AssetNotecard noteCardAsset = new AssetNotecard(UUID.Zero, asset);
                    noteCardAsset.Decode();
                    bool found       = false;
                    UUID lastOwnerID = UUID.Zero;
                    foreach (
                        InventoryItem notecardObjectItem in
                        noteCardAsset.EmbeddedItems.Where(notecardObjectItem => notecardObjectItem.UUID == ItemID))
                    {
                        //Make sure that it exists
                        found       = true;
                        lastOwnerID = notecardObjectItem.OwnerID;
                        break;
                    }
                    if (found)
                    {
                        m_scene.InventoryService.GiveInventoryItemAsync(agentID, lastOwnerID, ItemID, FolderID, false,
                                                                        (item) =>
                        {
                            IClientAPI client;
                            m_scene.ClientManager.TryGetValue(
                                agentID, out client);
                            if (item != null)
                            {
                                client.SendBulkUpdateInventory(item);
                            }
                            else
                            {
                                client.SendAlertMessage(
                                    "Failed to retrieve item");
                            }
                        });
                    }
                }
            }

            return(new byte[0]);
        }
Exemplo n.º 27
0
        /// <summary>
        /// </summary>
        /// <param name="assetData"></param>
        override internal void SetAssetData(byte[] assetData)
		{
			if( _Asset == null )
			{
				if( AssetID != null )
				{
					_Asset = new AssetNotecard( AssetID, assetData );
				} 
				else 
				{
					_Asset   = new AssetNotecard( LLUUID.Random(), assetData );
					_AssetID = _Asset.AssetID;
				}
			} 
			else 
			{
				_Asset.SetAssetData(assetData);
			}

		}
Exemplo n.º 28
0
        //Separate thread
        private void Assets_OnAssetReceived(AssetDownload transfer, Asset asset)
        {
            if (InvokeRequired)
            {
                BeginInvoke(new MethodInvoker(delegate()
                    {
                        Assets_OnAssetReceived(transfer, asset);
                    }
                ));

                return;
            }

            //if (transfer.AssetType != AssetType.Notecard) return;

            if (!transfer.Success)
            {
                notecardContent = "Unable to download notecard.";
                SetNotecardText(notecardContent, false);
                return;
            }

            receivedAsset = (AssetNotecard)asset;
            notecardContent = Utils.BytesToString(transfer.AssetData);

            SetNotecardText(notecardContent, false);
        }
Exemplo n.º 29
0
        Process(RestBot b, Dictionary <string, string> Parameters)
        {
            UUID embedItemID = UUID.Zero;
            string
                notecardName,
                notecardData;

            DebugUtilities.WriteDebug("Entering key parser");
            try
            {
                // item ID to embed is optional; handle later
                if (Parameters.ContainsKey("key"))
                {
                    UUID
                    .TryParse(Parameters["key"].ToString().Replace("_", " "),
                              out embedItemID);
                }

                // notecard data is required!
                if (Parameters.ContainsKey("notecard"))
                {
                    DebugUtilities
                    .WriteDebug("Attempting to parse notecard data from POST");
                    notecardData = Parameters["notecard"];
                }
                else
                {
                    return("<error>notecard text data not found</error>");
                }

                // notecard name is optional, we'll assign a random name
                if (Parameters.ContainsKey("name"))
                {
                    DebugUtilities
                    .WriteDebug("Attempting to parse notecard name from POST");
                    notecardName = Parameters["name"];

                    DebugUtilities.WriteDebug("Succesfully parsed POST");
                }
                else
                {
                    notecardName = "(no name)";
                }

                UUID
                    notecardItemID  = UUID.Zero,
                    notecardAssetID = UUID.Zero;
                bool
                    success                  = false,
                    finalUploadSuccess       = false;
                string         message       = String.Empty;
                AutoResetEvent notecardEvent = new AutoResetEvent(false);

                DebugUtilities
                .WriteDebug($"Notecard data ('{notecardName}') found: '{notecardData}'");


                #region Notecard asset data

                AssetNotecard notecard = new AssetNotecard();
                notecard.BodyText = notecardData;

                // Item embedding
                if (embedItemID != UUID.Zero)
                {
                    // Try to fetch the inventory item
                    InventoryItem?item = FetchItem(b, embedItemID);
                    if (item != null)
                    {
                        notecard.EmbeddedItems = new List <InventoryItem> {
                            item
                        };
                        notecard.BodyText += (char)0xdbc0 + (char)0xdc00;
                    }
                    else
                    {
                        return("Failed to fetch inventory item " + embedItemID);
                    }
                }

                notecard.Encode();


                #endregion Notecard asset data


                b
                .Client
                .Inventory
                .RequestCreateItem(b
                                   .Client
                                   .Inventory
                                   .FindFolderForType(AssetType.Notecard),
                                   notecardName,
                                   notecardName + " created by LibreMetaverse RESTbot " + DateTime.Now,
                                   AssetType.Notecard,
                                   UUID.Random(),
                                   InventoryType.Notecard,
                                   PermissionMask.All,
                                   delegate(bool createSuccess, InventoryItem item)
                {
                    if (createSuccess)
                    {
                        #region Upload an empty notecard asset first

                        AutoResetEvent emptyNoteEvent = new AutoResetEvent(false);
                        AssetNotecard empty           = new AssetNotecard();
                        empty.BodyText = "\n";
                        empty.Encode();

                        b
                        .Client
                        .Inventory
                        .RequestUploadNotecardAsset(empty.AssetData,
                                                    item.UUID,
                                                    delegate(
                                                        bool uploadSuccess,
                                                        string status,
                                                        UUID itemID,
                                                        UUID assetID)
                        {
                            notecardItemID  = itemID;
                            notecardAssetID = assetID;
                            success         = uploadSuccess;
                            message         = status ?? "Unknown error uploading notecard asset";
                            emptyNoteEvent.Set();
                        });

                        emptyNoteEvent.WaitOne(NOTECARD_CREATE_TIMEOUT, false);


                        #endregion Upload an empty notecard asset first


                        if (success)
                        {
                            // Upload the actual notecard asset
                            b
                            .Client
                            .Inventory
                            .RequestUploadNotecardAsset(notecard.AssetData, item.UUID,
                                                        delegate(bool uploadSuccess, string status, UUID itemID, UUID assetID)
                            {
                                notecardItemID     = itemID;
                                notecardAssetID    = assetID;
                                finalUploadSuccess = uploadSuccess;
                                message            = status ?? "Unknown error uploading notecard asset";
                                notecardEvent.Set();
                            });
                        }
                        else
                        {
                            notecardEvent.Set();
                        }
                    }
                    else
                    {
                        message = "Notecard item creation failed";
                        notecardEvent.Set();
                    }
                });                         // end delegate // end RequestCreateItem

                notecardEvent.WaitOne(NOTECARD_CREATE_TIMEOUT, false);

                // DebugUtilities.WriteDebug("Notecard possibly created, ItemID " + notecardItemID + " AssetID " + notecardAssetID + " Content: '" + DownloadNotecard(b, notecardItemID, notecardAssetID) + "'");
                if (finalUploadSuccess)
                {
                    DebugUtilities
                    .WriteDebug($"Notecard successfully created, ItemID {notecardItemID}; AssetID {notecardAssetID}; Content: '{DownloadNotecard(b, notecardItemID, notecardAssetID)}'");
                    return($"<notecard><ItemID>{notecardItemID}</ItemID><AssetID>{notecardAssetID}</AssetID><name>{notecardName}</name></notecard>");
                }
                else
                {
                    return($"<error>Notecard creation failed: {message}</error>");
                }
            }             // end try
            catch (Exception e)
            {
                DebugUtilities.WriteError(e.Message);
                return($"<error>{MethodName}: {e.Message}</error>");
            }
        }
Exemplo n.º 30
0
        public void TestSaveOarV0_2()
        {
            TestHelper.InMethod();
            //log4net.Config.XmlConfigurator.Configure();

            SceneObjectPart  part1 = CreateSceneObjectPart1();
            SceneObjectGroup sog1  = new SceneObjectGroup(part1);

            m_scene.AddNewSceneObject(sog1, false);

            SceneObjectPart part2 = CreateSceneObjectPart2();

            AssetNotecard nc = new AssetNotecard();

            nc.BodyText = "Hello World!";
            nc.Encode();
            UUID      ncAssetUuid = new UUID("00000000-0000-0000-1000-000000000000");
            UUID      ncItemUuid  = new UUID("00000000-0000-0000-1100-000000000000");
            AssetBase ncAsset
                = AssetHelpers.CreateAsset(ncAssetUuid, AssetType.Notecard, nc.AssetData, UUID.Zero);

            m_scene.AssetService.Store(ncAsset);
            SceneObjectGroup  sog2 = new SceneObjectGroup(part2);
            TaskInventoryItem ncItem
                = new TaskInventoryItem {
                Name = "ncItem", AssetID = ncAssetUuid, ItemID = ncItemUuid
                };

            part2.Inventory.AddInventoryItem(ncItem, true);

            m_scene.AddNewSceneObject(sog2, false);

            MemoryStream archiveWriteStream = new MemoryStream();

            m_scene.EventManager.OnOarFileSaved += SaveCompleted;

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

            lock (this)
            {
                m_archiverModule.ArchiveRegion(archiveWriteStream, requestId);
                //AssetServerBase assetServer = (AssetServerBase)scene.CommsManager.AssetCache.AssetServer;
                //while (assetServer.HasWaitingRequests())
                //    assetServer.ProcessNextRequest();

                Monitor.Wait(this, 60000);
            }

            Assert.That(m_lastRequestId, Is.EqualTo(requestId));

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

            bool gotControlFile = false;
            bool gotNcAssetFile = false;

            string expectedNcAssetFileName = string.Format("{0}_{1}", ncAssetUuid, "notecard.txt");

            List <string> foundPaths    = new List <string>();
            List <string> expectedPaths = new List <string>();

            expectedPaths.Add(ArchiveHelpers.CreateObjectPath(sog1));
            expectedPaths.Add(ArchiveHelpers.CreateObjectPath(sog2));

            string filePath;

            TarArchiveReader.TarEntryType tarEntryType;

            while (tar.ReadEntry(out filePath, out tarEntryType) != null)
            {
                if (ArchiveConstants.CONTROL_FILE_PATH == filePath)
                {
                    gotControlFile = true;
                }
                else if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH))
                {
                    string fileName = filePath.Remove(0, ArchiveConstants.ASSETS_PATH.Length);

                    Assert.That(fileName, Is.EqualTo(expectedNcAssetFileName));
                    gotNcAssetFile = true;
                }
                else if (filePath.StartsWith(ArchiveConstants.OBJECTS_PATH))
                {
                    foundPaths.Add(filePath);
                }
            }

            Assert.That(gotControlFile, Is.True, "No control file in archive");
            Assert.That(gotNcAssetFile, Is.True, "No notecard asset file in archive");
            Assert.That(foundPaths, Is.EquivalentTo(expectedPaths));

            // TODO: Test presence of more files and contents of files.
        }
Exemplo n.º 31
0
        public void TestSaveOarNoAssets()
        {
            TestHelpers.InMethod();
//            log4net.Config.XmlConfigurator.Configure();

            SceneObjectPart  part1 = CreateSceneObjectPart1();
            SceneObjectGroup sog1  = new SceneObjectGroup(part1);

            m_scene.AddNewSceneObject(sog1, false);

            SceneObjectPart part2 = CreateSceneObjectPart2();

            AssetNotecard nc = new AssetNotecard();

            nc.BodyText = "Hello World!";
            nc.Encode();
            UUID      ncAssetUuid = new UUID("00000000-0000-0000-1000-000000000000");
            UUID      ncItemUuid  = new UUID("00000000-0000-0000-1100-000000000000");
            AssetBase ncAsset
                = AssetHelpers.CreateAsset(ncAssetUuid, AssetType.Notecard, nc.AssetData, UUID.Zero);

            m_scene.AssetService.Store(ncAsset);
            SceneObjectGroup  sog2 = new SceneObjectGroup(part2);
            TaskInventoryItem ncItem
                = new TaskInventoryItem {
                Name = "ncItem", AssetID = ncAssetUuid, ItemID = ncItemUuid
                };

            part2.Inventory.AddInventoryItem(ncItem, true);

            m_scene.AddNewSceneObject(sog2, false);

            MemoryStream archiveWriteStream = new MemoryStream();

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

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

            options.Add("noassets", true);
            m_archiverModule.ArchiveRegion(archiveWriteStream, requestId, options);

            // Don't wait for completion - with --noassets save oar happens synchronously
//                Monitor.Wait(this, 60000);

            Assert.That(m_lastRequestId, Is.EqualTo(requestId));

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

            List <string> foundPaths    = new List <string>();
            List <string> expectedPaths = new List <string>();

            expectedPaths.Add(ArchiveHelpers.CreateObjectPath(sog1));
            expectedPaths.Add(ArchiveHelpers.CreateObjectPath(sog2));

            string filePath;

            TarArchiveReader.TarEntryType tarEntryType;

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

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

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

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

            while (tar.ReadEntry(out filePath, out tarEntryType) != null)
            {
                if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH))
                {
                    Assert.Fail("Asset was found in saved oar of TestSaveOarNoAssets()");
                }
                else if (filePath.StartsWith(ArchiveConstants.OBJECTS_PATH))
                {
                    foundPaths.Add(filePath);
                }
            }

            Assert.That(foundPaths, Is.EquivalentTo(expectedPaths));

            // TODO: Test presence of more files and contents of files.
        }
Exemplo n.º 32
0
        void Assets_OnAssetReceived(AssetDownload transfer, Asset asset)
        {
            if (InvokeRequired)
            {
                if (!instance.MonoRuntime || IsHandleCreated)
                {
                    BeginInvoke(new MethodInvoker(() => Assets_OnAssetReceived(transfer, asset)));
                }
                return;
            }

            if (transfer.Success)
            {
                AssetNotecard n = (AssetNotecard)asset;
                n.Decode();
                receivedNotecard = n;

                string noteText = string.Empty;
                rtbContent.Clear();

                for (int i = 0; i < n.BodyText.Length; i++)
                {
                    char c = n.BodyText[i];

                    if ((int)c == 0xdbc0)
                    {
                        int           index = (int)n.BodyText[++i] - 0xdc00;
                        InventoryItem e     = n.EmbeddedItems[index];
                        rtbContent.AppendText(noteText);
                        rtbContent.InsertLink(e.Name, string.Format("radegast://embeddedasset/{0}", index));
                        noteText = string.Empty;
                    }
                    else
                    {
                        noteText += c;
                    }
                }

                rtbContent.Text += noteText;

                if (n.EmbeddedItems != null && n.EmbeddedItems.Count > 0)
                {
                    tbtnAttachments.Enabled = true;
                    tbtnAttachments.Visible = true;
                    foreach (InventoryItem item in n.EmbeddedItems)
                    {
                        int ix = InventoryConsole.GetItemImageIndex(item.AssetType.ToString().ToLower());
                        ToolStripMenuItem titem = new ToolStripMenuItem(item.Name);

                        if (ix != -1)
                        {
                            titem.Image        = frmMain.ResourceImages.Images[ix];
                            titem.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText;
                        }
                        else
                        {
                            titem.DisplayStyle = ToolStripItemDisplayStyle.Text;
                        }

                        titem.Name   = item.UUID.ToString();
                        titem.Tag    = item;
                        titem.Click += new EventHandler(attachmentMenuItem_Click);

                        var saveToInv = new ToolStripMenuItem("Save to inventory");
                        saveToInv.Click += (xsender, xe) =>
                        {
                            client.Inventory.RequestCopyItemFromNotecard(UUID.Zero,
                                                                         notecard.UUID,
                                                                         client.Inventory.FindFolderForType(item.AssetType),
                                                                         item.UUID,
                                                                         Inventory_OnInventoryItemCopied);
                        };

                        titem.DropDownItems.Add(saveToInv);
                        tbtnAttachments.DropDownItems.Add(titem);
                    }
                }
                UpdateStatus("OK");
                rtbContent.Focus();
            }
            else
            {
                UpdateStatus("Failed");
                rtbContent.Text = "Failed to download notecard. " + transfer.Status;
            }
        }
Exemplo n.º 33
0
        public void TestSaveOarNoAssets()
        {
            TestHelpers.InMethod();
//            log4net.Config.XmlConfigurator.Configure();

            SceneObjectPart part1 = CreateSceneObjectPart1();
            SceneObjectGroup sog1 = new SceneObjectGroup(part1);
            m_scene.AddNewSceneObject(sog1, false);

            SceneObjectPart part2 = CreateSceneObjectPart2();
            
            AssetNotecard nc = new AssetNotecard();
            nc.BodyText = "Hello World!";
            nc.Encode();
            UUID ncAssetUuid = new UUID("00000000-0000-0000-1000-000000000000");
            UUID ncItemUuid = new UUID("00000000-0000-0000-1100-000000000000");
            AssetBase ncAsset
                = AssetHelpers.CreateAsset(ncAssetUuid, AssetType.Notecard, nc.AssetData, UUID.Zero);
            m_scene.AssetService.Store(ncAsset);
            SceneObjectGroup sog2 = new SceneObjectGroup(part2);
            TaskInventoryItem ncItem 
                = new TaskInventoryItem { Name = "ncItem", AssetID = ncAssetUuid, ItemID = ncItemUuid };
            part2.Inventory.AddInventoryItem(ncItem, true);
            
            m_scene.AddNewSceneObject(sog2, false);

            MemoryStream archiveWriteStream = new MemoryStream();

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

            Dictionary<string, Object> options = new Dictionary<string, Object>();
            options.Add("noassets", true);
            m_archiverModule.ArchiveRegion(archiveWriteStream, requestId, options);

            // Don't wait for completion - with --noassets save oar happens synchronously
//                Monitor.Wait(this, 60000);

            Assert.That(m_lastRequestId, Is.EqualTo(requestId));

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

            List<string> foundPaths = new List<string>();
            List<string> expectedPaths = new List<string>();
            expectedPaths.Add(ArchiveHelpers.CreateObjectPath(sog1));
            expectedPaths.Add(ArchiveHelpers.CreateObjectPath(sog2));

            string filePath;
            TarArchiveReader.TarEntryType tarEntryType;         

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

            Dictionary<string, object> archiveOptions = new Dictionary<string, object>();
            ArchiveReadRequest arr = new ArchiveReadRequest(m_scene, (Stream)null, Guid.Empty, archiveOptions);
            arr.LoadControlFile(filePath, data, new DearchiveScenesInfo());
            
            Assert.That(arr.ControlFileLoaded, Is.True);        
            
            while (tar.ReadEntry(out filePath, out tarEntryType) != null)
            {
                if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH))
                {
                    Assert.Fail("Asset was found in saved oar of TestSaveOarNoAssets()");
                }
                else if (filePath.StartsWith(ArchiveConstants.OBJECTS_PATH))
                {
                    foundPaths.Add(filePath);
                }
            }

            Assert.That(foundPaths, Is.EquivalentTo(expectedPaths));

            // TODO: Test presence of more files and contents of files.
        }
Exemplo n.º 34
0
        private Hashtable CopyInventoryFromNotecard(Hashtable mDhttpMethod, UUID agentID)
        {
            OSDMap rm = (OSDMap) OSDParser.DeserializeLLSDXml((string) mDhttpMethod["requestbody"]);
            UUID FolderID = rm["folder-id"].AsUUID();
            UUID ItemID = rm["item-id"].AsUUID();
            UUID NotecardID = rm["notecard-id"].AsUUID();
            UUID ObjectID = rm["object-id"].AsUUID();
            InventoryItemBase notecardItem = null;
            if (ObjectID != UUID.Zero)
            {
                ISceneChildEntity part = m_scene.GetSceneObjectPart(ObjectID);
                if (part != null)
                {
                    TaskInventoryItem item = part.Inventory.GetInventoryItem(NotecardID);
                    if (m_scene.Permissions.CanCopyObjectInventory(NotecardID, ObjectID, agentID))
                    {
                        notecardItem = new InventoryItemBase(NotecardID, agentID) {AssetID = item.AssetID};
                    }
                }
            }
            else
                notecardItem = m_scene.InventoryService.GetItem(new InventoryItemBase(NotecardID));
            if (notecardItem != null && notecardItem.Owner == agentID)
            {
                AssetBase asset = m_scene.AssetService.Get(notecardItem.AssetID.ToString());
                if (asset != null)
                {
                    UTF8Encoding enc =
                        new UTF8Encoding();
                    List<string> notecardData = SLUtil.ParseNotecardToList(enc.GetString(asset.Data));
                    AssetNotecard noteCardAsset = new AssetNotecard(UUID.Zero, asset.Data);
                    noteCardAsset.Decode();
                    bool found = false;
                    UUID lastOwnerID = UUID.Zero;
#if (!ISWIN)
                    foreach (InventoryItem notecardObjectItem in noteCardAsset.EmbeddedItems)
                    {
                        if (notecardObjectItem.UUID == ItemID)
                        {
                            //Make sure that it exists
                            found = true;
                            lastOwnerID = notecardObjectItem.OwnerID;
                            break;
                        }
                    }
#else
                    foreach (InventoryItem notecardObjectItem in noteCardAsset.EmbeddedItems.Where(notecardObjectItem => notecardObjectItem.UUID == ItemID))
                    {
                        //Make sure that it exists
                        found = true;
                        lastOwnerID = notecardObjectItem.OwnerID;
                        break;
                    }
#endif
                    if (found)
                    {
                        InventoryItemBase item = null;
                        ILLClientInventory inventoryModule = m_scene.RequestModuleInterface<ILLClientInventory>();
                        if (inventoryModule != null)
                            item = inventoryModule.GiveInventoryItem(agentID, lastOwnerID, ItemID, FolderID);

                        IClientAPI client;
                        m_scene.ClientManager.TryGetValue(agentID, out client);
                        if (item != null)
                            client.SendBulkUpdateInventory(item);
                        else
                            client.SendAlertMessage("Failed to retrieve item");
                    }
                }
            }

            //Send back data
            Hashtable responsedata = new Hashtable();
            responsedata["int_response_code"] = 200; //501; //410; //404;
            responsedata["content_type"] = "text/plain";
            responsedata["keepalive"] = false;
            responsedata["str_response_string"] = "";
            return responsedata;
        }
Exemplo n.º 35
0
        public void TestOsOwnerSaveAppearance()
        {
            TestHelpers.InMethod();
//            log4net.Config.XmlConfigurator.Configure();

            UUID userId = TestHelpers.ParseTail(0x1);
            float newHeight = 1.9f;

            ScenePresence sp = SceneHelpers.AddScenePresence(m_scene, userId);
            sp.Appearance.AvatarHeight = newHeight;
            SceneObjectGroup so = SceneHelpers.CreateSceneObject(1, userId, 0x10);
            SceneObjectPart part = so.RootPart;
            m_scene.AddSceneObject(so);

            OSSL_Api osslApi = new OSSL_Api();
            osslApi.Initialize(m_engine, part, null, null);

            string notecardName = "appearanceNc";

            osslApi.osOwnerSaveAppearance(notecardName);

            IList<TaskInventoryItem> items = part.Inventory.GetInventoryItems(notecardName);
            Assert.That(items.Count, Is.EqualTo(1));

            TaskInventoryItem ncItem = items[0];
            Assert.That(ncItem.Name, Is.EqualTo(notecardName));

            AssetBase ncAsset = m_scene.AssetService.Get(ncItem.AssetID.ToString());
            Assert.That(ncAsset, Is.Not.Null);

            AssetNotecard anc = new AssetNotecard(UUID.Zero, ncAsset.Data);
            anc.Decode();
            OSDMap appearanceOsd = (OSDMap)OSDParser.DeserializeLLSDXml(anc.BodyText);
            AvatarAppearance savedAppearance = new AvatarAppearance();
            savedAppearance.Unpack(appearanceOsd);

            Assert.That(savedAppearance.AvatarHeight, Is.EqualTo(sp.Appearance.AvatarHeight));
        }
        private byte[] CopyInventoryFromNotecard(Stream request, UUID agentID)
        {
            OSDMap rm = (OSDMap) OSDParser.DeserializeLLSDXml(HttpServerHandlerHelpers.ReadFully(request));
            UUID FolderID = rm["folder-id"].AsUUID();
            UUID ItemID = rm["item-id"].AsUUID();
            UUID NotecardID = rm["notecard-id"].AsUUID();
            UUID ObjectID = rm["object-id"].AsUUID();
            UUID notecardAssetID = UUID.Zero;
            if (ObjectID != UUID.Zero)
            {
                ISceneChildEntity part = m_scene.GetSceneObjectPart(ObjectID);
                if (part != null)
                {
                    TaskInventoryItem item = part.Inventory.GetInventoryItem(NotecardID);
                    if (m_scene.Permissions.CanCopyObjectInventory(NotecardID, ObjectID, agentID))
                        notecardAssetID = item.AssetID;
                }
            }
            else
                notecardAssetID = m_scene.InventoryService.GetItemAssetID(agentID, NotecardID);
            if (notecardAssetID != UUID.Zero)
            {
                byte[] asset = m_scene.AssetService.GetData(notecardAssetID.ToString());
                if (asset != null)
                {
                    AssetNotecard noteCardAsset = new AssetNotecard(UUID.Zero, asset);
                    noteCardAsset.Decode();
                    bool found = false;
                    UUID lastOwnerID = UUID.Zero;
                    foreach (
                        InventoryItem notecardObjectItem in
                            noteCardAsset.EmbeddedItems.Where(notecardObjectItem => notecardObjectItem.UUID == ItemID))
                    {
                        //Make sure that it exists
                        found = true;
                        lastOwnerID = notecardObjectItem.OwnerID;
                        break;
                    }
                    if (found)
                    {
                        m_scene.InventoryService.GiveInventoryItemAsync(agentID, lastOwnerID, ItemID, FolderID, false,
                                                                        (item) =>
                                                                            {
                                                                                IClientAPI client;
                                                                                m_scene.ClientManager.TryGetValue(
                                                                                    agentID, out client);
                                                                                if (item != null)
                                                                                    client.SendBulkUpdateInventory(item);
                                                                                else
                                                                                    client.SendAlertMessage(
                                                                                        "Failed to retrieve item");
                                                                            });
                    }
                }
            }

            return new byte[0];
        }
Exemplo n.º 37
0
        public static Asset CreateAssetWrapper(AssetType type, UUID uuid, byte[] data)
        {
            Asset asset;

            switch (type)
            {
            case AssetType.Animation:
                asset = new AssetAnimation(uuid, data);
                break;

            case AssetType.Gesture:
                asset = new AssetGesture(uuid, data);
                break;

            case AssetType.Landmark:
                asset = new AssetLandmark(uuid, data);
                break;

            case AssetType.Bodypart:
                asset = new AssetBodypart(uuid, data);
                break;

            case AssetType.Clothing:
                asset = new AssetClothing(uuid, data);
                break;

            case AssetType.LSLBytecode:
                asset = new AssetScriptBinary(uuid, data);
                break;

            case AssetType.LSLText:
                asset = new AssetScriptText(uuid, data);
                break;

            case AssetType.Notecard:
                asset = new AssetNotecard(uuid, data);
                break;

            case AssetType.Sound:
                asset = new AssetSound(uuid, data);
                break;

            case AssetType.Texture:
                asset = new AssetTexture(uuid, data);
                break;

#if COGBOT_LIBOMV
            case AssetType.CallingCard:
                asset = new AssetCallingCard(uuid, data);
                break;
#endif
            default:
#if COGBOT_LIBOMV
                asset = new AssetMutable(type, uuid, data);
                Logger.Log("[OarFile] Not Implemented asset type " + type, Helpers.LogLevel.Error);
#else
                throw new NotImplementedException("Unimplemented asset type: " + type);
#endif
                break;
            }
            return(asset);
        }
Exemplo n.º 38
0
        void menu_on_new_note(object o, ButtonPressEventArgs args)
        {
            Gtk.TreeModel mod;
            Gtk.TreeIter iter;

            TreePath[] paths = treeview_inv.Selection.GetSelectedRows(out mod);
            if(paths.Length!=1)
                return;

            foreach (TreePath path in paths)
            {
                if (mod.GetIter(out iter, path))
                {
                    InventoryBase item = (InventoryBase)mod.GetValue(iter, 3);
                    if(item is InventoryFolder)
                    {
                        MainClass.client.Inventory.RequestCreateItem(item.UUID,
                        "New Note", "New Note", AssetType.Notecard, UUID.Random(), InventoryType.Notecard, PermissionMask.All,
                        delegate(bool success, InventoryItem itemx)
                        {
                            if (success) // upload the asset
                            {

                                AssetNotecard note = new AssetNotecard();
                                note.BodyText="Add your notes here....";
                                note.Encode();

                                MainClass.client.Inventory.RequestUploadNotecardAsset(note.AssetData, itemx.UUID,delegate (bool success2,string status,UUID item_uuid, UUID asset_uuid)
                                {
                                    Gtk.TreeIter iterx;

                                    if(success2 && assetmap.TryGetValue(item.UUID,out iterx))
                                    {
                                        Gdk.Pixbuf buf = getprettyicon(itemx);
                                        Gtk.TreeIter newiter = inventory.AppendValues(iterx, buf, "New Note", itemx.UUID, itemx);
                                        assetmap.Add(item_uuid,newiter);

                                        treeview_inv.Selection.SelectIter(filter.ConvertChildIterToIter(newiter));
                                        treeview_inv.ScrollToCell(inventory.GetPath(newiter), null, true, (float)0.5, (float)0.5);
                                        treeview_inv.SetCursor(inventory.GetPath(newiter), null, true);

                                    }
                                });
                            }
                        });

             		            }
                }
            }
        }
 /// <summary>
 /// </summary>
 /// <param name="assetData"></param>
 internal override void SetAssetData(byte[] assetData)
 {
     if( _Asset == null )
     {
         if( AssetID != null )
         {
             _Asset = new AssetNotecard( AssetID, assetData );
         }
         else
         {
             _Asset   = new AssetNotecard( LLUUID.GenerateUUID(), assetData );
             _AssetID = _Asset.AssetID;
         }
     }
     else
     {
         _Asset.AssetData = assetData;
     }
 }
Exemplo n.º 40
0
        private void CreateTestObjects(Scene scene, out SceneObjectGroup sog1, out SceneObjectGroup sog2, out UUID ncAssetUuid)
        {
            SceneObjectPart part1 = CreateSceneObjectPart1();
            sog1 = new SceneObjectGroup(part1);
            scene.AddNewSceneObject(sog1, false);

            AssetNotecard nc = new AssetNotecard();
            nc.BodyText = "Hello World!";
            nc.Encode();
            ncAssetUuid = UUID.Random();
            UUID ncItemUuid = UUID.Random();
            AssetBase ncAsset
                = AssetHelpers.CreateAsset(ncAssetUuid, AssetType.Notecard, nc.AssetData, UUID.Zero);
            m_scene.AssetService.Store(ncAsset);

            TaskInventoryItem ncItem
                = new TaskInventoryItem { Name = "ncItem", AssetID = ncAssetUuid, ItemID = ncItemUuid };
            SceneObjectPart part2 = CreateSceneObjectPart2();
            sog2 = new SceneObjectGroup(part2);
            part2.Inventory.AddInventoryItem(ncItem, true);

            scene.AddNewSceneObject(sog2, false);
        }
Exemplo n.º 41
0
        /// <summary>
        /// Create an asset from the given data.
        /// </summary>
        public static AssetBase CreateAsset(UUID assetUuid, AssetType assetType, string text, UUID creatorID)
        {
            AssetNotecard anc = new AssetNotecard();
            anc.BodyText = text;
            anc.Encode();

            return CreateAsset(assetUuid, assetType, anc.AssetData, creatorID);
        }
Exemplo n.º 42
0
        public void TestLoadPublishedOar()
        {
            TestHelpers.InMethod();
//            log4net.Config.XmlConfigurator.Configure();

            SceneObjectPart part1 = CreateSceneObjectPart1();
            SceneObjectGroup sog1 = new SceneObjectGroup(part1);
            m_scene.AddNewSceneObject(sog1, false);

            SceneObjectPart part2 = CreateSceneObjectPart2();
            
            AssetNotecard nc = new AssetNotecard();
            nc.BodyText = "Hello World!";
            nc.Encode();
            UUID ncAssetUuid = new UUID("00000000-0000-0000-1000-000000000000");
            UUID ncItemUuid = new UUID("00000000-0000-0000-1100-000000000000");
            AssetBase ncAsset 
                = AssetHelpers.CreateAsset(ncAssetUuid, AssetType.Notecard, nc.AssetData, UUID.Zero);
            m_scene.AssetService.Store(ncAsset);
            SceneObjectGroup sog2 = new SceneObjectGroup(part2);
            TaskInventoryItem ncItem 
                = new TaskInventoryItem { Name = "ncItem", AssetID = ncAssetUuid, ItemID = ncItemUuid };
            part2.Inventory.AddInventoryItem(ncItem, true);
            
            m_scene.AddNewSceneObject(sog2, false);

            MemoryStream archiveWriteStream = new MemoryStream();
            m_scene.EventManager.OnOarFileSaved += SaveCompleted;

            Guid requestId = new Guid("00000000-0000-0000-0000-808080808080");
            
            lock (this)
            {
                m_archiverModule.ArchiveRegion(
                    archiveWriteStream, requestId, new Dictionary<string, Object>() { { "wipe-owners", Boolean.TrueString } });
                
                Monitor.Wait(this, 60000);
            }
            
            Assert.That(m_lastRequestId, Is.EqualTo(requestId));

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

            {
                UUID estateOwner = TestHelpers.ParseTail(0x4747);
                UUID objectOwner = TestHelpers.ParseTail(0x15);

                // Reload to new scene
                ArchiverModule archiverModule = new ArchiverModule();
                SerialiserModule serialiserModule = new SerialiserModule();
                TerrainModule terrainModule = new TerrainModule();

                SceneHelpers m_sceneHelpers2 = new SceneHelpers();
                TestScene scene2 = m_sceneHelpers2.SetupScene();
                SceneHelpers.SetupSceneModules(scene2, archiverModule, serialiserModule, terrainModule);

                // Make sure there's a valid owner for the owner we saved (this should have been wiped if the code is
                // behaving correctly
                UserAccountHelpers.CreateUserWithInventory(scene2, objectOwner);

                scene2.RegionInfo.EstateSettings.EstateOwner = estateOwner;

                lock (this)
                {
                    scene2.EventManager.OnOarFileLoaded += LoadCompleted;
                    archiverModule.DearchiveRegion(archiveReadStream);
                }

                Assert.That(m_lastErrorMessage, Is.Null);

                SceneObjectGroup loadedSog = scene2.GetSceneObjectGroup(part1.Name);
                Assert.That(loadedSog.OwnerID, Is.EqualTo(estateOwner));
                Assert.That(loadedSog.LastOwnerID, Is.EqualTo(estateOwner));
            }
        }
Exemplo n.º 43
0
        public override string Execute(string[] args, UUID fromAgentID)
        {
            UUID embedItemID = UUID.Zero, notecardItemID = UUID.Zero, notecardAssetID = UUID.Zero;
            string filename, fileData;
            bool success = false, finalUploadSuccess = false;
            string message = String.Empty;
            AutoResetEvent notecardEvent = new AutoResetEvent(false);

            if (args.Length == 1)
            {
                filename = args[0];
            }
            else if (args.Length == 2)
            {
                filename = args[0];
                UUID.TryParse(args[1], out embedItemID);
            }
            else
            {
                return "Usage: createnotecard filename.txt";
            }

            if (!File.Exists(filename))
                return "File \"" + filename + "\" does not exist";

            try { fileData = File.ReadAllText(filename); }
            catch (Exception ex) { return "Failed to open " + filename + ": " + ex.Message; }

            #region Notecard asset data

            AssetNotecard notecard = new AssetNotecard();
            notecard.BodyText = fileData;

            // Item embedding
            if (embedItemID != UUID.Zero)
            {
                // Try to fetch the inventory item
                InventoryItem item = FetchItem(embedItemID);
                if (item != null)
                {
                    notecard.EmbeddedItems = new List<InventoryItem> { item };
                    notecard.BodyText += (char)0xdbc0 + (char)0xdc00;
                }
                else
                {
                    return "Failed to fetch inventory item " + embedItemID;
                }
            }

            notecard.Encode();

            #endregion Notecard asset data

            Client.Inventory.RequestCreateItem(Client.Inventory.FindFolderForType(AssetType.Notecard),
                filename, filename + " created by OpenMetaverse TestClient " + DateTime.Now, AssetType.Notecard,
                UUID.Random(), InventoryType.Notecard, PermissionMask.All,
                delegate(bool createSuccess, InventoryItem item)
                {
                    if (createSuccess)
                    {
                        #region Upload an empty notecard asset first

                        AutoResetEvent emptyNoteEvent = new AutoResetEvent(false);
                        AssetNotecard empty = new AssetNotecard();
                        empty.BodyText = "\n";
                        empty.Encode();

                        Client.Inventory.RequestUploadNotecardAsset(empty.AssetData, item.UUID,
                            delegate(bool uploadSuccess, string status, UUID itemID, UUID assetID)
                            {
                                notecardItemID = itemID;
                                notecardAssetID = assetID;
                                success = uploadSuccess;
                                message = status ?? "Unknown error uploading notecard asset";
                                emptyNoteEvent.Set();
                            });

                        emptyNoteEvent.WaitOne(NOTECARD_CREATE_TIMEOUT, false);

                        #endregion Upload an empty notecard asset first

                        if (success)
                        {
                            // Upload the actual notecard asset
                            Client.Inventory.RequestUploadNotecardAsset(notecard.AssetData, item.UUID,
                                delegate(bool uploadSuccess, string status, UUID itemID, UUID assetID)
                                {
                                    notecardItemID = itemID;
                                    notecardAssetID = assetID;
                                    finalUploadSuccess = uploadSuccess;
                                    message = status ?? "Unknown error uploading notecard asset";
                                    notecardEvent.Set();
                                });
                        }
                        else
                        {
                            notecardEvent.Set();
                        }
                    }
                    else
                    {
                        message = "Notecard item creation failed";
                        notecardEvent.Set();
                    }
                }
            );

            notecardEvent.WaitOne(NOTECARD_CREATE_TIMEOUT, false);

            if (finalUploadSuccess)
            {
                Logger.Log("Notecard successfully created, ItemID " + notecardItemID + " AssetID " + notecardAssetID, Helpers.LogLevel.Info);
                return DownloadNotecard(notecardItemID, notecardAssetID);
            }
            else
                return "Notecard creation failed: " + message;
        }
Exemplo n.º 44
0
        private Asset CreateAssetWrapper(AssetType type)
        {
            Asset asset;

            switch (type)
            {
                case AssetType.Notecard:
                    asset = new AssetNotecard();
                    break;
                case AssetType.LSLText:
                    asset = new AssetScriptText();
                    break;
                case AssetType.LSLBytecode:
                    asset = new AssetScriptBinary();
                    break;
                case AssetType.Texture:
                    asset = new AssetTexture();
                    break;
                case AssetType.Object:
                    asset = new AssetPrim();
                    break;
                case AssetType.Clothing:
                    asset = new AssetClothing();
                    break;
                case AssetType.Bodypart:
                    asset = new AssetBodypart();
                    break;
                case AssetType.Animation:
                    asset = new AssetAnimation();
                    break;
                case AssetType.Sound:
                    asset = new AssetSound();
                    break;
                case AssetType.Landmark:
                    asset = new AssetLandmark();
                    break;
                case AssetType.Gesture:
                    asset = new AssetGesture();
                    break;
                default:
                    Logger.Log("Unimplemented asset type: " + type, Helpers.LogLevel.Error, Client);
                    return null;
            }

            return asset;
        }
        public override string Execute(string[] args, UUID fromAgentID)
        {
            UUID           embedItemID = UUID.Zero, notecardItemID = UUID.Zero, notecardAssetID = UUID.Zero;
            string         filename, fileData;
            bool           success = false, finalUploadSuccess = false;
            string         message       = String.Empty;
            AutoResetEvent notecardEvent = new AutoResetEvent(false);

            if (args.Length == 1)
            {
                filename = args[0];
            }
            else if (args.Length == 2)
            {
                filename = args[0];
                UUID.TryParse(args[1], out embedItemID);
            }
            else
            {
                return("Usage: createnotecard filename.txt");
            }

            if (!File.Exists(filename))
            {
                return("File \"" + filename + "\" does not exist");
            }

            try { fileData = File.ReadAllText(filename); }
            catch (Exception ex) { return("Failed to open " + filename + ": " + ex.Message); }

            #region Notecard asset data

            AssetNotecard notecard = new AssetNotecard();
            notecard.BodyText = fileData;

            // Item embedding
            if (embedItemID != UUID.Zero)
            {
                // Try to fetch the inventory item
                InventoryItem item = FetchItem(embedItemID);
                if (item != null)
                {
                    notecard.EmbeddedItems = new List <InventoryItem> {
                        item
                    };
                    notecard.BodyText += (char)0xdbc0 + (char)0xdc00;
                }
                else
                {
                    return("Failed to fetch inventory item " + embedItemID);
                }
            }

            notecard.Encode();

            #endregion Notecard asset data

            Client.Inventory.RequestCreateItem(Client.Inventory.FindFolderForType(AssetType.Notecard),
                                               filename, filename + " created by OpenMetaverse TestClient " + DateTime.Now, AssetType.Notecard,
                                               UUID.Random(), InventoryType.Notecard, PermissionMask.All,
                                               delegate(bool createSuccess, InventoryItem item)
            {
                if (createSuccess)
                {
                    #region Upload an empty notecard asset first

                    AutoResetEvent emptyNoteEvent = new AutoResetEvent(false);
                    AssetNotecard empty           = new AssetNotecard();
                    empty.BodyText = "\n";
                    empty.Encode();

                    Client.Inventory.RequestUploadNotecardAsset(empty.AssetData, item.UUID,
                                                                delegate(bool uploadSuccess, string status, UUID itemID, UUID assetID)
                    {
                        notecardItemID  = itemID;
                        notecardAssetID = assetID;
                        success         = uploadSuccess;
                        message         = status ?? "Unknown error uploading notecard asset";
                        emptyNoteEvent.Set();
                    });

                    emptyNoteEvent.WaitOne(NOTECARD_CREATE_TIMEOUT, false);

                    #endregion Upload an empty notecard asset first

                    if (success)
                    {
                        // Upload the actual notecard asset
                        Client.Inventory.RequestUploadNotecardAsset(notecard.AssetData, item.UUID,
                                                                    delegate(bool uploadSuccess, string status, UUID itemID, UUID assetID)
                        {
                            notecardItemID     = itemID;
                            notecardAssetID    = assetID;
                            finalUploadSuccess = uploadSuccess;
                            message            = status ?? "Unknown error uploading notecard asset";
                            notecardEvent.Set();
                        });
                    }
                    else
                    {
                        notecardEvent.Set();
                    }
                }
                else
                {
                    message = "Notecard item creation failed";
                    notecardEvent.Set();
                }
            }
                                               );

            notecardEvent.WaitOne(NOTECARD_CREATE_TIMEOUT, false);

            if (finalUploadSuccess)
            {
                Logger.Log("Notecard successfully created, ItemID " + notecardItemID + " AssetID " + notecardAssetID, Helpers.LogLevel.Info);
                return(DownloadNotecard(notecardItemID, notecardAssetID));
            }
            else
            {
                return("Notecard creation failed: " + message);
            }
        }