Exemplo n.º 1
0
        public void AllSubfolderWearables(InventoryNode root, ref List<InventoryItem> WearableItems)
        {
            foreach (var n in root.Nodes.Values)
            {
                if (!n.Data.Name.StartsWith("."))
                {
                    if (n.Data is InventoryFolder)
                    {
                        AllSubfolderWearables(n, ref WearableItems);
                    }
                    else
                    {
                        WearableItems.Add((InventoryItem)n.Data);
                    }
                }
            }

        }
Exemplo n.º 2
0
        public static InventoryNode FindNodeMyName(InventoryNode root, string name)
        {
            if (root.Data.Name == name)
            {
                return(root);
            }

            foreach (var node in root.Nodes.Values)
            {
                var ret = FindNodeMyName(node, name);
                if (ret != null)
                {
                    return(ret);
                }
            }

            return(null);
        }
Exemplo n.º 3
0
        /// <summary>
        ///     Gets items descending from a root node.
        /// </summary>
        /// <param name="root">the node to search from</param>
        /// <param name="items">a reference to a list where the items will be stored</param>
        public static IEnumerable <InventoryItem> GetInventoryItems(this InventoryNode root)
        {
            foreach (var node in root.Nodes.Values.Where(n => !n.Data.Name.StartsWith(RLV_CONSTANTS.DOT_MARKER)))
            {
                switch (node.Data is InventoryFolder)
                {
                case true:
                    foreach (var item in GetInventoryItems(node))
                    {
                        yield return(item);
                    }
                    break;

                default:
                    yield return(node.Data as InventoryItem);

                    break;
                }
            }
        }
        private void TraverseAndQueueNodes(InventoryNode start)
        {
            bool has_items = false;

            foreach (InventoryNode node in start.Nodes.Values)
            {
                if (node.Data is InventoryItem)
                {
                    has_items = true;
                    break;
                }
            }

            if (!has_items || start.NeedsUpdate)
            {
                lock (QueuedFolders)
                {
                    lock (FolderFetchRetries)
                    {
                        int retries = 0;
                        FolderFetchRetries.TryGetValue(start.Data.UUID, out retries);
                        if (retries < 3)
                        {
                            if (!QueuedFolders.Contains(start.Data.UUID))
                            {
                                QueuedFolders.Add(start.Data.UUID);
                            }
                        }
                        FolderFetchRetries[start.Data.UUID] = retries + 1;
                    }
                }
            }

            foreach (InventoryBase item in Inventory.GetContents((InventoryFolder)start.Data))
            {
                if (item is InventoryFolder)
                {
                    TraverseAndQueueNodes(Inventory.GetNodeFor(item.UUID));
                }
            }
        }
Exemplo n.º 5
0
        protected void FindFoldersKeywordsInternal(InventoryNode currentNode, string[] keywords, List <string> currentPathParts, ref List <InventoryNode> matchingNodes)
        {
            if (currentNode.Data is InventoryFolder &&
                !currentNode.Data.Name.StartsWith(".") &&
                !currentNode.Data.Name.StartsWith("~") &&
                keywords.All(currentPathParts.Contains))
            {
                matchingNodes.Add(currentNode);
            }

            foreach (var node in currentNode.Nodes.Values)
            {
                if (!(node.Data is InventoryFolder))
                {
                    continue;
                }
                currentPathParts.Add(node.Data.Name.ToLower());
                FindFoldersKeywordsInternal(node, keywords, currentPathParts, ref matchingNodes);
                currentPathParts.RemoveAt(currentPathParts.Count - 1);
            }
        }
Exemplo n.º 6
0
        public InventoryNode FindFolder(string folder, InventoryNode start)
        {
            if (start.Data.Name == folder)
            {
                return(start);
            }

            foreach (var node in start.Nodes.Values)
            {
                if (node.Data is InventoryFolder)
                {
                    var n = FindFolder(folder, node);
                    if (n != null)
                    {
                        return(n);
                    }
                }
            }

            return(null);
        }
Exemplo n.º 7
0
        protected InventoryNode FindFolderInternal(InventoryNode currentNode, string currentPath, string desiredPath)
        {
            if (desiredPath.ToLower() == currentPath.ToLower())
            {
                return(currentNode);
            }
            foreach (var n in currentNode.Nodes.Values)
            {
                if (n.Data.Name.StartsWith("."))
                {
                    continue;
                }

                var res = FindFolderInternal(n, (currentPath == "/" ? currentPath : currentPath + "/") + n.Data.Name.ToLower(), desiredPath);
                if (res != null)
                {
                    return(res);
                }
            }
            return(null);
        }
