protected RemoteFileSystemResourceAccessor(string nativeSystemId, ResourcePath nativeResourcePath, bool isFile,
     string resourcePathName, string resourceName, long size, DateTime lastChanged) :
         this(nativeSystemId, nativeResourcePath, isFile, resourcePathName, resourceName)
 {
   _lastChangedCache = lastChanged;
   _sizeCache = size;
 }
 internal static void SendImportMessage(MessageType messageType, ResourcePath path, ImportJobType importJobType)
 {
   SystemMessage msg = new SystemMessage(messageType);
   msg.MessageData[RESOURCE_PATH] = path;
   msg.MessageData[IMPORT_JOB_TYPE] = importJobType;
   ServiceRegistration.Get<IMessageBroker>().Send(CHANNEL, msg);
 }
 public ICollection<ResourcePathMetadata> GetChildDirectoriesData(ResourcePath path)
 {
   CpAction action = GetAction("GetChildDirectoriesData");
   IList<object> inParameters = new List<object> {path.Serialize()};
   IList<object> outParameters = action.InvokeAction(inParameters);
   return (ICollection<ResourcePathMetadata>) outParameters[0];
 }
 public string GetResourceDisplayName(ResourcePath path)
 {
   CpAction action = GetAction("GetResourceDisplayName");
   IList<object> inParameters = new List<object> {path.Serialize()};
   IList<object> outParameters = action.InvokeAction(inParameters);
   return (string) outParameters[0];
 }
Example #5
0
 /// <summary>
 /// Extension method which is added on <see cref="IEnumerable{Share}"/> to find that share in the given enumeration
 /// which best matches the given <paramref name="path"/>.
 /// </summary>
 /// <remarks>
 /// If there are shares where one share path contains the path of another share in the given <paramref name="shares"/> enumeration,
 /// the algorithm will always find the share whose path is as close to the given <paramref name="path"/>. If more than one share match best,
 /// the first best matching share is returned.
 /// </remarks>
 /// <param name="shares">Enumeration of shares to search through.</param>
 /// <param name="path">Path to find a share for.</param>
 /// <returns>Share which best matches the given <paramref name="path"/>, if one exists. Else, <c>null</c> will be returned.</returns>
 public static Share BestContainingPath(this IEnumerable<Share> shares, ResourcePath path)
 {
   if (path == null)
     return null;
   int bestMatchPathLength = int.MaxValue;
   Share bestMatchShare = null;
   foreach (Share share in shares)
   {
     ResourcePath currentSharePath = share.BaseResourcePath;
     if (!currentSharePath.IsSameOrParentOf(path))
       // The path is not located in the current share
       continue;
     if (bestMatchShare == null)
     {
       bestMatchShare = share;
       continue;
     }
     // We want to find a share which is as close as possible to the given path
     int currentSharePathLength = currentSharePath.Serialize().Length;
     if (bestMatchPathLength >= currentSharePathLength)
       continue;
     bestMatchShare = share;
     bestMatchPathLength = currentSharePathLength;
   }
   return bestMatchShare;
 }
    public const string CHOOSEN_PATH = "ChoosenPath"; // Type: ResourcePath

    public static void SendPathChoosenMessage(Guid dialogHandle, ResourcePath choosenPath)
    {
      SystemMessage msg = new SystemMessage(MessageType.PathChoosen);
      msg.MessageData[DIALOG_HANDLE] = dialogHandle;
      msg.MessageData[CHOOSEN_PATH] = choosenPath;
      ServiceRegistration.Get<IMessageBroker>().Send(CHANNEL, msg);
    }
 protected RemoteFileResourceAccessor(string nativeSystemId, ResourcePath nativeResourcePath,
     string resourcePathName, string resourceName, DateTime lastChanged, long size) :
     base(nativeSystemId, nativeResourcePath, true, resourcePathName, resourceName)
 {
   _lastChanged = lastChanged;
   _size = size;
 }
    /// <summary>
    /// Tries to find the resource path corresponding to the given media library <paramref name="viewSpecification"/>.
    /// </summary>
    /// <param name="viewSpecification">View specification to be examined.</param>
    /// <param name="path">Path corresponding to the given <paramref name="viewSpecification"/>, if it is a media library view specification (i.e. one of the
    /// view specifications which are created in any of the sub views of this view specification). Else, this parameter will return <c>null</c>.</param>
    /// <returns><c>true</c>, if the given <paramref name="viewSpecification"/> is one of the direct or indirect view specifications which are created as sub view specifications
    /// of this view specification.</returns>
    public static bool TryGetLocalBrowseViewPath(ViewSpecification viewSpecification, out ResourcePath path)
    {
      MediaLibraryBrowseViewSpecification mlbvs = viewSpecification as MediaLibraryBrowseViewSpecification;
      if (mlbvs != null)
      { // We're in some MediaLibrary browsing state
        IServerConnectionManager serverConnectionManager = ServiceRegistration.Get<IServerConnectionManager>();
        string localSystemId = ServiceRegistration.Get<ISystemResolver>().LocalSystemId;
        if (mlbvs.SystemId != localSystemId && mlbvs.SystemId != serverConnectionManager.HomeServerSystemId)
        { // If the currently browsed system is a different one, the path must be set to null
          path = null;
          return true;
        }
        // In a browsing state for the local system, we can return the base path from the view specification
        path = mlbvs.BasePath;
        return true;
      }

      BrowseMediaRootProxyViewSpecification bmrvs = viewSpecification as BrowseMediaRootProxyViewSpecification;
      SystemSharesViewSpecification ssvs = viewSpecification as SystemSharesViewSpecification;
      AllSystemsViewSpecification asvs = viewSpecification as AllSystemsViewSpecification;
      if (ssvs != null || asvs != null || bmrvs != null)
      { // If the current browsing state shows one of the root browse states, we can just set the path to null
        path = null;
        return true;
      }
      path = null;
      return false;
    }
    protected Stream _underlayingStream = null; // Lazy initialized

    protected RemoteResourceAccessorBase(string nativeSystemId, ResourcePath nativeResourcePath, bool isFile, string resourcePathName, string resourceName)
    {
      _nativeSystemId = nativeSystemId;
      _nativeResourcePath = nativeResourcePath;
      _isFile = isFile;
      _resourcePathName = resourcePathName;
      _resourceName = resourceName;
    }
 /// <summary>
 /// Creates a new <see cref="LocalDirectoryViewSpecification"/> instance.
 /// </summary>
 /// <param name="overrideName">Overridden name for the view. If not set, the resource name of the specified
 /// <paramref name="viewPath"/> will be used as <see cref="ViewDisplayName"/>.</param>
 /// <param name="viewPath">Path of a directory in a local filesystem provider.</param>
 /// <param name="necessaryMIATypeIds">Ids of the media item aspect types which should be extracted for all items and
 /// sub views of this view.</param>
 /// <param name="optionalMIATypeIds">Ids of the media item aspect types which may be extracted for items and
 /// sub views of this view.</param>
 public LocalDirectoryViewSpecification(string overrideName, ResourcePath viewPath,
     IEnumerable<Guid> necessaryMIATypeIds, IEnumerable<Guid> optionalMIATypeIds) :
     base(null, necessaryMIATypeIds, optionalMIATypeIds)
 {
   _overrideName = overrideName;
   _viewPath = viewPath;
   UpdateDisplayName();
 }
 public ImportJobInformation(ImportJobInformation other)
 {
   _jobType = other.JobType;
   _basePath = other.BasePath;
   _metadataExtractorIds = new HashSet<Guid>(other.MetadataExtractorIds);
   _includeSubDirectories = other.IncludeSubDirectories;
   _state = other.State;
 }
 public ImportJobInformation(ImportJobType jobType, ResourcePath basePath, IEnumerable<Guid> metadataExtractorIds, bool includeSubDirectories)
 {
   _jobType = jobType;
   _basePath = basePath;
   _metadataExtractorIds = new HashSet<Guid>(metadataExtractorIds);
   _includeSubDirectories = includeSubDirectories;
   _state = ImportJobState.None;
 }
 public MediaLibraryBrowseViewSpecification(string viewDisplayName, Guid directoryId,
     string systemId, ResourcePath basePath,
     IEnumerable<Guid> necessaryMIATypeIDs, IEnumerable<Guid> optionalMIATypeIDs) :
     base(viewDisplayName, necessaryMIATypeIDs, optionalMIATypeIDs)
 {
   _directoryId = directoryId;
   _systemId = systemId;
   _basePath = basePath;
 }
 /// <summary>
 /// Transforms a resource path denoting a local filesystem path to a DOS path.
 /// </summary>
 /// <param name="resourcePath">Resource path to transform.</param>
 /// <returns>Dos path to the given <paramref name="resourcePath"/> or <c>null</c>, if the given path is <c>null</c> or
 /// doesn't denote a path in the local filesystem provider.</returns>
 public static string ToDosPath(ResourcePath resourcePath)
 {
   if (resourcePath == null)
     return null;
   ProviderPathSegment lastSegment = resourcePath.LastPathSegment;
   if (lastSegment.ProviderId != LOCAL_FS_RESOURCE_PROVIDER_ID)
     return null;
   return ToDosPath(lastSegment.Path);
 }
