Beispiel #1
0
 public ResourcePath ExpandResourcePathFromString(string pathStr)
 {
     if (string.IsNullOrEmpty(pathStr))
     {
         return(null);
     }
     // The input string is given by the user. We can cope with two formats:
     // 1) A resource provider path in form of a virtual ID (GUID)
     // 2) A resource path in the resource path syntax (i.e. {[Provider-Id]}:///1)
     if (IsResource(pathStr))
     {
         return(new ResourcePath(new ProviderPathSegment[]
         {
             new ProviderPathSegment(VIRTUAL_RESOURCE_PROVIDER_ID, pathStr, true),
         }));
     }
     try
     {
         return(ResourcePath.Deserialize(pathStr));
     }
     catch (ArgumentException)
     {
         return(null);
     }
 }
Beispiel #2
0
        public override void Update(MediaItem mediaItem)
        {
            base.Update(mediaItem);
            SingleMediaItemAspect imageAspect;

            if (MediaItemAspect.TryGetAspect(mediaItem.Aspects, ImageAspect.Metadata, out imageAspect))
            {
                SimpleTitle = Title;
                int?width  = (int?)imageAspect[ImageAspect.ATTR_WIDTH];
                int?height = (int?)imageAspect[ImageAspect.ATTR_HEIGHT];
                if (width.HasValue && width.Value > 0 && height.HasValue && height.Value > 0)
                {
                    Width  = width;
                    Height = height;
                    Size   = width + " x " + height;
                }
            }
            IList <MultipleMediaItemAspect> resourceAspects;

            if (MediaItemAspect.TryGetAspects(mediaItem.Aspects, ProviderResourceAspect.Metadata, out resourceAspects))
            {
                ResourcePath rp  = ResourcePath.Deserialize((string)resourceAspects[0][ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH]);
                string       ext = ProviderPathHelper.GetExtension(rp.FileName);
                if (ext.Length > 1)
                {
                    // remove leading '.'
                    ext = ext.Substring(1);
                }
                Extension = ext;
                MimeType  = (string)resourceAspects[0][ProviderResourceAspect.ATTR_MIME_TYPE];
            }
            FireChange();
        }
Beispiel #3
0
        protected bool TryGetConfiguration(MediaItem mediaItem, out EmulatorConfiguration configuration)
        {
            configuration = null;
            List <string> mimeTypes;
            string        mimeType;

            if (mediaItem == null ||
                !MediaItemAspect.TryGetAttribute(mediaItem.Aspects, ProviderResourceAspect.ATTR_MIME_TYPE, out mimeTypes) ||
                string.IsNullOrEmpty(mimeType = mimeTypes.First()))
            {
                return(false);
            }

            List <string> paths;
            string        path;

            if (!MediaItemAspect.TryGetAttribute(mediaItem.Aspects, ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH, out paths) ||
                string.IsNullOrEmpty(path = paths.First()))
            {
                return(false);
            }

            ResourcePath rp  = ResourcePath.Deserialize(path);
            string       ext = ProviderPathHelper.GetExtension(rp.FileName);

            return(ServiceRegistration.Get <IEmulatorManager>().TryGetConfiguration(mimeType, ext, out configuration));
        }
        static UPnPError OnImportLocation(DvAction action, IList <object> inParams, out IList <object> outParams,
                                          CallContext context)
        {
            outParams = null;
            ResourcePath path = ResourcePath.Deserialize((string)inParams[0]);

            string[]      mediaCategories  = ((string)inParams[1]).Split(',');
            string        importJobTypeStr = (string)inParams[2];
            ImportJobType importJobType;
            UPnPError     error = ParseImportJobType("ImportJobType", importJobTypeStr, out importJobType);

            if (error != null)
            {
                return(error);
            }
            if (importJobType == ImportJobType.Refresh)
            {
                ServiceRegistration.Get <IImporterWorker>().ScheduleRefresh(path, mediaCategories, true);
            }
            else
            {
                ServiceRegistration.Get <IImporterWorker>().ScheduleImport(path, mediaCategories, true);
            }
            return(null);
        }