Exemplo n.º 8
0
        internal VmInstanceNode(
            Instance instance,
            VmInstanceConnectionSettings settings,
            Action <VmInstanceConnectionSettings> saveSettings,
            ZoneNode parent)
            : base(
                settings.InstanceName,
                DisconnectedIconIndex,
                settings,
                changedSettings => saveSettings((VmInstanceConnectionSettings)changedSettings),
                parent)
        {
            this.InstanceId  = instance.Id.Value;
            this.Status      = instance.Status;
            this.Hostname    = instance.Hostname;
            this.MachineType = InventoryNode.ShortIdFromUrl(instance.MachineType);
            this.Tags        = instance.Tags != null && instance.Tags.Items != null
                ? string.Join(", ", instance.Tags.Items) : null;

            this.InternalIp = InternalIpFromInstance(instance);
            this.ExternalIp = ExternalIpFromInstance(instance);
        }
        private void RenderInventory(InventoryNode node, float interpolation)
        {
            var position   = node.PositionComponent.GetInterpolatedPosition(interpolation);
            var spriteSize = node.RenderComponent.View.Size;
            var inventory  = node.InventoryComponent;

            var drawXPosition = position.X + spriteSize.Width + 5;
            var drawYPosition = position.Y - spriteSize.Height;

            RenderInventoryIcon(
                drawXPosition,
                drawYPosition,
                Assets.LootInventoryIcon,
                inventory.Count(ItemTypes.Axe));

            RenderInventoryIcon(
                drawXPosition,
                drawYPosition + Assets.MaxIconHeight,
                Assets.LootInventoryIcon,
                inventory.Count(ItemTypes.Pickaxe));

            RenderInventoryIcon(
                drawXPosition,
                drawYPosition + Assets.MaxIconHeight * 2,
                Assets.StoneInventoryIcon,
                inventory.Count(ItemTypes.Stone));

            RenderInventoryIcon(
                drawXPosition,
                drawYPosition + Assets.MaxIconHeight * 3,
                Assets.TreeInventoryIcon,
                inventory.Count(ItemTypes.Wood));

            RenderInventoryIcon(
                drawXPosition,
                drawYPosition + Assets.MaxIconHeight * 4,
                Assets.FoodInventoryIcon,
                inventory.Count(ItemTypes.Food));
        }
Exemplo n.º 10
0
        public InventoryTreeModel(InventoryManager manager, Inventory inventory, InventoryNode root, InventoryType[] displayedTypes)
        {
            this.DisplayedTypes    = new Dictionary <InventoryType, object>();
            this.DownloadedFolders = new Dictionary <InventoryFolder, object>();
            this.Manager           = manager;
            this.InventoryRoot     = root;
            this.Inventory         = inventory;
            this.Inventory.OnInventoryObjectRemoved += new Inventory.InventoryObjectRemoved(this.Inventory_OnInventoryRemoved);
            inventory.OnInventoryObjectUpdated      += new Inventory.InventoryObjectUpdated(this.inventory_OnInventoryUpdated);
            this.Inventory.OnInventoryObjectAdded   += new Inventory.InventoryObjectAdded(this.Inventory_OnInventoryAdded);
            //this.NodeMap = new Dictionary<Node, InventoryNode>();
            this.ReverseMap = new Dictionary <InventoryNode, Node>();
            Node rootNode = new Node("My Inventory");

            rootNode.Tag = this.InventoryRoot.Data;
            //this.NodeMap.Add(rootNode, this.InventoryRoot);
            this.ReverseMap.Add(this.InventoryRoot, rootNode);
            this.DisplayedTypes = new Dictionary <InventoryType, object>(displayedTypes.Length);
            foreach (InventoryType type in displayedTypes)
            {
                this.DisplayedTypes[type] = null;
            }
        }