Example #15
0
 public MediaItem LoadLocalItem(ResourcePath path,
     IEnumerable<Guid> necessaryRequestedMIATypeIDs, IEnumerable<Guid> optionalRequestedMIATypeIDs)
 {
   try
   {
     return _parent.LoadItem(_parent.LocalSystemId, path, necessaryRequestedMIATypeIDs, optionalRequestedMIATypeIDs);
   }
   catch (Exception)
   {
     throw new DisconnectedException();
   }
 }
    private DateTime _dateOfLastImport; // only valid for refresh imports

    #endregion

    #region Constructor

    public PendingImportResourceNewGen(ResourcePath parentDirectory, IFileSystemResourceAccessor resourceAccessor, String currentBlock, ImportJobController parentImportJobController, Guid? parentDirectoryId = null, Guid? mediaItemId = null)
    {
      _parentDirectoryId = parentDirectoryId;
      _mediaItemId = mediaItemId;
      _parentDirectoryResourcePathString = (parentDirectory == null) ? "" : parentDirectory.Serialize();
      _resourceAccessor = resourceAccessor;      
      _currentBlock = currentBlock;
      _parentImportJobController = parentImportJobController;
      _pendingImportResourceNumber = _parentImportJobController.GetNumberOfNextPendingImportResource();

      _isValid = (_resourceAccessor != null);

      _parentImportJobController.RegisterPendingImportResource(this);
    }
 public static bool ParseResourceURI(Uri resourceURI, out ResourcePath relativeResourcePath)
 {
   NameValueCollection query =  HttpUtility.ParseQueryString(resourceURI.Query);
   string resourcePathStr = query[RESOURCE_PATH_ARGUMENT_NAME];
   try
   {
     relativeResourcePath = ResourcePath.Deserialize(resourcePathStr);
     return true;
   }
   catch (ArgumentException)
   {
     relativeResourcePath = null;
     return false;
   }
 }
 public static bool ConnectFile(string nativeSystemId, ResourcePath nativeResourcePath, out IResourceAccessor result)
 {
   IRemoteResourceInformationService rris = ServiceRegistration.Get<IRemoteResourceInformationService>();
   result = null;
   bool isFileSystemResource;
   bool isFile;
   string resourcePathName;
   string resourceName;
   DateTime lastChanged;
   long size;
   if (!rris.GetResourceInformation(nativeSystemId, nativeResourcePath,
       out isFileSystemResource, out isFile, out resourcePathName, out resourceName, out lastChanged, out size) ||
           !isFile)
     return false;
   result = new RemoteFileResourceAccessor(nativeSystemId, nativeResourcePath, resourcePathName, resourceName, lastChanged, size);
   return true;
 }
 internal static bool TryExtractSystemAndPath(string providerPath, out string systemId, out ResourcePath nativeResourcePath)
 {
   systemId = null;
   nativeResourcePath = null;
   int sepIndex = providerPath.IndexOf(':');
   if (sepIndex < 1)
     return false;
   systemId = providerPath.Substring(0, sepIndex);
   try
   {
     nativeResourcePath = ResourcePath.Deserialize(providerPath.Substring(sepIndex + 1));
     return true;
   }
   catch (ArgumentException)
   {
     return false;
   }
 }
 /// <summary>
 /// Tries to find the resource path corresponding to the given local <paramref name="viewSpecification"/>.
 /// </summary>
 /// <param name="viewSpecification">View specification to be examined.</param>
 /// <param name="path">Path corresponding to the given <paramref name="viewSpecification"/>, if it is a local view specification (i.e. one of the
 /// view specifications which are created in any of the sub views of this view specification). Else, this parameter will return <c>null</c>.</param>
 /// <returns><c>true</c>, if the given <paramref name="viewSpecification"/> is one of the direct or indirect view specifications which are created as sub view specifications
 /// of this view specification.</returns>
 public static bool TryGetLocalBrowseViewPath(ViewSpecification viewSpecification, out ResourcePath path)
 {
   LocalMediaRootProxyViewSpecification lmrpvs = viewSpecification as LocalMediaRootProxyViewSpecification;
   LocalSharesViewSpecification lsvs = viewSpecification as LocalSharesViewSpecification;
   if (lmrpvs != null || lsvs != null)
   { // If the current browsing state shows one of the root states, the path must be set to null
     path = null;
     return true;
   }
   LocalDirectoryViewSpecification ldvs = viewSpecification as LocalDirectoryViewSpecification;
   if (ldvs != null)
   { // In a local browsing state, we can return the browsing path
     path = ldvs.ViewPath;
     return true;
   }
   path = null;
   return false;
 }
 /// <summary>
 /// Helper method which simulates a user navigation under this view specification to the given <paramref name="targetPath"/>
 /// under the given <paramref name="localShare"/>.
 /// </summary>
 /// <param name="localShare">Client or server share which is located at the local system.</param>
 /// <param name="targetPath">Resource path to navigate to. This path must be located under the given <paramref name="localShare"/>'s base path.</param>
 /// <param name="navigateToViewDlgt">Callback which will be called for each view specification to navigate to to do the actual navigation.</param>
 public void Navigate(Share localShare, ResourcePath targetPath, NavigateToViewDlgt navigateToViewDlgt)
 {
   NavigateToLocalRootView(localShare, navigateToViewDlgt);
   IResourceAccessor startRA;
   if (!localShare.BaseResourcePath.TryCreateLocalResourceAccessor(out startRA))
     return;
   IFileSystemResourceAccessor current = startRA as IFileSystemResourceAccessor;
   if (current == null)
   {
     // Wrong path resource, cannot navigate. Should not happen if the share is based on a filesystem resource,
     // but might happen if we have found a non-standard share.
     startRA.Dispose();
     return;
   }
   while (true)
   {
     ICollection<IFileSystemResourceAccessor> children = FileSystemResourceNavigator.GetChildDirectories(current, false);
     current.Dispose();
     current = null;
     if (children != null)
       foreach (IFileSystemResourceAccessor childDirectory in children)
         using (childDirectory)
         {
           if (childDirectory.CanonicalLocalResourcePath.IsSameOrParentOf(targetPath))
           {
             current = childDirectory;
             break;
           }
         }
     if (current == null)
       break;
     ViewSpecification newVS = NavigateCreateViewSpecification(localShare.SystemId, current);
     if (newVS == null)
     {
       current.Dispose();
       return;
     }
     navigateToViewDlgt(newVS);
   }
 }
 public void ImportLocation(ResourcePath path, IEnumerable<string> mediaCategories, ImportJobType importJobType)
 {
   CpAction action = GetAction("ImportLocation");
   string importJobTypeStr;
   switch (importJobType)
   {
     case ImportJobType.Import:
       importJobTypeStr = "Import";
       break;
     case ImportJobType.Refresh:
       importJobTypeStr = "Refresh";
       break;
     default:
       throw new NotImplementedException(string.Format("Import job type '{0}' is not implemented", importJobType));
   }
   IList<object> inParameters = new List<object>
       {
         path.Serialize(),
         StringUtils.Join(", ", mediaCategories),
         importJobTypeStr
       };
   action.InvokeAction(inParameters);
 }
Example #23
0
 protected override bool GetIsPathValid(ResourcePath path)
 {
   ResourcePath rp = path;
   if (rp == null)
     return false;
   IResourceAccessor ra;
   if (rp.TryCreateLocalResourceAccessor(out ra))
     using (ra)
       return true;
   return false;
 }
Example #24
0
        /// <summary>
        /// Tries to find the resource path corresponding to the given local <paramref name="viewSpecification"/>.
        /// </summary>
        /// <param name="viewSpecification">View specification to be examined.</param>
        /// <param name="path">Path corresponding to the given <paramref name="viewSpecification"/>, if it is a local view specification (i.e. one of the
        /// view specifications which are created in any of the sub views of this view specification). Else, this parameter will return <c>null</c>.</param>
        /// <returns><c>true</c>, if the given <paramref name="viewSpecification"/> is one of the direct or indirect view specifications which are created as sub view specifications
        /// of this view specification.</returns>
        public static bool TryGetLocalBrowseViewPath(ViewSpecification viewSpecification, out ResourcePath path)
        {
            LocalMediaRootProxyViewSpecification lmrpvs = viewSpecification as LocalMediaRootProxyViewSpecification;
            LocalSharesViewSpecification         lsvs   = viewSpecification as LocalSharesViewSpecification;

            if (lmrpvs != null || lsvs != null)
            { // If the current browsing state shows one of the root states, the path must be set to null
                path = null;
                return(true);
            }
            LocalDirectoryViewSpecification ldvs = viewSpecification as LocalDirectoryViewSpecification;

            if (ldvs != null)
            { // In a local browsing state, we can return the browsing path
                path = ldvs.ViewPath;
                return(true);
            }
            path = null;
            return(false);
        }
Example #25
0
 public abstract string GetResourcePathDisplayName(ResourcePath path);
Example #26
0
 protected abstract bool GetIsPathValid(ResourcePath path);
Example #27
0
        protected ResourceProviderMetadata GetBaseResourceProviderMetadata(ResourcePath path)
        {
            Guid?resourceProviderId = GetBaseResourceProviderId(path);

            return(resourceProviderId.HasValue ? GetResourceProviderMetadata(resourceProviderId.Value) : null);
        }
 protected bool GetIsPathValid(ResourcePath path)
 {
     return(_validatePathDlgt == null ? true : _validatePathDlgt(path));
 }
