Beispiel #1
0
        private void AssignTagToItem(CollectionFolder FileItem, string TagName)
        {
            if ((FileItem != null))
            {
                if (FileItem.File != null)
                {
                    // Назначить тэг файлу
                    if (Engine.Get().AssignTag(FileItem.File.FullName, TagName))
                    {
                        // Обновить список тэгов для файла
                        FileItem.AssignTagsList(Engine.Get().GetFileTags(FileItem.File.FullName));
                        UpdateCollectionTree();
                    }
                }
                else
                {
                    // Назначить тэг директории
                    foreach (var CurrFile in FileItem.GetFileItemsList())
                    {
                        Engine.Get().AssignTag(CurrFile.FullName, TagName);
                        CurrFile.AssignTagsList(Engine.Get().GetFileTags(CurrFile.FullName));
                    }

                    UpdateCollectionTree();
                }
            }
        }
Beispiel #2
0
        private void views_Drop(object sender, DragEventArgs e)
        {
            TreeViewItem SenderItem = sender as TreeViewItem;

            if (SenderItem != null)
            {
                // DROP "снаружи"
                if (e.Data.GetDataPresent(DataFormats.FileDrop))
                {
                    string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
                    AddFilesToColelction(files);
                }
                // DROP из списка тэгов
                else
                {
                    string           DroppedText = (string)e.Data.GetData(DataFormats.Text);
                    CollectionFolder FileItem    = SenderItem.DataContext as CollectionFolder;
                    AssignTagToItem(FileItem, DroppedText);

                    // обойти все выделенные файлы
                    foreach (var SelectedItem in selectedItems)
                    {
                        if (SelectedItem == FileItem)
                        {
                            continue;
                        }

                        AssignTagToItem(SelectedItem, DroppedText);
                    }
                }
            }
        }
Beispiel #3
0
        public MainWindow()
        {
            this.Closing += MainWindow_Closing;

            string SelectedCollectionName = AskCollectionName();

            // Если пользователь не выбрал коллекцию, выход
            if (SelectedCollectionName == null)
            {
                this.Close();
                return;
            }

            // Показать основное окно
            InitializeComponent();

            _CollectionFolder = new CollectionFolder();

            LoadDatabase(SelectedCollectionName);
            SetGropStyle();
            this.DataContext    = this;
            _Instance           = this;
            LoadDirectoryDialog = new LoadDirectory(LoadDirectoryToCollection);
            LoadDirectoryDialog.IsVisibleChanged += LoadDirectoryDialog_IsVisibleChanged;

            AllowMultiSelection(views);

            _AudioExtentions = Properties.Settings.Default.AudioFiles.Split(';');
            _VideoExtentions = Properties.Settings.Default.VideoFiles.Split(';');
            _ImageExtentions = Properties.Settings.Default.ImageFiles.Split(';');
            _DocsExtentions  = Properties.Settings.Default.Documents.Split(';');

            selectedItems = new List <CollectionFolder>();
        }
Beispiel #4
0
 private static void ProcessFolderItemTag(
     ref List <string> IntersectedTags,
     ref List <string> UnintersectedTags,
     CollectionFolder SelectedItem)
 {
     foreach (TaggedFile CurrentSubItem in SelectedItem.GetFileItemsList())
     {
         ProcessFileItemTag(
             ref IntersectedTags,
             ref UnintersectedTags,
             CurrentSubItem);
     }
 }
Beispiel #5
0
        /// <summary>
        /// Refreshes the collection folder children.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="collectionFolder">The collection folder.</param>
        /// <returns>Task.</returns>
        private async Task RefreshCollectionFolderChildren(RefreshItem request, CollectionFolder collectionFolder)
        {
            foreach (var child in collectionFolder.Children.ToList())
            {
                await child.RefreshMetadata(CancellationToken.None, forceRefresh : request.Forced).ConfigureAwait(false);

                var folder = child as Folder;

                if (folder != null)
                {
                    await folder.ValidateChildren(new Progress <double>(), CancellationToken.None, request.Recursive, request.Forced).ConfigureAwait(false);
                }
            }
        }