Exemplo n.º 11
0
        public IEnumerable GetChildren(TreePath treePath)
        {
            List <Node> children = new List <Node>();

            if (treePath.IsEmpty())
            {
                children.Add(this.ReverseMap[this.InventoryRoot]);
                return(children);
            }
            Node          lastNode = treePath.LastNode as Node;
            InventoryBase invBase  = lastNode.Tag as InventoryBase;
            InventoryNode invNode  = Inventory.GetNodeFor(invBase.UUID);//this.NodeMap[treePath.LastNode as Node];

            if (invNode.Data is InventoryFolder)
            {
                Console.WriteLine("Requesting {0}'s ({1}) contents...", invNode.Data.Name, invNode.Data.UUID);
                Manager.RequestFolderContents(invNode.Data.UUID, Inventory.Owner, true, true, InventorySortOrder.ByName);
                foreach (InventoryNode child in invNode.Nodes.Values)
                {
                    if ((child.Data is InventoryItem) && !this.DisplayedTypes.ContainsKey((child.Data as InventoryItem).InventoryType))
                    {
                        continue;
                    }
                    if (!this.ReverseMap.ContainsKey(child))
                    {
                        Node treeChild = new Node(child.Data.Name);
                        treeChild.Tag = child.Data;
                        this.ReverseMap.Add(child, treeChild);
                        //this.NodeMap.Add(treeChild, child);
                        Node parent = this.ReverseMap[child.Parent];
                        parent.Nodes.Add(treeChild);
                    }
                    children.Add(this.ReverseMap[child]);
                }
            }
            return(children);
        }
        public override bool Excecute(Automaton am, GridClient client, bool force)
        {
            if (!client.Network.Connected)
            {
                result.message = "Not Connected to grid"; return(true);
            }
            string res = string.Empty;

            if (path == null || path.Length < 1)
            {
                path = "";
            }
            if (filter == null || filter.Length < 1)
            {
                filter = "";
            }
            path = path.Trim().Trim('/');
            InventoryNode folder = FindFolder(client, path);

            if (folder != null)
            {
                foreach (var f in folder.Nodes.Values)
                {
                    if (f.Data is InventoryFolder && !f.Data.Name.StartsWith("."))
                    {
                        res += f.Data.Name + ",";
                    }
                }
                result.success = true;
                result.data    = res.TrimEnd(',');
            }
            else
            {
                result.message = "Path Doesn't Exist";
            }
            return(true);
        }
        public override bool Excecute(Automaton am, GridClient client, bool force)
        {
            if (!client.Network.Connected)
            {
                result.message = "Not Connected to grid"; return(true);
            }
            string res = string.Empty;

            if (path == null || path.Length < 1)
            {
                path = "";
            }
            if (filter == null || filter.Length < 1)
            {
                filter = "";
            }
            InventoryNode folder = FindFolder(client, path);

            client.Inventory.RequestFolderContents(folder.Data.UUID, folder.Data.OwnerID, true, true, InventorySortOrder.SystemFoldersToTop & InventorySortOrder.ByName);
            if (folder != null)
            {
                foreach (var f in folder.Nodes.Values)
                {
                    if (/*!(f.Data is InventoryFolder) && */ !f.Data.Name.StartsWith("."))
                    {
                        res += f.Data.Name + ",";
                    }
                }
                result.success = true;
                result.data    = res.TrimEnd(',');
            }
            else
            {
                result.message = "Path Doesn't Exist";
            }
            return(true);
        }
Exemplo n.º 14
0
        protected InventoryNode FindFolderKeywordsInternal(InventoryNode currentNode, string[] keywords)
        {
            bool mustSkip = false;

            foreach (string kw in keywords)
            {
                if (!mustSkip)
                {
                    if (!currentNode.Data.Name.ToLower().Contains(kw.ToLower()))
                    {
                        mustSkip = true;
                        break;
                    }
                }
            }

            if (!mustSkip)
            {
                return(currentNode);
            }

            foreach (var n in currentNode.Nodes.Values)
            {
                if (n.Data.Name.StartsWith("."))
                {
                    continue;
                }

                var res = FindFolderKeywordsInternal(n, keywords);
                if (res != null)
                {
                    return(res);
                }
            }
            return(null);
        }