Beispiel #5
0
        static UPnPError OnGetResourceDisplayName(DvAction action, IList <object> inParams, out IList <object> outParams,
                                                  CallContext context)
        {
            outParams = null;
            ResourcePath path = ResourcePath.Deserialize((string)inParams[0]);

            if (path == null)
            {
                return(new UPnPError(600, "Invalid resource path"));
            }
            if (!IsAllowedToAccess(path))
            {
                return(new UPnPError(600, "Access is not allowed to this resource path"));
            }
            IResourceAccessor ra;

            if (!path.TryCreateLocalResourceAccessor(out ra))
            {
                return(new UPnPError(600, "The given path is not accessible"));
            }
            using (ra)
                outParams = new List <object> {
                    ra.ResourceName
                };
            return(null);
        }
        protected static bool CanExtract(IResourceAccessor mediaItemAccessor, IDictionary <Guid, IList <MediaItemAspect> > extractedAspectData, out IResourceAccessor metaFileAccessor)
        {
            metaFileAccessor = null;
            IFileSystemResourceAccessor fsra = mediaItemAccessor as IFileSystemResourceAccessor;

            if (fsra == null || !fsra.IsFile)
            {
                return(false);
            }

            string title;

            if (!MediaItemAspect.TryGetAttribute(extractedAspectData, MediaAspect.ATTR_TITLE, out title) || string.IsNullOrEmpty(title))
            {
                return(false);
            }

            string filePath       = mediaItemAccessor.CanonicalLocalResourcePath.ToString();
            string lowerExtension = StringUtils.TrimToEmpty(ProviderPathHelper.GetExtension(filePath)).ToLowerInvariant();

            if (lowerExtension != ".ts")
            {
                return(false);
            }
            string metaFilePath = ProviderPathHelper.ChangeExtension(filePath, ".arg");

            if (!ResourcePath.Deserialize(metaFilePath).TryCreateLocalResourceAccessor(out metaFileAccessor))
            {
                return(false);
            }
            return(true);
        }
        public void TestFanArtExtractAlbumArtistFolderFanArt()
        {
            //Arrange
            _fanArtCache.Clear();
            Guid albumId = Guid.NewGuid();

            Guid artist1Id = Guid.NewGuid();
            Guid artist2Id = Guid.NewGuid();
            IList <Tuple <Guid, string> > artists = new List <Tuple <Guid, string> >
            {
                new Tuple <Guid, string>(artist1Id, "Album Artist1"),
                new Tuple <Guid, string>(artist2Id, "Album Artist2")
            };

            AudioFanArtHandlerForTests fh = new AudioFanArtHandlerForTests();

            //Act
            fh.TestExtractAlbumFolderFanArt(albumId, ResourcePath.BuildBaseProviderPath(MockResourceProvider.PROVIDER_ID, "Audio/TestArtist/TestAlbum/"), artists).Wait();

            //Assert
            List <string> fanart;

            Assert.IsTrue(_fanArtCache.FanArt.TryGetValue(artist1Id, out fanart));
            ICollection <string> fanartBasePaths = fanart.Select(p => ResourcePath.Deserialize(p).BasePathSegment.Path).ToList();

            CollectionAssert.Contains(fanartBasePaths, "Audio/TestArtist/TestAlbum/.artists/album_artist1-thumb.png");

            Assert.IsTrue(_fanArtCache.FanArt.TryGetValue(artist2Id, out fanart));
            fanartBasePaths = fanart.Select(p => ResourcePath.Deserialize(p).BasePathSegment.Path).ToList();
            CollectionAssert.Contains(fanartBasePaths, "Audio/TestArtist/TestAlbum/.artists/album_artist2-thumb.png");
        }