Beispiel #6
0
 private static void ProcessItemTags(
     ref List <string> IntersectedTags,
     ref List <string> UnintersectedTags,
     CollectionFolder SelectedItem)
 {
     if (SelectedItem.File != null)
     {
         ProcessFileItemTag(ref IntersectedTags, ref UnintersectedTags, SelectedItem.File);
     }
     else
     {
         ProcessFolderItemTag(ref IntersectedTags, ref UnintersectedTags, SelectedItem);
     }
 }
Beispiel #7
0
        /// <summary>
        /// Refreshes the collection folder children.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="collectionFolder">The collection folder.</param>
        /// <returns>Task.</returns>
        private async Task RefreshCollectionFolderChildren(RefreshItem request, CollectionFolder collectionFolder)
        {
            var options = GetRefreshOptions(request);

            foreach (var child in collectionFolder.Children.ToList())
            {
                await child.RefreshMetadata(options, CancellationToken.None).ConfigureAwait(false);

                if (child.IsFolder)
                {
                    var folder = (Folder)child;

                    await folder.ValidateChildren(new Progress <double>(), CancellationToken.None, options, request.Recursive).ConfigureAwait(false);
                }
            }
        }
Beispiel #8
0
        private bool UpdateFolderItem(CollectionFolder SelectedItem)
        {
            bool fHasChanges = false;

            foreach (var CurrSubitem in SelectedItem.Subfolders)
            {
                if (CurrSubitem.File == null)
                {
                    fHasChanges |= UpdateFolderItem(CurrSubitem);
                }
                else
                {
                    fHasChanges |= UpdateFileItem(CurrSubitem);
                }
            }
            return(fHasChanges);
        }
        public async Task <IActionResult> PutCollectionFolder(int id, CollectionFolder folder)
        {
            if (id != folder.Id)
            {
                return(BadRequest());
            }

            if (await _service.GetEntity(id) == null)
            {
                await _service.InsertEntity(folder);
            }
            else
            {
                await _service.UpdateEntity(folder);
            }

            return(NoContent());
        }
Beispiel #10
0
        private bool UpdateFileItem(CollectionFolder SelectedItem)
        {
            bool fHasChanges = false;

            foreach (StringObject CurrentTag in LabelsCollection)
            {
                if ((CurrentTag.TagChecked != null) && (CurrentTag.TagChecked.Value))
                {
                    if (Engine.Get().AssignTag(SelectedItem.File.FullName, CurrentTag.Value))
                    {
                        // Обновить список тэгов для файла
                        SelectedItem.AssignTagsList(Engine.Get().GetFileTags(SelectedItem.File.FullName));
                        fHasChanges = true;
                    }
                }
            }
            return(fHasChanges);
        }
Beispiel #11
0
        public void views_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            TreeViewItem SelectedListItem = sender as TreeViewItem;

            if (SelectedListItem != null)
            {
                CollectionFolder FileItem = SelectedListItem.DataContext as CollectionFolder;
                if ((FileItem != null) && (FileItem.File != null))
                {
                    if (File.Exists(FileItem.File.FullName))
                    {
                        Process.Start(FileItem.File.FullName);
                    }
                    else
                    {
                        MessageBox.Show("Файл не найден!", "Открытие файла", MessageBoxButton.OK, MessageBoxImage.Asterisk);
                    }
                }
            }
        }
Beispiel #12
0
        private void views_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                CollectionFolder FileItem = (sender as TreeViewItem).DataContext as CollectionFolder;

                DataObject DropObject = null;
                if (FileItem != null)
                {
                    if (FileItem.File != null)
                    {
                        DropObject = new DataObject(DataFormats.FileDrop, new string[1] {
                            FileItem.File.FullName
                        });
                    }
                    else
                    {
                        DropObject = new DataObject(DataFormats.FileDrop, FileItem.GetFilesList().ToArray());
                    }

                    DragDrop.DoDragDrop(sender as TreeViewItem, DropObject, DragDropEffects.All);
                }
            }
        }
Beispiel #13
0
 public long[] GetExcludedSubFolders(User user, CollectionFolder folder)
 {
     throw new NotImplementedException();
 }
        private bool IsEligibleForSpecialView(CollectionFolder view)
        {
            var types = new[] { CollectionType.Movies, CollectionType.TvShows, CollectionType.Games, CollectionType.Music };

            return(types.Contains(view.CollectionType ?? string.Empty, StringComparer.OrdinalIgnoreCase));
        }