Example #29
0
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                web.EnsureProperties(w => w.ServerRelativeUrl);

                // determine pages library
                string pagesLibrary = "SitePages";

                List <string> preCreatedPages = new List <string>();

                var currentPageIndex = 0;
                // pre create the needed pages so we can fill the needed tokens which might be used later on when we put web parts on those pages
                foreach (var clientSidePage in template.ClientSidePages)
                {
                    string pageName = $"{System.IO.Path.GetFileNameWithoutExtension(parser.ParseString(clientSidePage.PageName))}.aspx";
                    string url      = $"{pagesLibrary}/{pageName}";

                    // Write page level status messages, needed in case many pages are provisioned
                    currentPageIndex++;
                    WriteMessage($"ClientSidePage|Create {pageName}|{currentPageIndex}|{template.ClientSidePages.Count}", ProvisioningMessageType.Progress);

                    url = UrlUtility.Combine(web.ServerRelativeUrl, url);

                    var exists = true;
                    try
                    {
                        var file = web.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(url));
                        web.Context.Load(file, f => f.UniqueId, f => f.ServerRelativePath);
                        web.Context.ExecuteQueryRetry();

                        // Fill token
                        parser.AddToken(new PageUniqueIdToken(web, file.ServerRelativePath.DecodedUrl.Substring(web.ServerRelativeUrl.Length).TrimStart("/".ToCharArray()), file.UniqueId));
                        parser.AddToken(new PageUniqueIdEncodedToken(web, file.ServerRelativePath.DecodedUrl.Substring(web.ServerRelativeUrl.Length).TrimStart("/".ToCharArray()), file.UniqueId));
                    }
                    catch (ServerException ex)
                    {
                        if (ex.ServerErrorTypeName == "System.IO.FileNotFoundException")
                        {
                            exists = false;
                        }
                    }

                    if (!exists)
                    {
                        // Pre-create the page
                        Pages.ClientSidePage page = web.AddClientSidePage(pageName);

                        // Set page layout now, because once it's set, it can't be changed.
                        if (!string.IsNullOrEmpty(clientSidePage.Layout))
                        {
                            if (clientSidePage.Layout.Equals("Article", StringComparison.InvariantCultureIgnoreCase))
                            {
                                page.LayoutType = Pages.ClientSidePageLayoutType.Article;
                            }
                            else if (clientSidePage.Layout.Equals("Home", StringComparison.InvariantCultureIgnoreCase))
                            {
                                page.LayoutType = Pages.ClientSidePageLayoutType.Home;
                            }
                            else if (clientSidePage.Layout.Equals("SingleWebPartAppPage", StringComparison.InvariantCultureIgnoreCase))
                            {
                                page.LayoutType = Pages.ClientSidePageLayoutType.SingleWebPartAppPage;
                            }
                        }

                        page.Save(pageName);

                        var file = web.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(url));
                        web.Context.Load(file, f => f.UniqueId, f => f.ServerRelativePath);
                        web.Context.ExecuteQueryRetry();

                        // Fill token
                        parser.AddToken(new PageUniqueIdToken(web, file.ServerRelativePath.DecodedUrl.Substring(web.ServerRelativeUrl.Length).TrimStart("/".ToCharArray()), file.UniqueId));
                        parser.AddToken(new PageUniqueIdEncodedToken(web, file.ServerRelativePath.DecodedUrl.Substring(web.ServerRelativeUrl.Length).TrimStart("/".ToCharArray()), file.UniqueId));

                        // Track that we pre-added this page
                        preCreatedPages.Add(url);
                    }
                }

                currentPageIndex = 0;
                // Iterate over the pages and create/update them
                foreach (var clientSidePage in template.ClientSidePages)
                {
                    string pageName = $"{System.IO.Path.GetFileNameWithoutExtension(parser.ParseString(clientSidePage.PageName))}.aspx";
                    string url      = $"{pagesLibrary}/{pageName}";
                    // Write page level status messages, needed in case many pages are provisioned
                    currentPageIndex++;
                    WriteMessage($"ClientSidePage|{pageName}|{currentPageIndex}|{template.ClientSidePages.Count}", ProvisioningMessageType.Progress);

                    url = UrlUtility.Combine(web.ServerRelativeUrl, url);

                    var exists = true;
                    try
                    {
                        var file = web.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(url));
                        web.Context.Load(file);
                        web.Context.ExecuteQueryRetry();
                    }
                    catch (ServerException ex)
                    {
                        if (ex.ServerErrorTypeName == "System.IO.FileNotFoundException")
                        {
                            exists = false;
                        }
                    }

                    Pages.ClientSidePage page = null;
                    if (exists)
                    {
                        if (clientSidePage.Overwrite || preCreatedPages.Contains(url))
                        {
                            // Get the existing page
                            page = web.LoadClientSidePage(pageName);
                            // Clear the page
                            page.ClearPage();
                        }
                        else
                        {
                            scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_ClientSidePages_NoOverWrite, pageName);
                            continue;
                        }
                    }
                    else
                    {
                        // Create new client side page
                        page = web.AddClientSidePage(pageName);
                    }

                    // Set page title
                    string newTitle = parser.ParseString(clientSidePage.Title);
                    if (page.PageTitle != newTitle)
                    {
                        page.PageTitle = newTitle;
                    }

                    // Page Header
                    if (clientSidePage.Header != null)
                    {
                        switch (clientSidePage.Header.Type)
                        {
                        case ClientSidePageHeaderType.None:
                        {
                            page.RemovePageHeader();
                            break;
                        }

                        case ClientSidePageHeaderType.Default:
                        {
                            page.SetDefaultPageHeader();
                            break;
                        }

                        case ClientSidePageHeaderType.Custom:
                        {
                            var serverRelativeImageUrl = parser.ParseString(clientSidePage.Header.ServerRelativeImageUrl);
                            if (clientSidePage.Header.TranslateX.HasValue && clientSidePage.Header.TranslateY.HasValue)
                            {
                                page.SetCustomPageHeader(serverRelativeImageUrl, clientSidePage.Header.TranslateX.Value, clientSidePage.Header.TranslateY.Value);
                            }
                            else
                            {
                                page.SetCustomPageHeader(serverRelativeImageUrl);
                            }
                            break;
                        }
                        }
                    }

                    // Set page layout
                    if (!string.IsNullOrEmpty(clientSidePage.Layout))
                    {
                        if (clientSidePage.Layout.Equals("Article", StringComparison.InvariantCultureIgnoreCase))
                        {
                            page.LayoutType = Pages.ClientSidePageLayoutType.Article;
                        }
                        else if (clientSidePage.Layout.Equals("Home", StringComparison.InvariantCultureIgnoreCase))
                        {
                            page.LayoutType = Pages.ClientSidePageLayoutType.Home;
                        }
                        else if (clientSidePage.Layout.Equals("SingleWebPartAppPage", StringComparison.InvariantCultureIgnoreCase))
                        {
                            page.LayoutType = Pages.ClientSidePageLayoutType.SingleWebPartAppPage;
                        }
                    }

                    // Load existing available controls
                    var componentsToAdd = page.AvailableClientSideComponents().ToList();

                    // if no section specified then add a default single column section
                    if (!clientSidePage.Sections.Any())
                    {
                        clientSidePage.Sections.Add(new CanvasSection()
                        {
                            Type = CanvasSectionType.OneColumn, Order = 10
                        });
                    }

                    int sectionCount = -1;
                    // Apply the "layout" and content
                    foreach (var section in clientSidePage.Sections)
                    {
                        sectionCount++;
                        switch (section.Type)
                        {
                        case CanvasSectionType.OneColumn:
                            page.AddSection(Pages.CanvasSectionTemplate.OneColumn, section.Order);
                            break;

                        case CanvasSectionType.OneColumnFullWidth:
                            page.AddSection(Pages.CanvasSectionTemplate.OneColumnFullWidth, section.Order);
                            break;

                        case CanvasSectionType.TwoColumn:
                            page.AddSection(Pages.CanvasSectionTemplate.TwoColumn, section.Order);
                            break;

                        case CanvasSectionType.ThreeColumn:
                            page.AddSection(Pages.CanvasSectionTemplate.ThreeColumn, section.Order);
                            break;

                        case CanvasSectionType.TwoColumnLeft:
                            page.AddSection(Pages.CanvasSectionTemplate.TwoColumnLeft, section.Order);
                            break;

                        case CanvasSectionType.TwoColumnRight:
                            page.AddSection(Pages.CanvasSectionTemplate.TwoColumnRight, section.Order);
                            break;

                        default:
                            page.AddSection(Pages.CanvasSectionTemplate.OneColumn, section.Order);
                            break;
                        }

                        // Add controls to the section
                        if (section.Controls.Any())
                        {
                            // Safety measure: reset column order to 1 for columns marked with 0 or lower
                            foreach (var control in section.Controls.Where(p => p.Column <= 0).ToList())
                            {
                                control.Column = 1;
                            }

                            foreach (CanvasControl control in section.Controls)
                            {
                                Pages.ClientSideComponent baseControl = null;

                                // Is it a text control?
                                if (control.Type == WebPartType.Text)
                                {
                                    Pages.ClientSideText textControl = new Pages.ClientSideText();
                                    if (control.ControlProperties.Any())
                                    {
                                        var textProperty = control.ControlProperties.First();
                                        textControl.Text = parser.ParseString(textProperty.Value);
                                    }
                                    else
                                    {
                                        if (!string.IsNullOrEmpty(control.JsonControlData))
                                        {
                                            var json = JsonConvert.DeserializeObject <Dictionary <string, string> >(control.JsonControlData);

                                            if (json.Count > 0)
                                            {
                                                textControl.Text = parser.ParseString(json.First().Value);
                                            }
                                        }
                                    }
                                    // Reduce column number by 1 due 0 start indexing
                                    page.AddControl(textControl, page.Sections[sectionCount].Columns[control.Column - 1], control.Order);
                                }
                                // It is a web part
                                else
                                {
                                    // apply token parsing on the web part properties
                                    control.JsonControlData = parser.ParseString(control.JsonControlData);

                                    // perform processing of web part properties (e.g. include listid property based list title property)
                                    var webPartPostProcessor = CanvasControlPostProcessorFactory.Resolve(control);
                                    webPartPostProcessor.Process(control, page);

                                    // Is a custom developed client side web part (3rd party)
                                    if (control.Type == WebPartType.Custom)
                                    {
                                        if (!string.IsNullOrEmpty(control.CustomWebPartName))
                                        {
                                            baseControl = componentsToAdd.FirstOrDefault(p => p.Name.Equals(control.CustomWebPartName, StringComparison.InvariantCultureIgnoreCase));
                                        }
                                        else if (control.ControlId != Guid.Empty)
                                        {
                                            baseControl = componentsToAdd.FirstOrDefault(p => p.Id.Equals($"{{{control.ControlId.ToString()}}}", StringComparison.CurrentCultureIgnoreCase));

                                            if (baseControl == null)
                                            {
                                                baseControl = componentsToAdd.FirstOrDefault(p => p.Id.Equals(control.ControlId.ToString(), StringComparison.InvariantCultureIgnoreCase));
                                            }
                                        }
                                    }
                                    // Is an OOB client side web part (1st party)
                                    else
                                    {
                                        string webPartName = "";
                                        switch (control.Type)
                                        {
                                        case WebPartType.Image:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.Image);
                                            break;

                                        case WebPartType.BingMap:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.BingMap);
                                            break;

                                        case WebPartType.ContentEmbed:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.ContentEmbed);
                                            break;

                                        case WebPartType.ContentRollup:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.ContentRollup);
                                            break;

                                        case WebPartType.DocumentEmbed:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.DocumentEmbed);
                                            break;

                                        case WebPartType.Events:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.Events);
                                            break;

                                        case WebPartType.GroupCalendar:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.GroupCalendar);
                                            break;

                                        case WebPartType.Hero:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.Hero);
                                            break;

                                        case WebPartType.ImageGallery:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.ImageGallery);
                                            break;

                                        case WebPartType.LinkPreview:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.LinkPreview);
                                            break;

                                        case WebPartType.List:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.List);
                                            break;

                                        case WebPartType.NewsFeed:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.NewsFeed);
                                            break;

                                        case WebPartType.NewsReel:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.NewsReel);
                                            break;

                                        case WebPartType.PageTitle:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.PageTitle);
                                            break;

                                        case WebPartType.People:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.People);
                                            break;

                                        case WebPartType.PowerBIReportEmbed:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.PowerBIReportEmbed);
                                            break;

                                        case WebPartType.QuickChart:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.QuickChart);
                                            break;

                                        case WebPartType.QuickLinks:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.QuickLinks);
                                            break;

                                        case WebPartType.SiteActivity:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.SiteActivity);
                                            break;

                                        case WebPartType.VideoEmbed:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.VideoEmbed);
                                            break;

                                        case WebPartType.YammerEmbed:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.YammerEmbed);
                                            break;

                                        case WebPartType.CustomMessageRegion:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.CustomMessageRegion);
                                            break;

                                        case WebPartType.Divider:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.Divider);
                                            break;

                                        case WebPartType.MicrosoftForms:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.MicrosoftForms);
                                            break;

                                        case WebPartType.Spacer:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.Spacer);
                                            break;

                                        case WebPartType.ClientWebPart:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.ClientWebPart);
                                            break;
                                        }

                                        baseControl = componentsToAdd.FirstOrDefault(p => p.Name.Equals(webPartName, StringComparison.InvariantCultureIgnoreCase));
                                    }

                                    if (baseControl != null)
                                    {
                                        Pages.ClientSideWebPart myWebPart = new Pages.ClientSideWebPart(baseControl)
                                        {
                                            Order = control.Order
                                        };

                                        // Reduce column number by 1 due 0 start indexing
                                        page.AddControl(myWebPart, page.Sections[sectionCount].Columns[control.Column - 1], control.Order);

                                        // set properties using json string
                                        if (!String.IsNullOrEmpty(control.JsonControlData))
                                        {
                                            myWebPart.PropertiesJson = control.JsonControlData;
                                        }

                                        // set using property collection
                                        if (control.ControlProperties.Any())
                                        {
                                            // grab the "default" properties so we can deduct their types, needed to correctly apply the set properties
                                            var    controlManifest   = JObject.Parse(baseControl.Manifest);
                                            JToken controlProperties = null;
                                            if (controlManifest != null)
                                            {
                                                controlProperties = controlManifest.SelectToken("preconfiguredEntries[0].properties");
                                            }

                                            foreach (var property in control.ControlProperties)
                                            {
                                                Type propertyType = typeof(string);

                                                if (controlProperties != null)
                                                {
                                                    var defaultProperty = controlProperties.SelectToken(property.Key, false);
                                                    if (defaultProperty != null)
                                                    {
                                                        propertyType = Type.GetType($"System.{defaultProperty.Type.ToString()}");

                                                        if (propertyType == null)
                                                        {
                                                            if (defaultProperty.Type.ToString().Equals("integer", StringComparison.InvariantCultureIgnoreCase))
                                                            {
                                                                propertyType = typeof(int);
                                                            }
                                                        }
                                                    }
                                                }

                                                myWebPart.Properties[property.Key] = JToken.FromObject(Convert.ChangeType(parser.ParseString(property.Value), propertyType));
                                            }
                                        }
                                    }
                                    else
                                    {
                                        scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_ClientSidePages_BaseControlNotFound, control.ControlId, control.CustomWebPartName);
                                    }
                                }
                            }
                        }
                    }

                    // Persist the page
                    page.Save(pageName);

                    if (clientSidePage.FieldValues != null && clientSidePage.FieldValues.Any())
                    {
                        List <FieldUpdateValue> fieldValues = clientSidePage.FieldValues.Select(s => new FieldUpdateValue(parser.ParseString(s.Key), parser.ParseString(s.Value))).ToList();
                        Microsoft.SharePoint.Client.FieldCollection fields = page.PageListItem.ParentList.Fields;
                        web.Context.Load(fields, fs => fs.Include(f => f.InternalName, f => f.FieldTypeKind, f => f.TypeAsString, f => f.ReadOnlyField, f => f.Title));
                        web.Context.ExecuteQueryRetry();
                        ListItemUtilities.UpdateListItem(web, page.PageListItem, fields, fieldValues);
                    }

                    if (page.LayoutType != Pages.ClientSidePageLayoutType.SingleWebPartAppPage)
                    {
                        // Set commenting, ignore on pages of the type Home
                        if (page.LayoutType != Pages.ClientSidePageLayoutType.Home)
                        {
                            // Make it a news page if requested
                            if (clientSidePage.PromoteAsNewsArticle)
                            {
                                page.PromoteAsNewsArticle();
                            }
                        }

                        if (clientSidePage.EnableComments)
                        {
                            page.EnableComments();
                        }
                        else
                        {
                            page.DisableComments();
                        }
                    }

                    // Publish page
                    if (clientSidePage.Publish)
                    {
                        page.Publish();
                    }

                    // Set any security on the page
                    if (clientSidePage.Security != null && clientSidePage.Security.RoleAssignments.Count != 0)
                    {
                        web.Context.Load(page.PageListItem);
                        web.Context.ExecuteQueryRetry();
                        page.PageListItem.SetSecurity(parser, clientSidePage.Security);
                    }
                }
            }

            WriteMessage("Done processing Client Side Pages", ProvisioningMessageType.Completed);
            return(parser);
        }
        /// <summary>
        /// Initialize ThumbnailIndex View
        /// </summary>
        private void Initialize()
        {
            Console.WriteLine("Initialize");
            _isFirstItem = true;

            _pbox = new PaddingBox(Forms.NativeParent)
            {
                Padding = new Thickness {
                    Left = 0, Right = 0, Top = 22, Bottom = 0
                },
                HeaderSize = new ElmSharp.Size(200, 19),
                HeaderGap  = 38
            };
            _pbox.Show();

            _index = new ElmSharp.Index(_pbox)
            {
                Style        = "thumbnail",
                AutoHide     = false,
                IsHorizontal = true,
                AlignmentX   = 0.5,
                AlignmentY   = 0.5,
            };
            _index.Show();
            _pbox.Header = _index;
            //index.Geometry = new Rect(0, 22, 200, 19);

            _scroller = new ElmSharp.Scroller(_pbox)
            {
                HorizontalLoop = false,
                VerticalLoop   = false,
                HorizontalScrollBarVisiblePolicy = ScrollBarVisiblePolicy.Invisible,
                VerticalScrollBarVisiblePolicy   = ScrollBarVisiblePolicy.Invisible,
                HorizontalPageScrollLimit        = 1,
                VerticalPageScrollLimit          = 0,
            };

            _scroller.PageScrolled += (s, e) =>
            {
                Console.WriteLine($" _scroller PageScrolled");
                var pageIndex = _scroller.HorizontalPageIndex;
                _items[pageIndex].Select(true);
            };
            _scroller.Show();
            _pbox.Content = _scroller;
            //_scroller.Geometry = new Rect(0, 79, 360, 281);

            var box = new ElmSharp.Box(_scroller)
            {
                IsHorizontal = true,
                AlignmentX   = 0.5,
                AlignmentY   = 0.5,
            };

            _scroller.SetContent(box);
            box.Show();

            // Create Rectangle for layout center align in Box
            var padder = new ElmSharp.Rectangle(box);

            box.PackEnd(padder);
            _items.Clear();

            // Initialize ThumbnailItems
            foreach (var item in Element.ThumbnailItems)
            {
                // create layout
                var page = new ElmSharp.Layout(box)
                {
                    WeightX    = 1.0,
                    WeightY    = 1.0,
                    AlignmentX = -1.0,
                    AlignmentY = 0.5
                };
                page.SetTheme("layout", "body_thumbnail", "default");
                page.Show();

                // set icon
                var img  = new ElmSharp.Image(page);
                var icon = item.Image;
                Console.WriteLine($"item.Image File:{icon.File}");
                img.LoadAsync(ResourcePath.GetPath(icon.File));
                page.SetPartContent("elm.icon", img);

                var indexItem = _index.Append(null);
                _items.Add(indexItem);

                // first item case
                if (_isFirstItem)
                {
                    Console.WriteLine($"_isFirstItem is true");
                    page.Resized += (s, e) =>
                    {
                        var g  = _scroller.Geometry;
                        var pg = page.Geometry;
                        padder.MinimumWidth  = (g.Width - pg.Width) / 2;
                        padder.MinimumHeight = g.Height / 2;
                        _scroller.SetPageSize(pg.Width, pg.Height);
                    };
                    indexItem.Select(true);
                }

                _isFirstItem = false;
                box.PackEnd(page);
            }

            box.PackEnd(padder);
            _index.Update(0);
        }
        public static async Task ProcessAsync(IOwinContext context, WebMediaType type, string id, int maxWidth, int maxHeight, string borders = null)
        {
            if (id == null)
            {
                throw new BadRequestException("GetImageResized: id is null");
            }
            if (maxWidth == 0)
            {
                throw new BadRequestException("GetImageResized: maxWidth is null");
            }
            if (maxHeight == 0)
            {
                throw new BadRequestException("GetImageResized: maxHeight is null");
            }

            Guid idGuid;

            if (!Guid.TryParse(id, out idGuid))
            {
                throw new BadRequestException(String.Format("GetImageResized: Couldn't parse if '{0}' to Guid", id));
            }

            ISet <Guid> necessaryMIATypes = new HashSet <Guid>();

            necessaryMIATypes.Add(MediaAspect.ASPECT_ID);
            necessaryMIATypes.Add(ProviderResourceAspect.ASPECT_ID);
            necessaryMIATypes.Add(ImporterAspect.ASPECT_ID);
            necessaryMIATypes.Add(ImageAspect.ASPECT_ID);
            MediaItem item = MediaLibraryAccess.GetMediaItemById(context, idGuid, necessaryMIATypes, null);

            var resourcePathStr = item.PrimaryResources[item.ActiveResourceLocatorIndex].GetAttributeValue(ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH);
            var resourcePath    = ResourcePath.Deserialize(resourcePathStr.ToString());

            var ra = GetResourceAccessor(resourcePath);
            IFileSystemResourceAccessor fsra = ra as IFileSystemResourceAccessor;

            if (fsra == null)
            {
                throw new InternalServerException("GetImage: failed to create IFileSystemResourceAccessor");
            }

            // Resize
            ImageCache.CacheIdentifier identifier = ImageCache.GetIdentifier(idGuid, false, maxWidth, maxHeight, borders, 0, FanArtTypes.Undefined, FanArtMediaTypes.Image);
            byte[] resizedImage;

            if (ImageCache.TryGetImageFromCache(context, identifier, out resizedImage))
            {
                Logger.Info("GetImageResized: Got image from cache");
            }
            else
            {
                using (var resourceStream = fsra.OpenRead())
                {
                    byte[] buffer = new byte[resourceStream.Length];
                    resourceStream.Read(buffer, 0, Convert.ToInt32(resourceStream.Length));
                    resizedImage = Plugins.MP2Extended.WSS.Images.ResizeImage(buffer, maxWidth, maxHeight, borders);
                }

                // Add to cache
                if (ImageCache.AddImageToCache(context, resizedImage, identifier))
                {
                    Logger.Info("GetImageResized: Added image to cache");
                }
            }

            using (var resourceStream = new MemoryStream(resizedImage))
            {
                // HTTP/1.1 RFC2616 section 14.25 'If-Modified-Since'
                if (!string.IsNullOrEmpty(context.Request.Headers["If-Modified-Since"]))
                {
                    DateTime lastRequest = DateTime.Parse(context.Request.Headers["If-Modified-Since"]);
                    if (lastRequest.CompareTo(fsra.LastChanged) <= 0)
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.NotModified;
                    }
                }

                // HTTP/1.1 RFC2616 section 14.29 'Last-Modified'
                context.Response.Headers["Last-Modified"] = fsra.LastChanged.ToUniversalTime().ToString("r");

                string        byteRangesSpecifier = context.Request.Headers["Range"];
                IList <Range> ranges      = ParseByteRanges(byteRangesSpecifier, resourceStream.Length);
                bool          onlyHeaders = context.Request.Method == "HEAD" || context.Response.StatusCode == (int)HttpStatusCode.NotModified;
                if (ranges != null && ranges.Count > 0)
                {
                    // We only support last range
                    await SendRangeAsync(context, resourceStream, ranges[ranges.Count - 1], onlyHeaders);
                }
                else
                {
                    await SendWholeFileAsync(context, resourceStream, onlyHeaders);
                }
            }
        }