Beispiel #8
0
        protected internal override void ReLoadItemsAndSubViewSpecifications(out IList <MediaItem> mediaItems, out IList <ViewSpecification> subViewSpecifications)
        {
            mediaItems            = new List <MediaItem>();
            subViewSpecifications = new List <ViewSpecification>();
            IServerConnectionManager scm = ServiceRegistration.Get <IServerConnectionManager>();
            IContentDirectory        cd  = scm.ContentDirectory;

            if (cd == null)
            {
                return;
            }
            foreach (Share share in cd.GetShares(_systemId, SharesFilter.All))
            {
                // Check if we want to filter only for given MediaCategories
                if (_restrictedMediaCategories != null && !share.MediaCategories.Intersect(_restrictedMediaCategories).Any())
                {
                    continue;
                }
                MediaItem parentDirectory = cd.LoadItem(share.SystemId, share.BaseResourcePath, DIRECTORY_MIA_ID_ENUMERATION, EMPTY_ID_ENUMERATION);
                if (parentDirectory == null)
                {
                    continue;
                }
                MediaItemAspect pra = parentDirectory.Aspects[ProviderResourceAspect.ASPECT_ID];
                subViewSpecifications.Add(new MediaLibraryBrowseViewSpecification(share.Name, parentDirectory.MediaItemId,
                                                                                  (string)pra.GetAttributeValue(ProviderResourceAspect.ATTR_SYSTEM_ID),
                                                                                  ResourcePath.Deserialize((string)pra.GetAttributeValue(ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH)),
                                                                                  _necessaryMIATypeIds, _optionalMIATypeIds));
            }
        }
        public void TestFanArtExtractSeasonActorFolderFanArt()
        {
            //Arrange
            _fanArtCache.Clear();
            Guid seasonId = Guid.NewGuid();

            Guid actor1Id = Guid.NewGuid();
            Guid actor2Id = Guid.NewGuid();
            IList <Tuple <Guid, string> > actors = new List <Tuple <Guid, string> >
            {
                new Tuple <Guid, string>(actor1Id, "Season Actor1"),
                new Tuple <Guid, string>(actor2Id, "Season Actor2")
            };

            SeriesFanArtHandlerForTests fh = new SeriesFanArtHandlerForTests();

            //Act
            fh.TestExtractSeasonFolderFanArt(seasonId, ResourcePath.BuildBaseProviderPath(MockResourceProvider.PROVIDER_ID, "Series/TestSeries/Season 1/episode1.mkv"), 1, actors).Wait();

            //Assert
            List <string> fanart;

            Assert.IsTrue(_fanArtCache.FanArt.TryGetValue(actor1Id, out fanart));
            ICollection <string> fanartBasePaths = fanart.Select(p => ResourcePath.Deserialize(p).BasePathSegment.Path).ToList();

            CollectionAssert.Contains(fanartBasePaths, "Series/TestSeries/Season 1/.actors/season_actor1-thumb.png");

            Assert.IsTrue(_fanArtCache.FanArt.TryGetValue(actor2Id, out fanart));
            fanartBasePaths = fanart.Select(p => ResourcePath.Deserialize(p).BasePathSegment.Path).ToList();
            CollectionAssert.Contains(fanartBasePaths, "Series/TestSeries/Season 1/.actors/season_actor2-thumb.png");
        }
Beispiel #10
0
 private bool GetFsraFromResourcePathString(String resourcePathString, out IFileSystemResourceAccessor fsra)
 {
     try
     {
         IResourceAccessor ra;
         if (!ResourcePath.Deserialize(resourcePathString).TryCreateLocalResourceAccessor(out ra))
         {
             fsra = null;
             ServiceRegistration.Get <ILogger>().Error("ImporterWorker.{0}: Could not create ResourceAccessor for resource '{1}': It is no filesystem resource", _parentImportJobController, resourcePathString);
             return(false);
         }
         fsra = ra as IFileSystemResourceAccessor;
         if (fsra == null)
         {
             ra.Dispose();
             ServiceRegistration.Get <ILogger>().Error("ImporterWorker.{0}: Could not load resource '{1}': It is no filesystem resource", _parentImportJobController, resourcePathString);
             return(false);
         }
     }
     catch (Exception ex)
     {
         fsra = null;
         ServiceRegistration.Get <ILogger>().Error("ImporterWorker.{0}: Error creating ResourceAccessor for resource '{1}'", ex, _parentImportJobController, resourcePathString);
         return(false);
     }
     return(true);
 }
        public ResourcePath ExpandResourcePathFromString(string pathStr)
        {
            if (string.IsNullOrEmpty(pathStr))
            {
                return(null);
            }
            // The input string is given by the user. We can cope with three formats:
            // 1) A resource provider path of the form "/1"
            // 2) The track number
            // 3) A resource path in the resource path syntax (i.e. {[Provider-Id]}:///1)
            if (IsResource(pathStr))
            {
                return(new ResourcePath(new ProviderPathSegment[]
                {
                    new ProviderPathSegment(AUDIO_CD_RESOURCE_PROVIDER_ID, pathStr, true),
                }));
            }
            string modifiedPath = "/" + pathStr;

            if (IsResource(modifiedPath))
            {
                return(new ResourcePath(new ProviderPathSegment[]
                {
                    new ProviderPathSegment(AUDIO_CD_RESOURCE_PROVIDER_ID, modifiedPath, true),
                }));
            }
            try
            {
                return(ResourcePath.Deserialize(pathStr));
            }
            catch (ArgumentException)
            {
                return(null);
            }
        }