Beispiel #15
0
        private async Task RefreshCollectionFolderChildren(MetadataRefreshOptions options, CollectionFolder collectionFolder)
        {
            foreach (var child in collectionFolder.Children.ToList())
            {
                await child.RefreshMetadata(options, CancellationToken.None).ConfigureAwait(false);

                if (child.IsFolder)
                {
                    var folder = (Folder)child;

                    await folder.ValidateChildren(new Progress <double>(), CancellationToken.None, options, true).ConfigureAwait(false);
                }
            }
        }
Beispiel #16
0
        public ActionResult RenameVirtualFolder(
            [FromQuery] string?name,
            [FromQuery] string?newName,
            [FromQuery] bool refreshLibrary = false)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentNullException(nameof(name));
            }

            if (string.IsNullOrWhiteSpace(newName))
            {
                throw new ArgumentNullException(nameof(newName));
            }

            var rootFolderPath = _appPaths.DefaultUserViewsPath;

            var currentPath = Path.Combine(rootFolderPath, name);
            var newPath     = Path.Combine(rootFolderPath, newName);

            if (!Directory.Exists(currentPath))
            {
                return(NotFound("The media collection does not exist."));
            }

            if (!string.Equals(currentPath, newPath, StringComparison.OrdinalIgnoreCase) && Directory.Exists(newPath))
            {
                return(Conflict($"The media library already exists at {newPath}."));
            }

            _libraryMonitor.Stop();

            try
            {
                // Changing capitalization. Handle windows case insensitivity
                if (string.Equals(currentPath, newPath, StringComparison.OrdinalIgnoreCase))
                {
                    var tempPath = Path.Combine(
                        rootFolderPath,
                        Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture));
                    Directory.Move(currentPath, tempPath);
                    currentPath = tempPath;
                }

                Directory.Move(currentPath, newPath);
            }
            finally
            {
                CollectionFolder.OnCollectionFolderChange();

                Task.Run(async() =>
                {
                    // No need to start if scanning the library because it will handle it
                    if (refreshLibrary)
                    {
                        await _libraryManager.ValidateMediaLibrary(new SimpleProgress <double>(), CancellationToken.None).ConfigureAwait(false);
                    }
                    else
                    {
                        // Need to add a delay here or directory watchers may still pick up the changes
                        // Have to block here to allow exceptions to bubble
                        await Task.Delay(1000).ConfigureAwait(false);
                        _libraryMonitor.Start();
                    }
                });
            }

            return(NoContent());
        }
        public async Task <ActionResult <CollectionFolder> > PostCollectionFolder(CollectionFolder folder)
        {
            await _service.InsertEntity(folder);

            return(CreatedAtAction("GetCollectionFolder", new { id = folder.Id }, folder));
        }