Example #32
0
        public override void Load(IResourceCache cache, ResourcePath path)
        {
            var    manifestPath = path / "meta.json";
            string manifestContents;

            using (var manifestFile = cache.ContentFileRead(manifestPath))
                using (var reader = new StreamReader(manifestFile))
                {
                    manifestContents = reader.ReadToEnd();
                }

            if (RSISchema != null)
            {
                var errors = RSISchema.Validate(manifestContents);
                if (errors.Count != 0)
                {
                    Logger.Error($"Unable to load RSI from '{path}', {errors.Count} errors:");

                    foreach (var error in errors)
                    {
                        Logger.Error("{0}", error.ToString());
                    }

                    throw new RSILoadException($"{errors.Count} errors while loading RSI. See console.");
                }
            }

            // Ok schema validated just fine.
            var manifestJson = JObject.Parse(manifestContents);
            var size         = manifestJson["size"].ToObject <Vector2u>();

            var rsi = new RSI(size);

            // Do every state.
            foreach (var stateObject in manifestJson["states"].Cast <JObject>())
            {
                var stateName = stateObject["name"].ToObject <string>();
                var dirValue  = stateObject["directions"].ToObject <int>();
                RSI.State.DirectionType directions;

                switch (dirValue)
                {
                case 1:
                    directions = RSI.State.DirectionType.Dir1;
                    break;

                case 4:
                    directions = RSI.State.DirectionType.Dir4;
                    break;

                default:
                    throw new RSILoadException($"Invalid direction: {dirValue}");
                }

                // We can ignore selectors and flags for now,
                // because they're not used yet!

                // Get the lists of delays.
                float[][] delays;
                if (stateObject.TryGetValue("delays", out var delayToken))
                {
                    delays = delayToken.ToObject <float[][]>();

                    if (delays.Length != dirValue)
                    {
                        throw new RSILoadException($"Directions count does not match amount of delays specified.");
                    }

                    for (var i = 0; i < delays.Length; i++)
                    {
                        var delayList = delays[i];
                        if (delayList.Length == 0)
                        {
                            delays[i] = new float[] { 1 };
                        }
                    }
                }
                else
                {
                    delays = new float[dirValue][];
                    // No delays specified, default to 1 frame per dir.
                    for (var i = 0; i < dirValue; i++)
                    {
                        delays[i] = new float[] { 1 };
                    }
                }

                var texPath = path / (stateName + ".png");
                var texture = cache.GetResource <TextureResource>(texPath).Texture;

                if (texture.Width % size.X != 0 || texture.Height % size.Y != 0)
                {
                    throw new RSILoadException("State image size is not a multiple of the icon size.");
                }

                // Amount of icons per row of the sprite sheet.
                var sheetWidth = texture.Width / size.X;

                var iconFrames = new (Texture, float)[dirValue][];
Example #33
0
        /// <summary>
        /// Tries to find the resource path corresponding to the given media library <paramref name="viewSpecification"/>.
        /// </summary>
        /// <param name="viewSpecification">View specification to be examined.</param>
        /// <param name="path">Path corresponding to the given <paramref name="viewSpecification"/>, if it is a media library view specification (i.e. one of the
        /// view specifications which are created in any of the sub views of this view specification). Else, this parameter will return <c>null</c>.</param>
        /// <returns><c>true</c>, if the given <paramref name="viewSpecification"/> is one of the direct or indirect view specifications which are created as sub view specifications
        /// of this view specification.</returns>
        public static bool TryGetLocalBrowseViewPath(ViewSpecification viewSpecification, out ResourcePath path)
        {
            MediaLibraryBrowseViewSpecification mlbvs = viewSpecification as MediaLibraryBrowseViewSpecification;

            if (mlbvs != null)
            { // We're in some MediaLibrary browsing state
                IServerConnectionManager serverConnectionManager = ServiceRegistration.Get <IServerConnectionManager>();
                string localSystemId = ServiceRegistration.Get <ISystemResolver>().LocalSystemId;
                if (mlbvs.SystemId != localSystemId && mlbvs.SystemId != serverConnectionManager.HomeServerSystemId)
                { // If the currently browsed system is a different one, the path must be set to null
                    path = null;
                    return(true);
                }
                // In a browsing state for the local system, we can return the base path from the view specification
                path = mlbvs.BasePath;
                return(true);
            }

            BrowseMediaRootProxyViewSpecification bmrvs = viewSpecification as BrowseMediaRootProxyViewSpecification;
            SystemSharesViewSpecification         ssvs  = viewSpecification as SystemSharesViewSpecification;
            AllSystemsViewSpecification           asvs  = viewSpecification as AllSystemsViewSpecification;

            if (ssvs != null || asvs != null || bmrvs != null)
            { // If the current browsing state shows one of the root browse states, we can just set the path to null
                path = null;
                return(true);
            }
            path = null;
            return(false);
        }
Example #34
0
 public IFile FileFor(ResourcePath path)
 {
     return(new File(path));
 }
Example #35
0
 public IFolder FolderFor(ResourcePath path)
 {
     return(new Folder(path, this));
 }
Example #36
0
 public override string GetResourcePathDisplayName(ResourcePath path)
 {
   return GetLocalResourcePathDisplayName(path);
 }
Example #37
0
 protected override IEnumerable<ResourcePathMetadata> GetChildDirectoriesData(ResourcePath path)
 {
   IResourceAccessor ra;
   if (path.TryCreateLocalResourceAccessor(out ra))
   {
     using (ra)
     {
       IFileSystemResourceAccessor fsra = ra as IFileSystemResourceAccessor;
       if (fsra == null)
         yield break;
       ICollection<IFileSystemResourceAccessor> res = FileSystemResourceNavigator.GetChildDirectories(fsra, false);
       if (res != null)
         foreach (IFileSystemResourceAccessor childAccessor in res)
           using (childAccessor)
           {
             yield return new ResourcePathMetadata
               {
                   ResourceName = childAccessor.ResourceName,
                   HumanReadablePath = childAccessor.ResourcePathName,
                   ResourcePath = childAccessor.CanonicalLocalResourcePath
               };
           }
     }
   }
   else
     ServiceRegistration.Get<ILogger>().Warn("LocalShares: Cannot access resource path '{0}' for getting child directories", path);
 }
Example #38
0
        protected override void ExecuteCmdlet()
        {
            if (ParameterSetName == ParameterSet_ASFILE)
            {
                if (!System.IO.Path.IsPathRooted(Path))
                {
                    Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path);
                }
                if (string.IsNullOrEmpty(NewFileName))
                {
                    FileName = System.IO.Path.GetFileName(Path);
                }
                else
                {
                    FileName = NewFileName;
                }
            }

            var folder  = EnsureFolder();
            var fileUrl = UrlUtility.Combine(folder.ServerRelativeUrl, FileName);

            ContentType targetContentType = null;

            // Check to see if the Content Type exists. If it doesn't we are going to throw an exception and block this transaction right here.
            if (ContentType != null)
            {
                try
                {
                    var list = SelectedWeb.GetListByUrl(Folder);

                    if (!string.IsNullOrEmpty(ContentType.Id))
                    {
                        targetContentType = list.GetContentTypeById(ContentType.Id);
                    }
                    else if (!string.IsNullOrEmpty(ContentType.Name))
                    {
                        targetContentType = list.GetContentTypeByName(ContentType.Name);
                    }
                    else if (ContentType.ContentType != null)
                    {
                        targetContentType = ContentType.ContentType;
                    }
                    if (targetContentType == null)
                    {
                        ThrowTerminatingError(new ErrorRecord(new ArgumentException($"Content Type Argument: {ContentType} does not exist in the list: {list.Title}"), "CONTENTTYPEDOESNOTEXIST", ErrorCategory.InvalidArgument, this));
                    }
                }
                catch
                {
                    ThrowTerminatingError(new ErrorRecord(new ArgumentException($"The Folder specified ({folder.ServerRelativeUrl}) does not have a corresponding List, the -ContentType parameter is not valid."), "RELATIVEPATHNOTINLIBRARY", ErrorCategory.InvalidArgument, this));
                }
            }

            // Check if the file exists
            if (Checkout)
            {
                try
                {
#if ONPREMISES
                    var existingFile = SelectedWeb.GetFileByServerRelativeUrl(fileUrl);
#else
                    var existingFile = SelectedWeb.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(fileUrl));
#endif
                    existingFile.EnsureProperty(f => f.Exists);
                    if (existingFile.Exists)
                    {
                        SelectedWeb.CheckOutFile(fileUrl);
                    }
                }
                catch
                { // Swallow exception, file does not exist
                }
            }
            Microsoft.SharePoint.Client.File file;
            if (ParameterSetName == ParameterSet_ASFILE)
            {
                file = folder.UploadFile(FileName, Path, true);
            }
            else
            {
                file = folder.UploadFile(FileName, Stream, true);
            }

            if (Values != null)
            {
                var item = file.ListItemAllFields;

                ListItemHelper.UpdateListItem(item, Values, ListItemUpdateType.UpdateOverwriteVersion,
                                              (warning) =>
                {
                    WriteWarning(warning);
                },
                                              (terminatingErrorMessage, terminatingErrorCode) =>
                {
                    ThrowTerminatingError(new ErrorRecord(new Exception(terminatingErrorMessage), terminatingErrorCode, ErrorCategory.InvalidData, this));
                });
            }
            if (ContentType != null)
            {
                var item = file.ListItemAllFields;
                item["ContentTypeId"] = targetContentType.Id.StringValue;
#if !ONPREMISES
                item.UpdateOverwriteVersion();
#else
                item.Update();
#endif
                ClientContext.ExecuteQueryRetry();
            }

            if (Checkout)
            {
                SelectedWeb.CheckInFile(fileUrl, CheckinType.MajorCheckIn, CheckInComment);
            }


            if (Publish)
            {
                SelectedWeb.PublishFile(fileUrl, PublishComment);
            }

            if (Approve)
            {
                SelectedWeb.ApproveFile(fileUrl, ApproveComment);
            }
            ClientContext.Load(file);
            ClientContext.ExecuteQueryRetry();
            WriteObject(file);
        }