Beispiel #12
0
        public bool NextItem(MediaItem mediaItem, StartTime startTime)
        {
            string resourcePath;
            string title;

            if (!MediaItemAspect.TryGetAttribute(mediaItem.Aspects, ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH, out resourcePath) ||
                !MediaItemAspect.TryGetAttribute(mediaItem.Aspects, MediaAspect.ATTR_TITLE, out title))
            {
                return(false);
            }

            ResourcePath rp = ResourcePath.Deserialize(resourcePath);

            if (rp.LastPathSegment.ProviderId != RawUrlResourceProvider.RAW_URL_RESOURCE_PROVIDER_ID)
            {
                return(false);
            }

            _itemTitle = title;

            string url = rp.LastPathSegment.Path;

            UpdateTexture(url);
            return(true);
        }
        protected internal override void ReLoadItemsAndSubViewSpecifications(out IList <MediaItem> mediaItems, out IList <ViewSpecification> subViewSpecifications)
        {
            mediaItems            = null;
            subViewSpecifications = null;
            IContentDirectory cd = ServiceRegistration.Get <IServerConnectionManager>().ContentDirectory;

            if (cd == null)
            {
                return;
            }
            try
            {
                mediaItems = new List <MediaItem>(cd.Browse(_directoryId, _necessaryMIATypeIds, _optionalMIATypeIds));
                ICollection <MediaItem> childDirectories = cd.Browse(_directoryId, DIRECTORY_MIA_ID_ENUMERATION, EMPTY_ID_ENUMERATION);
                subViewSpecifications = new List <ViewSpecification>(childDirectories.Count);
                foreach (MediaItem childDirectory in childDirectories)
                {
                    MediaItemAspect ma  = childDirectory.Aspects[MediaAspect.ASPECT_ID];
                    MediaItemAspect pra = childDirectory.Aspects[ProviderResourceAspect.ASPECT_ID];
                    MediaLibraryBrowseViewSpecification subViewSpecification = new MediaLibraryBrowseViewSpecification(
                        (string)ma.GetAttributeValue(MediaAspect.ATTR_TITLE), childDirectory.MediaItemId,
                        (string)pra.GetAttributeValue(ProviderResourceAspect.ATTR_SYSTEM_ID),
                        ResourcePath.Deserialize((string)pra.GetAttributeValue(ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH)),
                        _necessaryMIATypeIds, _optionalMIATypeIds);
                    subViewSpecifications.Add(subViewSpecification);
                }
            }
            catch (UPnPRemoteException e)
            {
                ServiceRegistration.Get <ILogger>().Error("SimpleTextSearchViewSpecification.ReLoadItemsAndSubViewSpecifications: Error requesting server", e);
                mediaItems            = null;
                subViewSpecifications = null;
            }
        }
Beispiel #14
0
        private static ICollection <Share> GetMediaSources(ISQLDatabase database)
        {
            IList <Share> sources = new List <Share>();

            ITransaction transaction = database.BeginTransaction();

            IDbCommand sourcesCommand = transaction.CreateCommand();

            sourcesCommand.CommandText = "select share_id,base_resource_path,name from shares s";
            IDataReader sourcesReader = sourcesCommand.ExecuteReader();

            while (sourcesReader.Read())
            {
                Guid         sourceId     = sourcesReader.GetGuid(sourcesReader.GetOrdinal("share_id"));
                ResourcePath resourcePath = ResourcePath.Deserialize(sourcesReader.GetString(sourcesReader.GetOrdinal("base_resource_path")));

                IList <string> categories        = new List <string>();
                IDbCommand     categoriesCommand = transaction.CreateCommand();
                categoriesCommand.CommandText = "select categoryname from shares_categories where share_id=@share_id";
                database.AddParameter(categoriesCommand, "share_id", sourceId, typeof(Guid));
                IDataReader categoriesReader = categoriesCommand.ExecuteReader();
                while (categoriesReader.Read())
                {
                    categories.Add(categoriesReader.GetString(categoriesReader.GetOrdinal("categoryname")));
                }
                categoriesReader.Close();

                string name = sourcesReader.GetString(sourcesReader.GetOrdinal("name"));
                sources.Add(new Share(sourceId, null, resourcePath, name, true, categories));
            }
            sourcesReader.Close();

            return(sources);
        }
        /// <summary>
        /// Returns a resource locator instance for this item.
        /// </summary>
        /// <returns>Resource locator instance or <c>null</c>, if this item doesn't contain a <see cref="ProviderResourceAspect"/>.</returns>
        public virtual IResourceLocator GetResourceLocator()
        {
            var    aspect               = PrimaryResources[ActiveResourceLocatorIndex];
            string systemId             = (string)aspect[ProviderResourceAspect.ATTR_SYSTEM_ID];
            string resourceAccessorPath = (string)aspect[ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH];

            return(new ResourceLocator(systemId, ResourcePath.Deserialize(resourceAccessorPath)));
        }