Beispiel #18
0
        /// <summary>
        /// Ensures the existence of the Category.
        /// If it doesn't exist it creates the Category, adds DisplayNames, adds identifiers and associates the Category with the parent Category.
        /// </summary>
        /// <param name="propositionCategory"></param>
        /// <param name="catalogId"></param>
        /// <param name="catalogName"></param>
        /// <param name="policy"></param>
        /// <param name="context"></param>
        /// <param name="associateWithCatalog"></param>
        /// <returns></returns>
        private async Task <List <Category> > EnsureCategory(CollectionFolder propositionCategory, string catalogId,
                                                             string catalogName, SyncForceClientPolicy policy, CommerceContext context,
                                                             bool associateWithCatalog = false)
        {
            var result = new List <Category>();

            var categoryName = propositionCategory.Values.FirstOrDefault(l => l.Language == policy.DefaultLanguage)
                               ?.Name;
            //Added sort index to category name to make sure sorting is done right, instead of done on alphabetical order.
            var categoryId =
                $"{CommerceEntity.IdPrefix<Category>()}{catalogName}-{propositionCategory.SortIndex.ToString().PadLeft(3, '0') + propositionCategory.Id + categoryName.ProposeValidId()}";
            Category category = null;

            //Get or create category
            if (await _doesEntityExistPipeline.Run(new FindEntityArgument(typeof(Category), categoryId),
                                                   context.PipelineContextOptions))
            {
                category = await _getCategoryPipeline.Run(new GetCategoryArgument(categoryId),
                                                          context.PipelineContextOptions);
            }
            else
            {
                var createResult = await _createCategoryPipeline.Run(
                    new CreateCategoryArgument(catalogId,
                                               propositionCategory.SortIndex.ToString().PadLeft(3, '0') + propositionCategory.Id +
                                               categoryName.ProposeValidId(), categoryName, ""), context.PipelineContextOptions);

                category = createResult?.Categories?.FirstOrDefault(c => c.Id == categoryId);
            }

            if (category != null)
            {
                //Localize properties
                var localizationEntityId = LocalizationEntity.GetIdBasedOnEntityId(category.Id);
                var localizationEntity   = await _findEntityPipeline.Run(new FindEntityArgument(typeof(LocalizationEntity), localizationEntityId),
                                                                         context.PipelineContextOptions) as LocalizationEntity;

                if (localizationEntity != null)
                {
                    var displayNames = propositionCategory.Values.Select(p => new Parameter(p.Language, p.Name)).ToList();
                    localizationEntity.AddOrUpdatePropertyValue("DisplayName", displayNames);

                    var descriptions = propositionCategory.CategoryContent.Values.Select(p => new Parameter(p.Language, p.Name)).ToList();
                    localizationEntity.AddOrUpdatePropertyValue("Description", descriptions);

                    await _persistEntityPipeline.Run(new PersistEntityArgument(localizationEntity),
                                                     context.PipelineContextOptions);
                }

                //Add identifiers
                var identifiersComponent = category.GetComponent <IdentifiersComponent>();
                if (!identifiersComponent.CustomId.Any(i => i.Key.Equals(policy.CustomIdentifierKey)))
                {
                    identifiersComponent.CustomId.Add(
                        new Sitecore.Commerce.Plugin.Catalogs.SyncForce.Models.CustomIdentifier(
                            policy.CustomIdentifierKey, propositionCategory.Id.ToString()));
                }
                category.SetComponent(identifiersComponent);
                category = (await _persistEntityPipeline.Run(new PersistEntityArgument(category),
                                                             context.PipelineContextOptions))?.Entity as Category ?? category;

                //Add custom properties
                var categoryComponent = category.GetComponent <SyncForceCategoryComponent>();
                categoryComponent.Sortorder = propositionCategory.SortIndex;
                category.SetComponent(categoryComponent);
                category = (await _persistEntityPipeline.Run(new PersistEntityArgument(category), context.PipelineContextOptions))?.Entity as Category ?? category;

                //Create sub-categories
                if (propositionCategory?.ProductPropositionCategories?.Any() ?? false)
                {
                    foreach (var subCategory in propositionCategory.ProductPropositionCategories)
                    {
                        var s = await EnsureCategory(subCategory, catalogId, catalogName, policy, context);

                        result.AddRange(s);

                        foreach (var createdSubCategory in s)
                        {
                            var persistedSubCategory =
                                (await _persistEntityPipeline.Run(new PersistEntityArgument(createdSubCategory),
                                                                  context.PipelineContextOptions))?.Entity;
                            var associateResult = await _associateCategoryToParentPipeline.Run(
                                new CatalogReferenceArgument(catalogId, category.Id,
                                                             persistedSubCategory?.Id ?? createdSubCategory.Id),
                                context.PipelineContextOptions);

                            category = associateResult?.Categories?.FirstOrDefault(c => c.Id == category.Id) ??
                                       category;
                        }
                    }
                }

                //Associate with catalog if top level category
                if (associateWithCatalog)
                {
                    var associateResult = await _associateCategoryToParentPipeline.Run(
                        new CatalogReferenceArgument(catalogId, catalogId, category.Id),
                        context.PipelineContextOptions);

                    category = associateResult?.Categories
                               ?.FirstOrDefault(c => c.Id == category.Id) ?? category;
                }

                result.Add(category);
            }

            return(result);
        }
        /// <summary>
        /// Posts the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        public void Post(RenameVirtualFolder request)
        {
            if (string.IsNullOrWhiteSpace(request.Name))
            {
                throw new ArgumentNullException(nameof(request));
            }

            if (string.IsNullOrWhiteSpace(request.NewName))
            {
                throw new ArgumentNullException(nameof(request));
            }

            var rootFolderPath = _appPaths.DefaultUserViewsPath;

            var currentPath = Path.Combine(rootFolderPath, request.Name);
            var newPath     = Path.Combine(rootFolderPath, request.NewName);

            if (!Directory.Exists(currentPath))
            {
                throw new FileNotFoundException("The media collection does not exist");
            }

            if (!string.Equals(currentPath, newPath, StringComparison.OrdinalIgnoreCase) && Directory.Exists(newPath))
            {
                throw new ArgumentException("Media library already exists at " + newPath + ".");
            }

            _libraryMonitor.Stop();

            try
            {
                // Changing capitalization. Handle windows case insensitivity
                if (string.Equals(currentPath, newPath, StringComparison.OrdinalIgnoreCase))
                {
                    var tempPath = Path.Combine(rootFolderPath, Guid.NewGuid().ToString("N"));
                    Directory.Move(currentPath, tempPath);
                    currentPath = tempPath;
                }

                Directory.Move(currentPath, newPath);
            }
            finally
            {
                CollectionFolder.OnCollectionFolderChange();

                Task.Run(() =>
                {
                    // No need to start if scanning the library because it will handle it
                    if (request.RefreshLibrary)
                    {
                        _libraryManager.ValidateMediaLibrary(new SimpleProgress <double>(), CancellationToken.None);
                    }
                    else
                    {
                        // Need to add a delay here or directory watchers may still pick up the changes
                        var task = Task.Delay(1000);
                        // Have to block here to allow exceptions to bubble
                        Task.WaitAll(task);

                        _libraryMonitor.Start();
                    }
                });
            }
        }