Example #39
0
 protected bool IsAllowedToAccess(ResourcePath resourcePath)
 {
     // TODO: How to check safety? We don't have access to our shares store here... See also method IsAllowedToAccess
     // in UPnPResourceInformationServiceImpl
     return(true);
 }
Example #40
0
        /// <summary>
        /// Creates a new local share. This will create a new share ID and call the constructor with it.
        /// </summary>
        /// <param name="baseResourcePath">Description of the resource provider chain for the share's base directory.</param>
        /// <param name="name">Name of the share. This name will be shown at the GUI. The string might be
        /// localized using a "[[Section-Name].[String-Name]]" syntax, for example "[Media.MyMusic]".</param>
        /// <param name="mediaCategories">Media content categories of this share. If set, the category
        /// describes the desired contents of this share. If set to <c>null</c>, this share has no explicit
        /// media categories, i.e. it is a general share.</param>
        /// <returns>Created <see cref="Share"/> with a new share id.</returns>
        public static Share CreateNewLocalShare(ResourcePath baseResourcePath, string name, IEnumerable <string> mediaCategories)
        {
            ISystemResolver systemResolver = ServiceRegistration.Get <ISystemResolver>();

            return(CreateNewShare(systemResolver.LocalSystemId, baseResourcePath, name, mediaCategories));
        }
        public Guid ShowPathBrowser(string headerText, bool enumerateFiles, bool showSystemResources, ResourcePath initialPath, ValidatePathDlgt validatePathDlgt)
        {
            ChoosenResourcePath = null;
            UpdateResourceProviderPathTree();
            HeaderText          = headerText;
            _dialogHandle       = Guid.NewGuid();
            _dialogAccepted     = false;
            _enumerateFiles     = enumerateFiles;
            _validatePathDlgt   = validatePathDlgt;
            ShowSystemResources = showSystemResources;

            IScreenManager screenManager    = ServiceRegistration.Get <IScreenManager>();
            Guid?          dialogInstanceId = screenManager.ShowDialog(Consts.DIALOG_PATH_BROWSER, OnDialogClosed);

            if (!dialogInstanceId.HasValue)
            {
                throw new InvalidDataException("File browser could not be shown");
            }
            _dialogInstanceId = dialogInstanceId.Value;
            return(_dialogHandle);
        }