Exemplo n.º 15
0
        /// <summary>
        /// BackupFolder - recurse through the inventory nodes sending scripts and notecards to the transfer queue
        /// </summary>
        /// <param name="folder">The current leaf in the inventory tree</param>
        /// <param name="sPathSoFar">path so far, in the form @"c:\here" -- this needs to be "clean" for the current filesystem</param>
        private void BackupFolder(InventoryNode folder, string sPathSoFar)
        {
            StringBuilder sbRequests = new StringBuilder();

            // FIXME:
            //Client.Inventory.RequestFolderContents(folder.Data.UUID, Client.Self.AgentID, true, true, false,
            //    InventorySortOrder.ByName);

            // first scan this folder for text
            foreach (InventoryNode iNode in folder.Nodes.Values)
            {
                if (BackupWorker.CancellationPending)
                {
                    return;
                }
                if (iNode.Data is libsecondlife.InventoryItem)
                {
                    InventoryItem ii = iNode.Data as InventoryItem;
                    if (ii.AssetType == AssetType.LSLText || ii.AssetType == AssetType.Notecard)
                    {
                        // check permissions on scripts
                        if (ii.AssetType == AssetType.LSLText)
                        {
                            if ((ii.Permissions.OwnerMask & PermissionMask.Modify) == PermissionMask.None)
                            {
                                // skip this one
                                continue;
                            }
                        }

                        string sExtension = (ii.AssetType == AssetType.LSLText) ? ".lsl" : ".txt";
                        // make the output file
                        string sPath = sPathSoFar + @"\" + MakeValid(ii.Name.Trim()) + sExtension;

                        // create the new qdi
                        QueuedDownloadInfo qdi = new QueuedDownloadInfo(sPath, ii.AssetUUID, iNode.Data.UUID, LLUUID.Zero,
                                                                        Client.Self.AgentID, ii.AssetType);

                        // add it to the queue
                        lock (PendingDownloads)
                        {
                            TextItemsFound++;
                            PendingDownloads.Enqueue(qdi);
                        }
                    }
                }
            }

            // now run any subfolders
            foreach (InventoryNode i in folder.Nodes.Values)
            {
                if (BackupWorker.CancellationPending)
                {
                    return;
                }
                else if (i.Data is libsecondlife.InventoryFolder)
                {
                    BackupFolder(i, sPathSoFar + @"\" + MakeValid(i.Data.Name.Trim()));
                }
            }
        }
Exemplo n.º 16
0
 // Methods
 public InventoryTreeModel(InventoryManager manager, Inventory inventory, InventoryNode root)
     : this(manager, inventory, root, (InventoryType[])Enum.GetValues(typeof(InventoryType)))
 {
 }
Exemplo n.º 17
0
        // Methods
        public InventoryDirectorySelector(InventoryManager manager, Inventory inventory, InventoryNode root)
        {
            this.form.FormBorderStyle   = FormBorderStyle.FixedDialog;
            this.treeView               = new InventoryTreeView();
            this.treeView.Model         = new InventoryTreeModel(manager, inventory, root, new InventoryType[0]);
            this.treeView.SelectionMode = TreeSelectionMode.Single;
            this.form.Controls.Add(this.treeView);
            Button ok = new Button();

            ok.Text = "Select";
            this.form.AcceptButton = ok;
            this.form.Controls.Add(ok);
            Button cancel = new Button();

            cancel.Text            = "Cancel";
            this.form.CancelButton = cancel;
            this.form.Controls.Add(cancel);
        }
Exemplo n.º 18
0
        public bool TryProcessCMD(ChatEventArgs e)
        {
            if (!Enabled || !e.Message.StartsWith("@"))
            {
                return(false);
            }

            foreach (string cmd in e.Message.Substring(1).Split(','))
            {
                RLVRule rule = new RLVRule(e);

                switch (rule.Behaviour)
                {
                case "version":
                    int chan = 0;
                    if (int.TryParse(rule.Param, out chan) && chan > 0)
                    {
                        Respond(chan, "RestrainedLife viewer v1.23 (SteelCity Automaton - Alpha)");
                    }
                    break;

                case "versionnew":
                    chan = 0;
                    if (int.TryParse(rule.Param, out chan) && chan > 0)
                    {
                        Respond(chan, "RestrainedLove viewer v1.23 (SteelCity Automaton - Alpha)");
                    }
                    break;


                case "versionnum":
                    if (int.TryParse(rule.Param, out chan) && chan > 0)
                    {
                        Respond(chan, "1230100");
                    }
                    break;

                case "getgroup":
                    if (int.TryParse(rule.Param, out chan) && chan > 0)
                    {
                        UUID gid = Client.Self.ActiveGroup;
                        if (Am.Groups().ContainsKey(gid))
                        {
                            Respond(chan, Am.Groups()[gid].Name);
                        }
                    }
                    break;

                case "setgroup":
                {
                    if (rule.Param == "force")
                    {
                        Am.set_group(rule.Option);
                    }
                }
                break;

                //TODO MORE

                case "getinv":
                    if (int.TryParse(rule.Param, out chan) && chan > 0)
                    {
                        string        res    = string.Empty;
                        InventoryNode folder = FindFolder(rule.Option);
                        if (folder != null)
                        {
                            foreach (var f in folder.Nodes.Values)
                            {
                                if (f.Data is InventoryFolder && !f.Data.Name.StartsWith("."))
                                {
                                    res += f.Data.Name + ",";
                                }
                            }
                        }

                        Respond(chan, res.TrimEnd(','));
                    }
                    break;

                default:
                    Console.WriteLine("Invalid rlv behaviour:");
                    Console.WriteLine(rule.ToString());
                    break;
                }
            }
            return(true);
        }
Exemplo n.º 19
0
    /// <summary>
    /// Updates the state of the InventoryNode and inventory data structure that
    /// is responsible for the InventoryObject. If the item was previously not added to inventory,
    /// it adds the item, and updates structure accordingly. If it was, it updates the 
    /// InventoryNode, changing the parent node if <code>item.parentUUID</code> does 
    /// not match <code>node.Parent.Data.UUID</code>.
    /// 
    /// You can not set the inventory root folder using this method
    /// </summary>
    /// <param name="item">The InventoryObject to store</param>
    public void UpdateNodeFor(InventoryBase item)
    {
        lock (Items)
        {
            InventoryNode itemParent = null;
            if (item.ParentUUID != UUID.Zero && !Items.TryGetValue(item.ParentUUID, out itemParent))
            {
                // OK, we have no data on the parent, let's create a fake one.
                InventoryFolder fakeParent = new InventoryFolder(item.ParentUUID);
                fakeParent.DescendentCount = 1; // Dear god, please forgive me.
                itemParent = new InventoryNode(fakeParent);
                Items[item.ParentUUID] = itemParent;
                // Unfortunately, this breaks the nice unified tree
                // while we're waiting for the parent's data to come in.
                // As soon as we get the parent, the tree repairs itself.
                Console.WriteLine("Attempting to update inventory child of " +
                    item.ParentUUID.ToString() + " when we have no local reference to that folder");

                if (true)
                {
                    // Fetch the parent
                    List<UUID> fetchreq = new List<UUID>(1);
                    fetchreq.Add(item.ParentUUID);
                    //Manager.FetchInventory(fetchreq); // we cant fetch folder data! :-O
                }
            }

            InventoryNode itemNode;
            if (Items.TryGetValue(item.UUID, out itemNode)) // We're updating.
            {
                InventoryNode oldParent = itemNode.Parent;
                // Handle parent change
                if (oldParent == null || itemParent == null || itemParent.Data.UUID != oldParent.Data.UUID)
                {
                    if (oldParent != null)
                    {
                        lock (oldParent.Nodes.SyncRoot)
                            oldParent.Nodes.Remove(item.UUID);
                    }
                    if (itemParent != null)
                    {
                        lock (itemParent.Nodes.SyncRoot)
                            itemParent.Nodes[item.UUID] = itemNode;
                    }
                }

                itemNode.Parent = itemParent;

                itemNode.Data = item;
            }
            else // We're adding.
            {
                itemNode = new InventoryNode(item, itemParent);
                Items.Add(item.UUID, itemNode);
            }
        }
    }
Exemplo n.º 20
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 { }
            }
        }
 public void TraverseNodes(InventoryNode start)
 {
     TraverseNodes(start, TimeSpan.FromSeconds(10));
 }