Beispiel #16
0
        /// <summary>
        /// Main process method for the InnerBlock
        /// </summary>
        /// <remarks>
        /// - SingleResources are just passed to the next DataflowBlock
        /// - If it's not a SingleResource
        ///   - it finds all the files in the current directory,
        ///   - in case of a RefreshImport
        ///     - it deletes all the files in the MediaLibrary that do not exist anymore in the filesystem,
        ///     - it stores the DateOfLastImport of all the files in the <see cref="PendingImportResourceNewGen"/>
        /// </remarks>
        /// <param name="importResource"><see cref="PendingImportResourceNewGen"/> to be processed</param>
        /// <returns>
        /// a HashSet of <see cref="PendingImportResourceNewGen"/>s containing the current <see cref="PendingImportResource"/>
        /// after processing as well as <see cref="PendingImportResourceNewGen"/>s for all files in the current directory
        /// </returns>
        private async Task <IEnumerable <PendingImportResourceNewGen> > ProcessDirectory(PendingImportResourceNewGen importResource)
        {
            var result = new HashSet <PendingImportResourceNewGen> {
                importResource
            };

            try
            {
                if (importResource.IsSingleResource)
                {
                    return(result);
                }

                // FileSystemResourceNavigator.GetFiles also returns files that were identified as virtual directories by
                // FileSystemResourceNavigator.GetChildDirectories (such as zip-files).
                // ToDo: Clarify if this is a bug
                var files = FileSystemResourceNavigator.GetFiles(importResource.ResourceAccessor, false) ?? new HashSet <IFileSystemResourceAccessor>();
                IDictionary <ResourcePath, DateTime> path2LastImportDate = null;

                if (ImportJobInformation.JobType == ImportJobType.Refresh)
                {
                    MediaItemAspect directoryAspect;
                    // ReSharper disable once PossibleInvalidOperationException
                    path2LastImportDate = (await Browse(importResource.MediaItemId.Value, PROVIDERRESOURCE_IMPORTER_MIA_ID_ENUMERATION, DIRECTORY_MIA_ID_ENUMERATION))
                                          .Where(mi => !mi.Aspects.TryGetValue(DirectoryAspect.ASPECT_ID, out directoryAspect))
                                          .ToDictionary(mi => ResourcePath.Deserialize(mi[ProviderResourceAspect.ASPECT_ID].GetAttributeValue <String>(ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH)), mi => mi[ImporterAspect.ASPECT_ID].GetAttributeValue <DateTime>(ImporterAspect.ATTR_LAST_IMPORT_DATE));
                    await DeleteNoLongerExistingFilesFromMediaLibrary(files, path2LastImportDate.Keys);
                }

                result.UnionWith(files.Select(f => new PendingImportResourceNewGen(importResource.ResourceAccessor.CanonicalLocalResourcePath, f, ToString(), ParentImportJobController, importResource.MediaItemId)));

                // If this is a RefreshImport and we found files of the current directory in the MediaLibrary,
                // store the DateOfLastImport in the PendingImportResource
                DateTime dateTime;
                if (path2LastImportDate != null)
                {
                    foreach (var pir in result)
                    {
                        if (path2LastImportDate.TryGetValue(pir.PendingResourcePath, out dateTime))
                        {
                            pir.DateOfLastImport = dateTime;
                        }
                    }
                }

                return(result);
            }
            catch (TaskCanceledException)
            {
                return(result);
            }
            catch (Exception ex)
            {
                ServiceRegistration.Get <ILogger>().Warn("ImporterWorker.{0}.{1}: Error while processing {2}", ex, ParentImportJobController, ToString(), importResource);
                importResource.IsValid = false;
                return(result);
            }
        }
Beispiel #17
0
        public static async Task <bool> ProcessAsync(IOwinContext context, WebMediaType type, string id)
        {
            if (id == null)
            {
                throw new BadRequestException("GetImage: id is null");
            }

            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, id, 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");
            }

            using (var resourceStream = fsra.OpenRead())
            {
                // 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);
                }
            }
            return(true);
        }
        public ResourcePath ExpandResourcePathFromString(Guid resourceProviderId, string path)
        {
            CpAction       action       = GetAction("ExpandResourcePathFromString");
            IList <object> inParameters = new List <object> {
                MarshallingHelper.SerializeGuid(resourceProviderId), path
            };
            IList <object> outParameters = action.InvokeAction(inParameters);

            return(ResourcePath.Deserialize((string)outParameters[0]));
        }
        public ResourcePath ConcatenatePaths(ResourcePath basePath, string relativePath)
        {
            CpAction       action       = GetAction("ConcatenatePaths");
            IList <object> inParameters = new List <object> {
                basePath.Serialize(), relativePath
            };
            IList <object> outParameters = action.InvokeAction(inParameters);

            return(ResourcePath.Deserialize((string)outParameters[0]));
        }