Example #42
0
 internal string GetPath(ResourcePath relPath)
 {
     return(Path.GetFullPath(Path.Combine(_directory.FullName, relPath.ToRelativeSystemPath())));
 }
Example #43
0
 protected abstract bool SharePathExists(ResourcePath sharePath);
Example #44
0
 protected static bool IsAllowedToAccess(ResourcePath resourcePath)
 {
     // TODO: How to check safety? We don't have access to our shares store here... See also method IsAllowedToAccess
     // in ResourceAccessModule
     return(true);
 }
Example #45
0
        protected void UpdateChoosenPathDisplayName()
        {
            ResourcePath path = ChoosenResourcePath;

            ChoosenResourcePathDisplayName = path == null ? string.Empty : GetResourcePathDisplayName(path);
        }
Example #46
0
 protected override IEnumerable<ResourcePathMetadata> GetChildDirectoriesData(ResourcePath path)
 {
   IResourceInformationService ris = GetResourceInformationService();
   return ris.GetChildDirectoriesData(path);
 }
Example #47
0
 /// <summary>
 /// Creates a new resource accessor for the resource located in the system with the given <paramref name="systemId"/> with the
 /// given <paramref name="nativeResourcePath"/>.
 /// </summary>
 /// <param name="systemId">Id of the MP2 system where the desirec resource is located.</param>
 /// <param name="nativeResourcePath">Path of the desired resource in the system with the given <paramref name="systemId"/>.</param>
 public ResourceLocator(string systemId, ResourcePath nativeResourcePath)
 {
     _nativeSystemId     = systemId;
     _nativeResourcePath = nativeResourcePath;
 }