Exemplo n.º 22
0
        public bool TryProcessCMD(ChatEventArgs e)
        {
            if (!Enabled || !e.Message.StartsWith("@"))
            {
                return(false);
            }

            if (e.Message == "@clear")
            {
                Clear(e.SourceID);
                return(true);
            }

            foreach (var cmd in e.Message.Substring(1).Split(','))
            {
                var m = rlv_regex.Match(cmd);
                if (!m.Success)
                {
                    continue;
                }

                var rule = new RLVRule
                {
                    Behaviour  = m.Groups["behaviour"].ToString().ToLower(),
                    Option     = m.Groups["option"].ToString().ToLower(),
                    Param      = m.Groups["param"].ToString().ToLower(),
                    Sender     = e.SourceID,
                    SenderName = e.FromName
                };

                Logger.DebugLog(rule.ToString());

                if (rule.Param == "rem")
                {
                    rule.Param = "y";
                }
                if (rule.Param == "add")
                {
                    rule.Param = "n";
                }

                switch (rule.Param)
                {
                case "n":
                    lock (rules)
                    {
                        var existing = rules.Find(r =>
                                                  r.Behaviour == rule.Behaviour &&
                                                  r.Sender == rule.Sender &&
                                                  r.Option == rule.Option);

                        if (existing != null)
                        {
                            rules.Remove(existing);
                        }
                        rules.Add(rule);
                        OnRLVRuleChanged(new RLVEventArgs(rule));
                    }
                    continue;

                case "y":
                    lock (rules)
                    {
                        if (rule.Option == "")
                        {
                            rules.RemoveAll((RLVRule r) => r.Behaviour == rule.Behaviour && r.Sender == rule.Sender);
                        }
                        else
                        {
                            rules.RemoveAll((RLVRule r) => r.Behaviour == rule.Behaviour && r.Sender == rule.Sender && r.Option == rule.Option);
                        }
                    }

                    OnRLVRuleChanged(new RLVEventArgs(rule));
                    continue;
                }


                switch (rule.Behaviour)
                {
                case "version":
                    int chan = 0;
                    if (int.TryParse(rule.Param, out chan) && chan > 0)
                    {
                        Respond(chan, "RestrainedLife viewer v1.23 (" + Properties.Resources.RadegastTitle + " " + Assembly.GetExecutingAssembly().GetName().Version + ")");
                    }
                    break;

                case "versionnew":
                    chan = 0;
                    if (int.TryParse(rule.Param, out chan) && chan > 0)
                    {
                        Respond(chan, "RestrainedLove viewer v1.23 (" + Properties.Resources.RadegastTitle + " " + Assembly.GetExecutingAssembly().GetName().Version + ")");
                    }
                    break;


                case "versionnum":
                    if (int.TryParse(rule.Param, out chan) && chan > 0)
                    {
                        Respond(chan, "1230100");
                    }
                    break;

                case "getgroup":
                    if (int.TryParse(rule.Param, out chan) && chan > 0)
                    {
                        UUID gid = client.Self.ActiveGroup;
                        if (instance.Groups.ContainsKey(gid))
                        {
                            Respond(chan, instance.Groups[gid].Name);
                        }
                    }
                    break;

                case "setgroup":
                {
                    if (rule.Param == "force")
                    {
                        foreach (var g in instance.Groups.Values)
                        {
                            if (g.Name.ToLower() == rule.Option)
                            {
                                client.Groups.ActivateGroup(g.ID);
                            }
                        }
                    }
                }
                break;

                case "getsitid":
                    if (int.TryParse(rule.Param, out chan) && chan > 0)
                    {
                        Avatar me;
                        if (client.Network.CurrentSim.ObjectsAvatars.TryGetValue(client.Self.LocalID, out me))
                        {
                            if (me.ParentID != 0)
                            {
                                Primitive seat;
                                if (client.Network.CurrentSim.ObjectsPrimitives.TryGetValue(me.ParentID, out seat))
                                {
                                    Respond(chan, seat.ID.ToString());
                                    break;
                                }
                            }
                        }
                        Respond(chan, UUID.Zero.ToString());
                    }
                    break;

                case "getstatusall":
                case "getstatus":
                    if (int.TryParse(rule.Param, out chan) && chan > 0)
                    {
                        string sep    = "/";
                        string filter = "";

                        if (!string.IsNullOrEmpty(rule.Option))
                        {
                            var parts = rule.Option.Split(';');
                            if (parts.Length > 1 && parts[1].Length > 0)
                            {
                                sep = parts[1].Substring(0, 1);
                            }
                            if (parts.Length > 0 && parts[0].Length > 0)
                            {
                                filter = parts[0].ToLower();
                            }
                        }

                        lock (rules)
                        {
                            string res = "";
                            rules
                            .FindAll(r => (rule.Behaviour == "getstatusall" || r.Sender == rule.Sender) && r.Behaviour.Contains(filter))
                            .ForEach(objRule =>
                            {
                                res += sep + objRule.Behaviour;
                                if (!string.IsNullOrEmpty(objRule.Option))
                                {
                                    res += ":" + objRule.Option;
                                }
                            });
                            Respond(chan, res);
                        }
                    }
                    break;

                case "sit":
                    UUID sitTarget = UUID.Zero;

                    if (rule.Param == "force" && UUID.TryParse(rule.Option, out sitTarget) && sitTarget != UUID.Zero)
                    {
                        instance.State.SetSitting(true, sitTarget);
                    }
                    break;

                case "unsit":
                    if (rule.Param == "force")
                    {
                        instance.State.SetSitting(false, UUID.Zero);
                    }
                    break;

                case "setrot":
                    double rot = 0.0;

                    if (rule.Param == "force" && double.TryParse(rule.Option, System.Globalization.NumberStyles.Float, Utils.EnUsCulture, out rot))
                    {
                        client.Self.Movement.UpdateFromHeading(Math.PI / 2d - rot, true);
                    }
                    break;

                case "tpto":
                    var coord = rule.Option.Split('/');

                    try
                    {
                        float gx = float.Parse(coord[0], Utils.EnUsCulture);
                        float gy = float.Parse(coord[1], Utils.EnUsCulture);
                        float z = float.Parse(coord[2], Utils.EnUsCulture);
                        float x = 0, y = 0;

                        instance.TabConsole.DisplayNotificationInChat("Starting teleport...");
                        ulong h = Helpers.GlobalPosToRegionHandle(gx, gy, out x, out y);
                        client.Self.RequestTeleport(h, new Vector3(x, y, z));
                    }
                    catch (Exception) { }

                    break;

                    #region #RLV folder and outfit manipulation
                case "getoutfit":
                    if (int.TryParse(rule.Param, out chan) && chan > 0)
                    {
                        var    wearables = client.Appearance.GetWearables();
                        string res       = "";

                        // Do we have a specific wearable to check, ie @getoutfit:socks=99
                        if (!string.IsNullOrEmpty(rule.Option))
                        {
                            res = wearables.ContainsKey(WearableFromString(rule.Option)) ? "1" : "0";
                        }
                        else
                        {
                            foreach (var t in RLVWearables)
                            {
                                if (wearables.ContainsKey(t.Type))
                                {
                                    res += "1";
                                }
                                else
                                {
                                    res += "0";
                                }
                            }
                        }
                        Respond(chan, res);
                    }
                    break;

                case "getattach":
                    if (int.TryParse(rule.Param, out chan) && chan > 0)
                    {
                        string res         = "";
                        var    attachments = client.Network.CurrentSim.ObjectsPrimitives.FindAll(p => p.ParentID == client.Self.LocalID);
                        if (attachments.Count > 0)
                        {
                            var myPoints = new List <AttachmentPoint>(attachments.Count);
                            foreach (var p in attachments)
                            {
                                if (!myPoints.Contains(p.PrimData.AttachmentPoint))
                                {
                                    myPoints.Add(p.PrimData.AttachmentPoint);
                                }
                            }

                            // Do we want to check one single attachment
                            if (!string.IsNullOrEmpty(rule.Option))
                            {
                                res = myPoints.Contains(AttachmentPointFromString(rule.Option)) ? "1" : "0";
                            }
                            else
                            {
                                foreach (var a in RLVAttachments)
                                {
                                    if (myPoints.Contains(a.Point))
                                    {
                                        res += "1";
                                    }
                                    else
                                    {
                                        res += "0";
                                    }
                                }
                            }
                        }
                        Respond(chan, res);
                    }
                    break;

                case "remattach":
                case "detach":
                    if (rule.Param == "force")
                    {
                        if (!string.IsNullOrEmpty(rule.Option))
                        {
                            var point = RLVAttachments.Find(a => a.Name == rule.Option);
                            if (point.Name == rule.Option)
                            {
                                var attachment = client.Network.CurrentSim.ObjectsPrimitives.Find(p => p.ParentID == client.Self.LocalID && p.PrimData.AttachmentPoint == point.Point);
                                if (attachment != null && client.Inventory.Store.Items.ContainsKey(CurrentOutfitFolder.GetAttachmentItem(attachment)))
                                {
                                    instance.COF.Detach((InventoryItem)client.Inventory.Store.Items[CurrentOutfitFolder.GetAttachmentItem(attachment)].Data);
                                }
                            }
                            else
                            {
                                InventoryNode folder = FindFolder(rule.Option);
                                if (folder != null)
                                {
                                    var outfit = (from item in folder.Nodes.Values where CurrentOutfitFolder.CanBeWorn(item.Data) select(InventoryItem) (item.Data)).ToList();
                                    instance.COF.RemoveFromOutfit(outfit);
                                }
                            }
                        }
                        else
                        {
                            client.Network.CurrentSim.ObjectsPrimitives.FindAll(p => p.ParentID == client.Self.LocalID).ForEach(attachment =>
                            {
                                if (client.Inventory.Store.Items.ContainsKey(CurrentOutfitFolder.GetAttachmentItem(attachment)))
                                {
                                    instance.COF.Detach((InventoryItem)client.Inventory.Store.Items[CurrentOutfitFolder.GetAttachmentItem(attachment)].Data);
                                }
                            });
                        }
                    }
                    break;

                case "remoutfit":
                    if (rule.Param == "force")
                    {
                        if (!string.IsNullOrEmpty(rule.Option))
                        {
                            var w = RLVWearables.Find(a => a.Name == rule.Option);
                            if (w.Name == rule.Option)
                            {
                                var items = instance.COF.GetWornAt(w.Type);
                                instance.COF.RemoveFromOutfit(items);
                            }
                        }
                    }
                    break;

                case "attach":
                case "attachoverorreplace":
                case "attachover":
                case "attachall":
                case "attachallover":
                    if (rule.Param == "force")
                    {
                        if (!string.IsNullOrEmpty(rule.Option))
                        {
                            InventoryNode folder = FindFolder(rule.Option);
                            if (folder != null)
                            {
                                List <InventoryItem> outfit = new List <InventoryItem>();
                                if (rule.Behaviour == "attachall" || rule.Behaviour == "attachallover")
                                {
                                    GetAllItems(folder, true, ref outfit);
                                }
                                else
                                {
                                    GetAllItems(folder, false, ref outfit);
                                }

                                if (rule.Behaviour == "attachover" || rule.Behaviour == "attachallover")
                                {
                                    instance.COF.AddToOutfit(outfit, false);
                                }
                                else
                                {
                                    instance.COF.AddToOutfit(outfit, true);
                                }
                            }
                        }
                    }
                    break;

                case "getinv":
                    if (int.TryParse(rule.Param, out chan) && chan > 0)
                    {
                        string        res    = string.Empty;
                        InventoryNode folder = FindFolder(rule.Option);
                        if (folder != null)
                        {
                            res = folder.Nodes.Values.Where(
                                f => f.Data is InventoryFolder && !f.Data.Name.StartsWith(".")).Aggregate(
                                res, (current, f) => current + (f.Data.Name + ","));
                        }

                        Respond(chan, res.TrimEnd(','));
                    }
                    break;

                case "getinvworn":
                    if (int.TryParse(rule.Param, out chan) && chan > 0)
                    {
                        string        res  = string.Empty;
                        InventoryNode root = FindFolder(rule.Option);
                        if (root != null)
                        {
                            res += "|" + GetWornIndicator(root) + ",";
                            res  = root.Nodes.Values.Where(
                                n => n.Data is InventoryFolder && !n.Data.Name.StartsWith(".")).Aggregate(
                                res, (current, n) => current + (n.Data.Name + "|" + GetWornIndicator(n) + ","));
                        }

                        Respond(chan, res.TrimEnd(','));
                    }
                    break;

                case "findfolder":
                case "findfolders":
                    if (int.TryParse(rule.Param, out chan) && chan > 0)
                    {
                        StringBuilder response = new StringBuilder();

                        string[] keywordsArray = rule.Option.Split(new string[] { "&&" }, StringSplitOptions.None);
                        if (keywordsArray.Any())
                        {
                            List <InventoryNode> matching_nodes = FindFoldersKeyword(keywordsArray);
                            if (matching_nodes.Any())
                            {
                                if (rule.Behaviour == "findfolder")
                                {
                                    InventoryNode bestCandidate           = null;
                                    int           bestCandidateSlashCount = -1;
                                    foreach (var match in matching_nodes)
                                    {
                                        string fullPath   = FindFullInventoryPath(match, "");
                                        int    numSlashes = fullPath.Count(ch => ch == '/');
                                        if (bestCandidate == null || numSlashes > bestCandidateSlashCount)
                                        {
                                            bestCandidateSlashCount = numSlashes;
                                            bestCandidate           = match;
                                        }
                                    }

                                    string bestCandidatePath = bestCandidate.Data.Name;
                                    if (bestCandidatePath.Substring(0, 5).ToLower() == @"#rlv/")
                                    {
                                        bestCandidatePath = bestCandidatePath.Substring(5);
                                    }
                                    response.Append(bestCandidatePath);
                                }
                                else
                                {
                                    StringBuilder sb = new StringBuilder();
                                    foreach (var node in matching_nodes)
                                    {
                                        string fullPath = FindFullInventoryPath(node, "");
                                        if (fullPath.Length > 4 && fullPath.Substring(0, 5).ToLower() == @"#rlv/")
                                        {
                                            fullPath = fullPath.Substring(5);
                                        }
                                        response.Append(fullPath + ",");
                                    }
                                }
                            }
                        }

                        Respond(chan, response.ToString().TrimEnd(','));
                    }
                    break;

                    #endregion #RLV folder and outfit manipulation
                }
            }

            return(true);
        }
 public void TraverseNodes(InventoryNode start, TimeSpan maxTime)
 {
     TraverseNodesUnsorted(start, maxTime);
     start.Sort();
 }