Beispiel #20
0
        /// <summary>
        /// Returns a resource locator instance for this item.
        /// </summary>
        /// <returns>Resource locator instance or <c>null</c>, if this item doesn't contain a <see cref="ProviderResourceAspect"/>.</returns>
        public IResourceLocator GetResourceLocator()
        {
            MediaItemAspect providerAspect;

            if (!_aspects.TryGetValue(ProviderResourceAspect.ASPECT_ID, out providerAspect))
            {
                return(null);
            }
            string systemId             = (string)providerAspect[ProviderResourceAspect.ATTR_SYSTEM_ID];
            string resourceAccessorPath = (string)providerAspect[ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH];

            return(new ResourceLocator(systemId, ResourcePath.Deserialize(resourceAccessorPath)));
        }
Beispiel #21
0
        protected internal override void ReLoadItemsAndSubViewSpecifications(out IList <MediaItem> mediaItems, out IList <ViewSpecification> subViewSpecifications)
        {
            mediaItems            = null;
            subViewSpecifications = null;
            IContentDirectory cd = ServiceRegistration.Get <IServerConnectionManager>().ContentDirectory;

            if (cd == null)
            {
                return;
            }

            Guid?           userProfile = null;
            IUserManagement userProfileDataManagement = ServiceRegistration.Get <IUserManagement>();

            if (userProfileDataManagement != null && userProfileDataManagement.IsValidUser)
            {
                userProfile = userProfileDataManagement.CurrentUser.ProfileId;
            }

            try
            {
                bool showVirtual = VirtualMediaHelper.ShowVirtualMedia(_necessaryMIATypeIds);
                mediaItems = new List <MediaItem>(cd.BrowseAsync(_directoryId, _necessaryMIATypeIds, _optionalMIATypeIds, userProfile, showVirtual).Result);
                ICollection <MediaItem> childDirectories = cd.BrowseAsync(_directoryId, DIRECTORY_MIA_ID_ENUMERATION, EMPTY_ID_ENUMERATION, userProfile, showVirtual).Result;
                subViewSpecifications = new List <ViewSpecification>(childDirectories.Count);
                foreach (MediaItem childDirectory in childDirectories)
                {
                    SingleMediaItemAspect ma = null;
                    MediaItemAspect.TryGetAspect(childDirectory.Aspects, MediaAspect.Metadata, out ma);
                    IList <MultipleMediaItemAspect> pras = null;

                    MediaItemAspect.TryGetAspects(childDirectory.Aspects, ProviderResourceAspect.Metadata, out pras);
                    foreach (MultipleMediaItemAspect pra in pras)
                    {
                        MediaLibraryBrowseViewSpecification subViewSpecification = new MediaLibraryBrowseViewSpecification(
                            (string)ma.GetAttributeValue(MediaAspect.ATTR_TITLE), childDirectory.MediaItemId,
                            (string)pra.GetAttributeValue(ProviderResourceAspect.ATTR_SYSTEM_ID),
                            ResourcePath.Deserialize((string)pra.GetAttributeValue(ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH)),
                            _necessaryMIATypeIds, _optionalMIATypeIds);
                        subViewSpecifications.Add(subViewSpecification);
                    }
                }
            }
            catch (UPnPRemoteException e)
            {
                ServiceRegistration.Get <ILogger>().Error("SimpleTextSearchViewSpecification.ReLoadItemsAndSubViewSpecifications: Error requesting server", e);
                mediaItems            = null;
                subViewSpecifications = null;
            }
        }
Beispiel #22
0
        static UPnPError OnGetFilesData(DvAction action, IList <object> inParams, out IList <object> outParams,
                                        CallContext context)
        {
            outParams = null;
            ResourcePath path = ResourcePath.Deserialize((string)inParams[0]);

            if (path == null)
            {
                return(new UPnPError(600, "Invalid resource path"));
            }
            if (!IsAllowedToAccess(path))
            {
                return(new UPnPError(600, "Access is not allowed to this resource path"));
            }
            IResourceAccessor ra;

            if (!path.TryCreateLocalResourceAccessor(out ra))
            {
                return(new UPnPError(600, "The given path is not accessible"));
            }
            using (ra)
            {
                IFileSystemResourceAccessor fsra = ra as IFileSystemResourceAccessor;
                if (fsra == null)
                {
                    return(new UPnPError(600, "The given path is not a file system resource"));
                }
                ICollection <IFileSystemResourceAccessor> res = FileSystemResourceNavigator.GetFiles(fsra, false);
                IList <ResourcePathMetadata> result           = null;
                if (res != null)
                {
                    result = new List <ResourcePathMetadata>();
                    foreach (IFileSystemResourceAccessor fileAccessor in res)
                    {
                        using (fileAccessor)
                            result.Add(new ResourcePathMetadata
                            {
                                ResourceName      = fileAccessor.ResourceName,
                                HumanReadablePath = fileAccessor.ResourcePathName,
                                ResourcePath      = fileAccessor.CanonicalLocalResourcePath
                            });
                    }
                }
                outParams = new List <object> {
                    result
                };
            }
            return(null);
        }