Example #48
0
 public ImportJob(ImportJobType jobType, ResourcePath basePath, IEnumerable <Guid> metadataExtractorIds,
                  bool includeSubDirectories)
 {
     _jobInfo = new ImportJobInformation(jobType, basePath, new List <Guid>(metadataExtractorIds), includeSubDirectories);
 }
 public static Texture GetTexture(this IResourceCache cache, ResourcePath path)
 {
     return(cache.GetResource <TextureResource>(path));
 }
 public static Font GetFont(this IResourceCache cache, ResourcePath path, int size)
 {
     return(new VectorFont(cache.GetResource <FontResource>(path), size));
 }
Example #51
0
 protected override bool SharePathExists(ResourcePath sharePath)
 {
   if (_serverSharesCache == null)
     GetShares();
   Guid origShareId = _origShare == null ? Guid.Empty : _origShare.ShareId;
   return _serverSharesCache.Any(serverShare => serverShare.ShareId != origShareId && serverShare.BaseResourcePath == sharePath);
 }
Example #52
0
        private bool TryCreateInsertVideoMediaMediaItem(MediaItem origMi, out MediaItem subMi)
        {
            subMi = null;
            IPathManager pathManager       = ServiceRegistration.Get <IPathManager>();
            string       resourceDirectory = pathManager.GetPath(@"<DATA>\Resources\");

            string[] files = Directory.GetFiles(resourceDirectory, "InsertVideoMedia.*");
            if (files == null || files.Length == 0)
            {
                return(false);
            }

            IDictionary <Guid, IList <MediaItemAspect> > aspects = new Dictionary <Guid, IList <MediaItemAspect> >();

            foreach (var aspect in origMi.Aspects)
            {
                if (aspect.Key != ProviderResourceAspect.ASPECT_ID)
                {
                    aspects.Add(aspect.Key, aspect.Value);
                }
            }

            MediaItemAspect providerResourceAspect = MediaItemAspect.CreateAspect(aspects, ProviderResourceAspect.Metadata);

            providerResourceAspect.SetAttribute(ProviderResourceAspect.ATTR_RESOURCE_INDEX, 0);
            providerResourceAspect.SetAttribute(ProviderResourceAspect.ATTR_TYPE, ProviderResourceAspect.TYPE_PRIMARY);
            providerResourceAspect.SetAttribute(ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH, ResourcePath.BuildBaseProviderPath(LocalFsResourceProviderBase.LOCAL_FS_RESOURCE_PROVIDER_ID, files[0]).Serialize());
            providerResourceAspect.SetAttribute(ProviderResourceAspect.ATTR_MIME_TYPE, MimeTypeDetector.GetMimeType(files[0], "video/unknown"));
            providerResourceAspect.SetAttribute(ProviderResourceAspect.ATTR_SYSTEM_ID, ServiceRegistration.Get <ISystemResolver>().LocalSystemId);

            subMi = new MediaItem(Guid.Empty, aspects);
            return(true);
        }
Example #53
0
 public static string GetServerResourcePathDisplayName(ResourcePath path)
 {
   try
   {
   IResourceInformationService ris = GetResourceInformationService();
     return ris.GetResourcePathDisplayName(path);
   }
   catch (Exception e)
   {
     ServiceRegistration.Get<ILogger>().Warn("Problem updating display name of choosen path '{0}'", e, path);
     return string.Empty;
   }
 }
        private static TextureLoadParameters?_tryLoadTextureParameters(IResourceCache cache, ResourcePath path)
        {
            var metaPath = path.WithName(path.Filename + ".yml");

            if (cache.TryContentFileRead(metaPath, out var stream))
            {
                YamlDocument yamlData;
                using (var reader = new StreamReader(stream, EncodingHelpers.UTF8))
                {
                    var yamlStream = new YamlStream();
                    yamlStream.Load(reader);
                    if (yamlStream.Documents.Count == 0)
                    {
                        return(null);
                    }

                    yamlData = yamlStream.Documents[0];
                }

                return(TextureLoadParameters.FromYaml((YamlMappingNode)yamlData.RootNode));
            }
            return(null);
        }
Example #55
0
 protected override bool SharePathExists(ResourcePath sharePath)
 {
   ILocalSharesManagement sharesManagement = ServiceRegistration.Get<ILocalSharesManagement>();
   return sharesManagement.Shares.Values.Any(share => share.ShareId != _origShare.ShareId && share.BaseResourcePath == sharePath);
 }
Example #56
0
        public static IDbCommand UpdateShareCommand(ITransaction transaction, Guid shareId, ResourcePath baseResourcePath,
                                                    string shareName, bool useWatcher)
        {
            IDbCommand result = transaction.CreateCommand();

            result.CommandText = "UPDATE SHARES set NAME=@NAME, BASE_RESOURCE_PATH=@BASE_RESOURCE_PATH, WATCHER=@WATCHER WHERE SHARE_ID=@SHARE_ID";
            ISQLDatabase database = transaction.Database;

            database.AddParameter(result, "NAME", shareName, typeof(string));
            database.AddParameter(result, "BASE_RESOURCE_PATH", baseResourcePath.Serialize(), typeof(string));
            database.AddParameter(result, "WATCHER", useWatcher ? 1 : 0, typeof(int));
            database.AddParameter(result, "SHARE_ID", shareId, typeof(Guid));
            return(result);
        }
Example #57
0
 public static string GetLocalResourcePathDisplayName(ResourcePath path)
 {
   if (path == null)
     return string.Empty;
   IResourceAccessor ra;
   if (path.TryCreateLocalResourceAccessor(out ra))
     using (ra)
       return ra.ResourcePathName;
   ServiceRegistration.Get<ILogger>().Warn("LocalShares: Cannot access resource path '{0}' for updating display name", path);
   return string.Empty;
 }
        private Task <bool> ExtractThumbnailAsync(ILocalFsResourceAccessor lfsra, IDictionary <Guid, IList <MediaItemAspect> > extractedAspectData)
        {
            // We can only work on files and make sure this file was detected by a lower MDE before (title is set then).
            // VideoAspect must be present to be sure it is actually a video resource.
            if (!lfsra.IsFile || !extractedAspectData.ContainsKey(VideoStreamAspect.ASPECT_ID))
            {
                return(Task.FromResult(false));
            }

            //ServiceRegistration.Get<ILogger>().Info("OCVVideoThumbnailer: Evaluate {0}", lfsra.ResourceName);

            bool isPrimaryResource = false;
            IList <MultipleMediaItemAspect> resourceAspects;

            if (MediaItemAspect.TryGetAspects(extractedAspectData, ProviderResourceAspect.Metadata, out resourceAspects))
            {
                foreach (MultipleMediaItemAspect pra in resourceAspects)
                {
                    string       accessorPath = (string)pra.GetAttributeValue(ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH);
                    ResourcePath resourcePath = ResourcePath.Deserialize(accessorPath);
                    if (resourcePath.Equals(lfsra.CanonicalLocalResourcePath))
                    {
                        if (pra.GetAttributeValue <int?>(ProviderResourceAspect.ATTR_TYPE) == ProviderResourceAspect.TYPE_PRIMARY)
                        {
                            isPrimaryResource = true;
                            break;
                        }
                    }
                }
            }

            if (!isPrimaryResource) //Ignore subtitles
            {
                return(Task.FromResult(false));
            }

            // Check for a reasonable time offset
            int    defaultVideoOffset = 720;
            long   videoDuration;
            double downscale = 2; // Reduces the video frame size to a half of original
            IList <MultipleMediaItemAspect> videoAspects;

            if (MediaItemAspect.TryGetAspects(extractedAspectData, VideoStreamAspect.Metadata, out videoAspects))
            {
                if ((videoDuration = videoAspects[0].GetAttributeValue <long>(VideoStreamAspect.ATTR_DURATION)) > 0)
                {
                    if (defaultVideoOffset > videoDuration * 1 / 3)
                    {
                        defaultVideoOffset = Convert.ToInt32(videoDuration * 1 / 3);
                    }
                }

                double width  = videoAspects[0].GetAttributeValue <int>(VideoStreamAspect.ATTR_WIDTH);
                double height = videoAspects[0].GetAttributeValue <int>(VideoStreamAspect.ATTR_HEIGHT);
                downscale = width / 256.0; //256 is max size of large thumbnail aspect
            }

            using (lfsra.EnsureLocalFileSystemAccess())
            {
                using (VideoCapture capture = new VideoCapture())
                {
                    capture.Open(lfsra.LocalFileSystemPath);
                    capture.PosMsec = defaultVideoOffset * 1000;
                    using (var mat = capture.RetrieveMat())
                    {
                        if (mat.Height > 0 && mat.Width > 0)
                        {
                            double width  = mat.Width;
                            double height = mat.Height;
                            ServiceRegistration.Get <ILogger>().Debug("OCVVideoThumbnailer: Scaling thumbnail of size {1}x{2} for resource '{0}'", lfsra.LocalFileSystemPath, width, height);
                            using (var scaledMat = mat.Resize(new OpenCvSharp.Size(width / downscale, height / downscale)))
                            {
                                var binary = scaledMat.ToBytes();
                                MediaItemAspect.SetAttribute(extractedAspectData, ThumbnailLargeAspect.ATTR_THUMBNAIL, binary);
                                ServiceRegistration.Get <ILogger>().Info("OCVVideoThumbnailer: Successfully created thumbnail for resource '{0}'", lfsra.LocalFileSystemPath);
                            }
                        }
                        else
                        {
                            ServiceRegistration.Get <ILogger>().Warn("OCVVideoThumbnailer: Failed to create thumbnail for resource '{0}'", lfsra.LocalFileSystemPath);
                        }
                    }
                }
            }
            return(Task.FromResult(true));
        }
Example #59
0
 /// <summary>
 /// Creates a new share. This will create a new share id and call the constructor with it.
 /// </summary>
 /// <param name="systemId">Specifies the system on that the resource provider with the specified
 /// <paramref name="baseResourcePath"/> will be evaluated.</param>
 /// <param name="baseResourcePath">Description of the resource provider chain for the share's base directory.</param>
 /// <param name="name">Name of the share. This name will be shown at the GUI. The string might be
 /// localized using a "[[Section-Name].[String-Name]]" syntax, for example "[Media.MyMusic]".</param>
 /// <param name="mediaCategories">Media content categories of this share. If set, the category
 /// describes the desired contents of this share. If set to <c>null</c>, this share has no explicit
 /// media categories, i.e. it is a general share.</param>
 /// <returns>Created <see cref="Share"/> with a new share id.</returns>
 public static Share CreateNewShare(string systemId, ResourcePath baseResourcePath, string name,
                                    IEnumerable <string> mediaCategories)
 {
     return(new Share(Guid.NewGuid(), systemId, baseResourcePath, name, mediaCategories));
 }
Example #60
0
        /// <summary>
        /// Gets a list of <see cref="FanArtImage"/>s for a requested <paramref name="mediaType"/>, <paramref name="fanArtType"/> and <paramref name="name"/>.
        /// The name can be: Series name, Actor name, Artist name depending on the <paramref name="mediaType"/>.
        /// </summary>
        /// <param name="mediaType">Requested FanArtMediaType</param>
        /// <param name="fanArtType">Requested FanArtType</param>
        /// <param name="name">Requested name of Series, Actor, Artist...</param>
        /// <param name="maxWidth">Maximum width for image. <c>0</c> returns image in original size.</param>
        /// <param name="maxHeight">Maximum height for image. <c>0</c> returns image in original size.</param>
        /// <param name="singleRandom">If <c>true</c> only one random image URI will be returned</param>
        /// <param name="result">Result if return code is <c>true</c>.</param>
        /// <returns><c>true</c> if at least one match was found.</returns>
        public bool TryGetFanArt(string mediaType, string fanArtType, string name, int maxWidth, int maxHeight, bool singleRandom, out IList <IResourceLocator> result)
        {
            result = null;

            if (!VALID_MEDIA_TYPES.Contains(mediaType) || !VALID_FANART_TYPES.Contains(fanArtType))
            {
                return(false);
            }

            if (string.IsNullOrWhiteSpace(name))
            {
                return(false);
            }

            Guid mediaItemId;

            if (Guid.TryParse(name, out mediaItemId) == false)
            {
                return(false);
            }

            List <string> fanArtFiles = new List <string>();

            fanArtFiles.AddRange(FanArtCache.GetFanArtFiles(mediaItemId.ToString().ToUpperInvariant(), fanArtType));

            // Try fallback
            if (fanArtFiles.Count == 0 &&
                (mediaType == FanArtMediaTypes.SeriesSeason ||
                 mediaType == FanArtMediaTypes.Character ||
                 (mediaType == FanArtMediaTypes.Episode && fanArtType == FanArtTypes.FanArt)))
            {
                IMediaLibrary mediaLibrary = ServiceRegistration.Get <IMediaLibrary>(false);
                if (mediaLibrary == null)
                {
                    return(false);
                }

                IFilter           filter = new MediaItemIdFilter(mediaItemId);
                IList <MediaItem> items  = mediaLibrary.Search(new MediaItemQuery(NECESSARY_MIAS, OPTIONAL_MIAS, filter), false, null, true);
                if (items == null || items.Count == 0)
                {
                    return(false);
                }

                MediaItem mediaItem = items.First();

                if (mediaType == FanArtMediaTypes.Episode && fanArtType == FanArtTypes.FanArt)
                {
                    if (mediaItem.Aspects.ContainsKey(EpisodeAspect.ASPECT_ID))
                    {
                        IList <MultipleMediaItemAspect> relationAspects;
                        if (MediaItemAspect.TryGetAspects(mediaItem.Aspects, RelationshipAspect.Metadata, out relationAspects))
                        {
                            //Season fallback
                            foreach (MultipleMediaItemAspect relation in relationAspects)
                            {
                                if ((Guid?)relation[RelationshipAspect.ATTR_LINKED_ROLE] == SeasonAspect.ROLE_SEASON)
                                {
                                    fanArtFiles.AddRange(FanArtCache.GetFanArtFiles(relation[RelationshipAspect.ATTR_LINKED_ID].ToString().ToUpperInvariant(), fanArtType));
                                    if (fanArtFiles.Count > 0)
                                    {
                                        break;
                                    }
                                }
                            }

                            //Series fallback
                            if (fanArtFiles.Count == 0)
                            {
                                foreach (MultipleMediaItemAspect relation in relationAspects)
                                {
                                    if ((Guid?)relation[RelationshipAspect.ATTR_LINKED_ROLE] == SeriesAspect.ROLE_SERIES)
                                    {
                                        fanArtFiles.AddRange(FanArtCache.GetFanArtFiles(relation[RelationshipAspect.ATTR_LINKED_ID].ToString().ToUpperInvariant(), fanArtType));
                                        if (fanArtFiles.Count > 0)
                                        {
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                else if (mediaType == FanArtMediaTypes.SeriesSeason)
                {
                    if (mediaItem.Aspects.ContainsKey(SeasonAspect.ASPECT_ID))
                    {
                        IList <MultipleMediaItemAspect> relationAspects;
                        if (MediaItemAspect.TryGetAspects(mediaItem.Aspects, RelationshipAspect.Metadata, out relationAspects))
                        {
                            foreach (MultipleMediaItemAspect relation in relationAspects)
                            {
                                if ((Guid?)relation[RelationshipAspect.ATTR_LINKED_ROLE] == SeriesAspect.ROLE_SERIES)
                                {
                                    fanArtFiles.AddRange(FanArtCache.GetFanArtFiles(relation[RelationshipAspect.ATTR_LINKED_ID].ToString().ToUpperInvariant(), fanArtType));
                                    if (fanArtFiles.Count > 0)
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                else if (mediaType == FanArtMediaTypes.Character)
                {
                    if (mediaItem.Aspects.ContainsKey(CharacterAspect.ASPECT_ID))
                    {
                        IList <MultipleMediaItemAspect> relationAspects;
                        if (MediaItemAspect.TryGetAspects(mediaItem.Aspects, RelationshipAspect.Metadata, out relationAspects))
                        {
                            foreach (MultipleMediaItemAspect relation in relationAspects)
                            {
                                if ((Guid?)relation[RelationshipAspect.ATTR_LINKED_ROLE] == PersonAspect.ROLE_ACTOR)
                                {
                                    fanArtFiles.AddRange(FanArtCache.GetFanArtFiles(relation[RelationshipAspect.ATTR_LINKED_ID].ToString().ToUpperInvariant(), fanArtType));
                                    if (fanArtFiles.Count > 0)
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            List <IResourceLocator> files = new List <IResourceLocator>();

            try
            {
                files.AddRange(fanArtFiles
                               .Select(fileName => new ResourceLocator(ResourcePath.BuildBaseProviderPath(LocalFsResourceProviderBase.LOCAL_FS_RESOURCE_PROVIDER_ID, fileName)))
                               );
                result = files;
                return(result.Count > 0);
            }
            catch (Exception) { }
            return(false);
        }