Beispiel #20
0
        private async Task RefreshCollectionFolderChildren(MetadataRefreshOptions options, CollectionFolder collectionFolder, CancellationToken cancellationToken)
        {
            foreach (var child in collectionFolder.GetPhysicalFolders())
            {
                await child.RefreshMetadata(options, cancellationToken).ConfigureAwait(false);

                await child.ValidateChildren(new SimpleProgress <double>(), cancellationToken, options).ConfigureAwait(false);
            }
        }
Beispiel #21
0
        public static void AllowMultiSelection(TreeView treeView)
        {
            if (IsSelectionChangeActiveProperty == null)
            {
                return;
            }


            treeView.SelectedItemChanged += (a, b) =>
            {
                var treeViewItem = treeView.SelectedItem as CollectionFolder;
                if (treeViewItem == null)
                {
                    return;
                }

                // allow multiple selection
                // when control key is pressed
                if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
                {
                    // suppress selection change notification
                    // select all selected items
                    // then restore selection change notifications
                    var isSelectionChangeActive =
                        IsSelectionChangeActiveProperty.GetValue(treeView, null);

                    IsSelectionChangeActiveProperty.SetValue(treeView, true, null);
                    selectedItems.ForEach(item => item.IsSelected = true);

                    IsSelectionChangeActiveProperty.SetValue
                    (
                        treeView,
                        isSelectionChangeActive,
                        null
                    );
                }
                else if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
                {
                    if (PrevSelectedItem == treeViewItem)
                    {
                        treeViewItem.IsSelected = !treeViewItem.IsSelected;
                    }

                    bool fSelect = false;
                    foreach (var item in treeView.Items)
                    {
                        if ((item == PrevSelectedItem) || (item == treeViewItem))
                        {
                            fSelect = !fSelect;
                        }

                        (item as CollectionFolder).IsSelected = fSelect;
                    }
                }
                // TODO сделать множественное выделение для shift
                else
                {
                    // deselect all selected items except the current one
                    selectedItems.ForEach(item => item.IsSelected = (item == treeViewItem));
                    selectedItems.Clear();
                }

                if (!selectedItems.Contains(treeViewItem))
                {
                    treeViewItem.IsSelected = true;
                    selectedItems.Add(treeViewItem);
                }
                else
                {
                    // deselect if already selected
                    treeViewItem.IsSelected = false;
                    selectedItems.Remove(treeViewItem);
                }

                PrevSelectedItem = treeViewItem;
            };
        }