Beispiel #23
0
        /// <summary>
        /// Main process method for the InnerBlock
        /// </summary>
        /// <remarks>
        /// - SingleResources are just passed to the next DataflowBlock
        /// - If it's not a SingleResource
        ///   - it finds all the files in the current directory,
        ///   - in case of a RefreshImport
        ///     - it deletes all the files in the MediaLibrary that do not exist anymore in the filesystem,
        ///     - it stores the DateOfLastImport of all the files in the <see cref="PendingImportResourceNewGen"/>
        /// </remarks>
        /// <param name="importResource"><see cref="PendingImportResourceNewGen"/> to be processed</param>
        /// <returns>
        /// a HashSet of <see cref="PendingImportResourceNewGen"/>s containing the current <see cref="PendingImportResource"/>
        /// after processing as well as <see cref="PendingImportResourceNewGen"/>s for all files in the current directory
        /// </returns>
        private async Task <IEnumerable <PendingImportResourceNewGen> > ProcessChanges(PendingImportResourceNewGen importResource)
        {
            var result = new HashSet <PendingImportResourceNewGen> {
                importResource
            };

            try
            {
                if (ImportJobInformation.JobType == ImportJobType.Refresh)
                {
                    // ReSharper disable once PossibleInvalidOperationException
                    IEnumerable <MediaItem> mediaItems = await GetUpdatableMediaItems(PROVIDERRESOURCE_IMPORTER_MIA_ID_ENUMERATION, null);

                    if (mediaItems != null)
                    {
                        foreach (MediaItem mi in mediaItems)
                        {
                            IList <MultipleMediaItemAspect> providerAspects = null;
                            if (MediaItemAspect.TryGetAspects(mi.Aspects, ProviderResourceAspect.Metadata, out providerAspects))
                            {
                                ResourcePath      path        = ResourcePath.Deserialize(providerAspects[0].GetAttributeValue <String>(ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH));
                                Guid?             directoryId = providerAspects[0].GetAttributeValue <Guid?>(ProviderResourceAspect.ATTR_PARENT_DIRECTORY_ID);
                                IResourceAccessor ra;
                                if (path.TryCreateLocalResourceAccessor(out ra) && ra is IFileSystemResourceAccessor)
                                {
                                    IFileSystemResourceAccessor f   = ra as IFileSystemResourceAccessor;
                                    string       dirPath            = ResourcePathHelper.GetDirectoryName(ra.Path);
                                    ResourcePath dirRa              = ResourcePath.BuildBaseProviderPath(ra.ParentProvider.Metadata.ResourceProviderId, dirPath);
                                    PendingImportResourceNewGen pir = new PendingImportResourceNewGen(dirRa, f, ToString(), ParentImportJobController, directoryId, mi.MediaItemId);
                                    pir.DateOfLastImport = DateTime.MinValue; //Force update
                                    result.Add(pir);
                                }
                            }
                        }
                    }
                }
                return(result);
            }
            catch (TaskCanceledException)
            {
                return(result);
            }
            catch (Exception ex)
            {
                ServiceRegistration.Get <ILogger>().Warn("ImporterWorker.{0}.{1}: Error while processing {2}", ex, ParentImportJobController, ToString(), importResource);
                importResource.IsValid = false;
                return(result);
            }
        }
Beispiel #24
0
        internal static IList <ResourcePath> GetResourcePaths(MediaItem item)
        {
            List <ResourcePath>             paths = new List <ResourcePath>();
            IList <MultipleMediaItemAspect> providerResourceAspects;

            if (MediaItemAspect.TryGetAspects(item.Aspects, ProviderResourceAspect.Metadata, out providerResourceAspects))
            {
                foreach (var res in providerResourceAspects.Where(p => p.GetAttributeValue <int>(ProviderResourceAspect.ATTR_TYPE) == ProviderResourceAspect.TYPE_PRIMARY))
                {
                    var resourcePathStr = res.GetAttributeValue <string>(ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH);
                    var resourcePath    = ResourcePath.Deserialize(resourcePathStr.ToString());
                    paths.Add(resourcePath);
                }
            }
            return(paths);
        }
Beispiel #25
0
        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);
            }
        }
    private string GetRemovableMediaItemPath(MediaItem mediaItem)
    {
      if (mediaItem == null)
        return null;

      foreach (var pra in mediaItem.PrimaryResources)
      {
        var resPath = ResourcePath.Deserialize(pra.GetAttributeValue<string>(ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH));
        var dosPath = LocalFsResourceProviderBase.ToDosPath(resPath);
        if (string.IsNullOrEmpty(dosPath))
          continue;
        if (DriveUtils.IsDVD(dosPath))
          return dosPath;
      }
      return null;
    }
        internal static bool Delete(IOwinContext context, MediaItem item)
        {
            Guid?user = ResourceAccessUtils.GetUser(context);
            IList <MultipleMediaItemAspect> providerResourceAspects;

            if (MediaItemAspect.TryGetAspects(item.Aspects, ProviderResourceAspect.Metadata, out providerResourceAspects))
            {
                foreach (var res in providerResourceAspects.Where(p => p.GetAttributeValue <int>(ProviderResourceAspect.ATTR_TYPE) == ProviderResourceAspect.TYPE_PRIMARY))
                {
                    var systemId        = res.GetAttributeValue <string>(ProviderResourceAspect.ATTR_SYSTEM_ID);
                    var resourcePathStr = res.GetAttributeValue <string>(ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH);
                    var resourcePath    = ResourcePath.Deserialize(resourcePathStr.ToString());
                    MediaLibrary.DeleteMediaItemOrPath(systemId, resourcePath, true);
                }
            }
            return(true);
        }
Beispiel #28
0
        /// <summary>
        /// Tries to create a <see cref="IFileSystemResourceAccessor"/> for the directory of a given file.
        /// </summary>
        /// <param name="fsra">IFileSystemResourceAccessor of file.</param>
        /// <returns>IFileSystemResourceAccessor or <c>null</c>, if no fsra could be created.</returns>
        private static IFileSystemResourceAccessor GetContainingDirectory(IFileSystemResourceAccessor fsra)
        {
            string            filePath      = fsra.CanonicalLocalResourcePath.ToString();
            string            directoryPath = ResourcePathHelper.GetDirectoryName(filePath);
            IResourceAccessor metaFileAccessor;

            if (!ResourcePath.Deserialize(directoryPath).TryCreateLocalResourceAccessor(out metaFileAccessor))
            {
                return(null);
            }
            if (!(metaFileAccessor is IFileSystemResourceAccessor))
            {
                metaFileAccessor.Dispose();
                return(null);
            }
            return((IFileSystemResourceAccessor)metaFileAccessor);
        }
Beispiel #29
0
 public void CreateResourceAccessor()
 {
     try
     {
         string            resourcePathStr = ResourcePathStr;
         ResourcePath      path            = ResourcePath.Deserialize(resourcePathStr);
         IResourceAccessor ra;
         if (path.TryCreateLocalResourceAccessor(out ra))
         {
             ra.Dispose();
         }
     }
     catch (Exception e)
     {
         ServiceRegistration.Get <ILogger>().Error("Error creating resource accessor", e);
     }
 }
Beispiel #30
0
        /// <summary>
        /// Does the preparation to start a stream
        /// </summary>
        internal static async Task <StreamContext> StartOriginalFileStreamingAsync(string identifier)
        {
            if (STREAM_ITEMS.TryGetValue(identifier, out var currentStreamItem))
            {
                using (await currentStreamItem.RequestBusyLockAsync())
                {
                    if (currentStreamItem.IsActive)
                    {
                        currentStreamItem.TranscoderObject?.StopStreaming();
                        if (currentStreamItem.StreamContext is TranscodeContext context)
                        {
                            context.UpdateStreamUse(false);
                        }
                        else if (currentStreamItem.StreamContext != null)
                        {
                            currentStreamItem.StreamContext.Dispose();
                            currentStreamItem.StreamContext = null;
                        }
                    }

                    IMediaAccessor           mediaAccessor = ServiceRegistration.Get <IMediaAccessor>();
                    List <IResourceAccessor> resources     = new List <IResourceAccessor>();
                    foreach (var res in currentStreamItem.TranscoderObject.Metadata.FilePaths)
                    {
                        var path = ResourcePath.Deserialize(res.Value);
                        if (mediaAccessor.LocalResourceProviders.TryGetValue(path.BasePathSegment.ProviderId, out var resourceProvider) &&
                            resourceProvider is IBaseResourceProvider baseProvider && baseProvider.TryCreateResourceAccessor(res.Value, out var accessor))
                        {
                            using (accessor)
                            {
                                if (accessor is IFileSystemResourceAccessor)
                                {
                                    currentStreamItem.TranscoderObject.StartStreaming();
                                    currentStreamItem.StreamContext = await MediaConverter.GetFileStreamAsync(path);

                                    return(currentStreamItem.StreamContext);
                                }
                            }
                        }
                    }
                }
            }

            return(null);
        }