コード例 #1
0
        /// <summary>
        /// Imports or refreshes a single file without a parent directory with the specified <paramref name="fileAccessor"/>.
        /// </summary>
        /// <param name="importJob">The import job being processed.</param>
        /// <param name="fileAccessor">Resource accessor for the file to import.</param>
        /// <param name="metadataExtractors">Metadata extractors to apply on the resource.</param>
        /// <param name="mediaBrowsing">Callback interface to the media library for the refresh import type.</param>
        /// <param name="resultHandler">Callback to notify the import result.</param>
        /// <param name="mediaAccessor">Convenience reference to the media accessor.</param>
        protected void ImportSingleFile(ImportJob importJob, IResourceAccessor fileAccessor,
                                        ICollection <IMetadataExtractor> metadataExtractors, IMediaBrowsing mediaBrowsing,
                                        IImportResultHandler resultHandler, IMediaAccessor mediaAccessor)
        {
            ResourcePath currentFilePath = fileAccessor.CanonicalLocalResourcePath;

            try
            {
                if (importJob.JobType == ImportJobType.Refresh)
                {
                    MediaItem mediaItem = mediaBrowsing.LoadLocalItem(currentFilePath,
                                                                      IMPORTER_MIA_ID_ENUMERATION, EMPTY_MIA_ID_ENUMERATION);
                    MediaItemAspect importerAspect;
                    if (mediaItem != null && mediaItem.Aspects.TryGetValue(ImporterAspect.ASPECT_ID, out importerAspect) &&
                        (DateTime)importerAspect[ImporterAspect.ATTR_LAST_IMPORT_DATE] > fileAccessor.LastChanged)
                    {
                        return;
                    }
                }
                ImportResource(fileAccessor, Guid.Empty, metadataExtractors, resultHandler, mediaAccessor);
            }
            catch (Exception e)
            {
                CheckSuspended(e); // Throw ImportAbortException if suspended - will skip warning and tagging job as erroneous
                ServiceRegistration.Get <ILogger>().Warn("ImporterWorker: Problem while importing resource '{0}'", e, currentFilePath);
                importJob.State = ImportJobState.Erroneous;
            }
        }
コード例 #2
0
        public void Execute()
        {
            IServerConnectionManager serverConnectionManager = ServiceRegistration.Get <IServerConnectionManager>();
            IContentDirectory        contentDirectory        = serverConnectionManager.ContentDirectory;
            SystemName homeServerSystem   = serverConnectionManager.LastHomeServerSystem;
            bool       localHomeServer    = homeServerSystem != null && homeServerSystem.IsLocalSystem();
            bool       homeServerConncted = contentDirectory != null;

            ILocalSharesManagement localSharesManagement = ServiceRegistration.Get <ILocalSharesManagement>();

            if (localHomeServer)
            {
                if (homeServerConncted && contentDirectory.GetShares(null, SharesFilter.All).Count == 0)
                {
                    IMediaAccessor mediaAccessor = ServiceRegistration.Get <IMediaAccessor>();
                    foreach (Share share in mediaAccessor.CreateDefaultShares())
                    {
                        ServerShares serverShareProxy = new ServerShares(share);
                        serverShareProxy.AddShare();
                    }
                }
            }
            else
            {
                if (localSharesManagement.Shares.Count == 0)
                {
                    localSharesManagement.SetupDefaultShares();
                }
            }
            // The shares config model listens to share update events from both the local shares management and the home server,
            // so we don't need to trigger an update of the shares lists here
        }
コード例 #3
0
        private static IEnumerable <IRelationshipRoleExtractor> GetLinkedRoleExtractors(IDictionary <Guid, IList <MediaItemAspect> > aspects)
        {
            IMediaAccessor mediaAccessor = ServiceRegistration.Get <IMediaAccessor>();

            return(mediaAccessor.LocalRelationshipExtractors.Values.SelectMany(r => r.RoleExtractors)
                   .Where(r => r.LinkedRoleAspects.All(a => aspects.ContainsKey(a))));
        }
コード例 #4
0
        /// <summary>
        /// Collects all fanart for the given media item using the registered <see cref="IMediaFanArtHandler"/>s
        /// </summary>
        /// <param name="mediaItemId">The id of the media item.</param>
        /// <param name="aspects">The aspects of the media item.</param>
        protected async Task CollectFanArt(Guid mediaItemId, IDictionary <Guid, IList <MediaItemAspect> > aspects)
        {
            try
            {
                if ((aspects?.Count ?? 0) == 0)
                {
                    return;
                }

                IMediaAccessor mediaAccessor = ServiceRegistration.Get <IMediaAccessor>();
                IEnumerable <IMediaFanArtHandler> handlers = mediaAccessor.LocalFanArtHandlers.Values.Where(h => h.FanArtAspects.Any(a => aspects.ContainsKey(a)));
                foreach (IMediaFanArtHandler handler in handlers)
                {
                    try
                    {
                        await handler.CollectFanArtAsync(mediaItemId, aspects);
                    }
                    catch (Exception ex)
                    {
                        ServiceRegistration.Get <ILogger>().Error("FanArtActionBlock: Error collecting fanart by handler {0} for media item {1}", ex, handler.Metadata.Name, mediaItemId);
                    }
                }
            }
            catch (Exception ex)
            {
                ServiceRegistration.Get <ILogger>().Error("FanArtActionBlock: Error collecting fanart for media item {0}.", ex, mediaItemId);
            }
        }
コード例 #5
0
        static SeriesMetadataExtractor()
        {
            MediaCategory  seriesCategory;
            IMediaAccessor mediaAccessor = ServiceRegistration.Get <IMediaAccessor>();

            if (!mediaAccessor.MediaCategories.TryGetValue(MEDIA_CATEGORY_NAME_SERIES, out seriesCategory))
            {
                seriesCategory = mediaAccessor.RegisterMediaCategory(MEDIA_CATEGORY_NAME_SERIES, new List <MediaCategory> {
                    DefaultMediaCategories.Video
                });
            }
            MEDIA_CATEGORIES.Add(seriesCategory);
            OnlineMatcherService.RegisterDefaultSeriesMatchers(MEDIA_CATEGORY_NAME_SERIES);
            OnlineMatcherService.RegisterDefaultSeriesSubtitleMatchers(MEDIA_CATEGORY_NAME_SERIES);

            // All non-default media item aspects must be registered
            IMediaItemAspectTypeRegistration miatr = ServiceRegistration.Get <IMediaItemAspectTypeRegistration>();

            miatr.RegisterLocallyKnownMediaItemAspectTypeAsync(TempSeriesAspect.Metadata);

            // Register reimport support
            miatr.RegisterLocallySupportedReimportMediaItemAspectTypeAsync(SeriesAspect.Metadata);
            miatr.RegisterLocallySupportedReimportMediaItemAspectTypeAsync(EpisodeAspect.Metadata);
            miatr.RegisterLocallySupportedReimportMediaItemAspectTypeAsync(VideoAspect.Metadata);
        }
コード例 #6
0
        protected VideoDriveHandler(DriveInfo driveInfo, IEnumerable <Guid> extractedMIATypeIds) : base(driveInfo)
        {
            IMediaAccessor    mediaAccessor = ServiceRegistration.Get <IMediaAccessor>();
            ResourcePath      rp            = LocalFsResourceProviderBase.ToResourcePath(driveInfo.Name);
            IResourceAccessor ra;

            if (!rp.TryCreateLocalResourceAccessor(out ra))
            {
                throw new ArgumentException(string.Format("Unable to access drive '{0}'", driveInfo.Name));
            }
            using (ra)
                _mediaItem = mediaAccessor.CreateLocalMediaItem(ra, mediaAccessor.GetMetadataExtractorsForMIATypes(extractedMIATypeIds));
            if (_mediaItem == null)
            {
                throw new Exception(string.Format("Could not create media item for drive '{0}'", driveInfo.Name));
            }

            MatchWithStubs(driveInfo, new MediaItem[] { _mediaItem });
            IEnumerable <MediaItem> processedItems = CertificationHelper.ProcessMediaItems(new MediaItem[] { _mediaItem });

            if (processedItems.Count() == 0)
            {
                _mediaItem = null;
                return;
            }
            _mediaItem = processedItems.First();
            SingleMediaItemAspect mia = null;

            MediaItemAspect.TryGetAspect(_mediaItem.Aspects, MediaAspect.Metadata, out mia);
            mia.SetAttribute(MediaAspect.ATTR_TITLE, mia.GetAttributeValue(MediaAspect.ATTR_TITLE) +
                             " (" + DriveUtils.GetDriveNameWithoutRootDirectory(driveInfo) + ")");
        }
コード例 #7
0
        /// <summary>
        /// Imports the resource with the given <paramref name="mediaItemAccessor"/>.
        /// </summary>
        /// <remarks>
        /// This method will be called for file resources as well as for directory resources because some metadata extractors
        /// extract their metadata from directories.
        /// </remarks>
        /// <param name="mediaItemAccessor">File or directory resource to be imported.</param>
        /// <param name="parentDirectoryId">Media item id of the parent directory, if present, else <see cref="Guid.Empty"/>.</param>
        /// <param name="metadataExtractors">Collection of metadata extractors to apply to the given resoure.</param>
        /// <param name="resultHandler">Callback to notify the import results.</param>
        /// <param name="mediaAccessor">Convenience reference to the media accessor.</param>
        /// <returns><c>true</c>, if metadata could be extracted from the given <paramref name="mediaItemAccessor"/>, else
        /// <c>false</c>.</returns>
        protected bool ImportResource(ImportJob importJob, IResourceAccessor mediaItemAccessor, Guid parentDirectoryId, ICollection <IMetadataExtractor> metadataExtractors,
                                      IImportResultHandler resultHandler, IMediaAccessor mediaAccessor)
        {
            const bool   forceQuickMode = false; // Allow extractions with probably longer runtime.
            ResourcePath path           = mediaItemAccessor.CanonicalLocalResourcePath;

            ImporterWorkerMessaging.SendImportMessage(ImporterWorkerMessaging.MessageType.ImportStatus, path);
            IDictionary <Guid, IList <MediaItemAspect> > aspects = mediaAccessor.ExtractMetadataAsync(mediaItemAccessor, metadataExtractors, forceQuickMode).Result;

            if (aspects == null)
            {
                // No metadata could be extracted
                return(false);
            }
            using (CancellationTokenSource cancelToken = new CancellationTokenSource())
            {
                try
                {
                    resultHandler.UpdateMediaItemAsync(parentDirectoryId, path, MediaItemAspect.GetAspects(aspects), importJob.JobType == ImportJobType.Refresh, importJob.BasePath);
                    resultHandler.DeleteUnderPathAsync(path);
                }
                catch
                {
                    cancelToken.Cancel();
                    throw;
                }
            }
            return(true);
        }
コード例 #8
0
        static UPnPError OnDoesResourceProviderSupportTreeListing(DvAction action, IList <object> inParams, out IList <object> outParams,
                                                                  CallContext context)
        {
            Guid              resourceProviderId = MarshallingHelper.DeserializeGuid((string)inParams[0]);
            IMediaAccessor    mediaAccessor      = ServiceRegistration.Get <IMediaAccessor>();
            IResourceProvider rp;
            bool              result = false;

            if (mediaAccessor.LocalResourceProviders.TryGetValue(resourceProviderId, out rp) && rp is IBaseResourceProvider)
            {
                IResourceAccessor rootAccessor;
                if (((IBaseResourceProvider)rp).TryCreateResourceAccessor("/", out rootAccessor))
                {
                    if (rootAccessor is IFileSystemResourceAccessor)
                    {
                        result = true;
                    }
                    rootAccessor.Dispose();
                }
            }
            outParams = new List <object> {
                result
            };
            return(null);
        }
コード例 #9
0
        public BaseScriptableMovieMetadataExtractor(string id)
        {
            try
            {
                bool loaded = _metadataExtractorCustomCategories.TryTake(out _category);

                List <MediaCategory> mediaCategories = new List <MediaCategory>();
                if (loaded)
                {
                    MediaCategory  mediaCategory;
                    IMediaAccessor mediaAccessor = ServiceRegistration.Get <IMediaAccessor>();
                    if (!mediaAccessor.MediaCategories.TryGetValue(_category, out mediaCategory))
                    {
                        mediaCategory = mediaAccessor.RegisterMediaCategory(_category, new List <MediaCategory> {
                            DefaultMediaCategories.Video
                        });
                    }
                    mediaCategories.Add(mediaCategory);
                }

                _metadata = new MetadataExtractorMetadata(new Guid(id), $"Scriptable movie metadata extractor ({(loaded ? _category : "Disabled")})", MetadataExtractorPriority.External, true,
                                                          mediaCategories, new MediaItemAspectMetadata[] { MediaAspect.Metadata, MovieAspect.Metadata });
            }
            catch (Exception ex)
            {
                ServiceRegistration.Get <ILogger>().Error("ScriptableMetadataExtractor: Error initializing metadata extractor", ex);
            }
        }
コード例 #10
0
        public void SetupDefaultShares()
        {
            IMediaAccessor mediaAccessor = ServiceRegistration.Get <IMediaAccessor>();

            foreach (Share share in mediaAccessor.CreateDefaultShares())
            {
                RegisterShare(share.BaseResourcePath, share.Name, share.UseShareWatcher, share.MediaCategories);
            }
        }
コード例 #11
0
        static UPnPError OnGetMediaCategoriesFromMetadataExtractors(DvAction action, IList <object> inParams, out IList <object> outParams,
                                                                    CallContext context)
        {
            IMediaAccessor mediaAccessor = ServiceRegistration.Get <IMediaAccessor>();

            outParams = new List <object> {
                mediaAccessor.MediaCategories.Values
            };
            return(null);
        }
コード例 #12
0
        protected ICollection <Guid> GetMetadataExtractorIdsForMediaCategories(IEnumerable <string> mediaCategories)
        {
            IMediaAccessor     mediaAccessor = ServiceRegistration.Get <IMediaAccessor>();
            ICollection <Guid> result        = new HashSet <Guid>();

            foreach (string mediaCategory in mediaCategories)
            {
                CollectionUtils.AddAll(result, mediaAccessor.GetMetadataExtractorsForCategory(mediaCategory));
            }
            return(result);
        }
コード例 #13
0
        static UPnPError OnGetAllBaseResourceProviderMetadata(DvAction action, IList <object> inParams, out IList <object> outParams,
                                                              CallContext context)
        {
            IMediaAccessor mediaAccessor = ServiceRegistration.Get <IMediaAccessor>();
            IEnumerable <ResourceProviderMetadata> metadata = mediaAccessor.LocalBaseResourceProviders.Select(resourceProvider => resourceProvider.Metadata);

            outParams = new List <object> {
                metadata
            };
            return(null);
        }
コード例 #14
0
        protected static IBaseResourceProvider GetResourceProvider(Guid resourceProviderId)
        {
            IMediaAccessor    mediaAccessor = ServiceRegistration.Get <IMediaAccessor>();
            IResourceProvider result;

            if (!mediaAccessor.LocalResourceProviders.TryGetValue(resourceProviderId, out result))
            {
                return(null);
            }
            return(result as IBaseResourceProvider);
        }
コード例 #15
0
        static MovieMetadataExtractor()
        {
            MediaCategory  movieCategory;
            IMediaAccessor mediaAccessor = ServiceRegistration.Get <IMediaAccessor>();

            if (!mediaAccessor.MediaCategories.TryGetValue(MEDIA_CATEGORY_NAME_MOVIE, out movieCategory))
            {
                movieCategory = mediaAccessor.RegisterMediaCategory(MEDIA_CATEGORY_NAME_MOVIE, new List <MediaCategory> {
                    DefaultMediaCategories.Video
                });
            }
            MEDIA_CATEGORIES.Add(movieCategory);
        }
コード例 #16
0
        static ArgusRecordingSeriesMetadataExtractor()
        {
            MediaCategory  seriesCategory;
            IMediaAccessor mediaAccessor = ServiceRegistration.Get <IMediaAccessor>();

            if (!mediaAccessor.MediaCategories.TryGetValue(MEDIA_CATEGORY_NAME_SERIES, out seriesCategory))
            {
                seriesCategory = mediaAccessor.RegisterMediaCategory(MEDIA_CATEGORY_NAME_SERIES, new List <MediaCategory> {
                    DefaultMediaCategories.Video
                });
            }
            SERIES_MEDIA_CATEGORIES.Add(seriesCategory);
        }
コード例 #17
0
        public static MediaItem CreateMediaItem(string filename)
        {
            IMediaAccessor     mediaAccessor   = ServiceRegistration.Get <IMediaAccessor>();
            IEnumerable <Guid> meIds           = mediaAccessor.GetMetadataExtractorsForMIATypes(NECESSARY_VIDEO_MIAS);
            ResourceLocator    resourceLocator = new ResourceLocator(LocalFsResourceProviderBase.ToResourcePath(filename));
            IResourceAccessor  ra = resourceLocator.CreateAccessor();

            if (ra == null)
            {
                return(null);
            }
            using (ra)
                return(mediaAccessor.CreateLocalMediaItem(ra, meIds));
        }
コード例 #18
0
        /// <summary>
        /// Tries to unfold the given <paramref name="fileAccessor"/> to a virtual directory.
        /// </summary>
        /// <param name="fileAccessor">File resource accessor to be used as input for a potential chained provider.
        /// The ownership of this resource accessor remains at the caller.</param>
        /// <param name="resultResourceAccessor">Chained resource accessor which was chained upon the given file resource.</param>
        public static bool TryUnfold(IFileSystemResourceAccessor fileAccessor, out IFileSystemResourceAccessor resultResourceAccessor)
        {
            IMediaAccessor mediaAccessor = ServiceRegistration.Get <IMediaAccessor>();

            foreach (IChainedResourceProvider cmp in mediaAccessor.LocalChainedResourceProviders)
            {
                if (cmp.TryChainUp(fileAccessor, "/", out resultResourceAccessor))
                {
                    return(true);
                }
            }
            resultResourceAccessor = null;
            return(false);
        }
コード例 #19
0
        static GameMetadataExtractor()
        {
            IMediaAccessor mediaAccessor = ServiceRegistration.Get <IMediaAccessor>();

            if (!mediaAccessor.MediaCategories.TryGetValue(GameCategory.CATEGORY_NAME, out _gameCategory))
            {
                _gameCategory = mediaAccessor.RegisterMediaCategory(GameCategory.CATEGORY_NAME, null);
            }
            MEDIA_CATEGORIES.Add(_gameCategory);
            // All non-default media item aspects must be registered
            IMediaItemAspectTypeRegistration miatr = ServiceRegistration.Get <IMediaItemAspectTypeRegistration>();

            miatr.RegisterLocallyKnownMediaItemAspectTypeAsync(GameAspect.Metadata);
        }
コード例 #20
0
        /// <summary>
        /// Imports or refreshes a single file without a parent directory with the specified <paramref name="resourceAccessor"/>.
        /// </summary>
        /// <param name="importJob">The import job being processed.</param>
        /// <param name="resourceAccessor">Resource accessor for the file to import.</param>
        /// <param name="metadataExtractors">Metadata extractors to apply on the resource.</param>
        /// <param name="mediaBrowsing">Callback interface to the media library for the refresh import type.</param>
        /// <param name="resultHandler">Callback to notify the import result.</param>
        /// <param name="mediaAccessor">Convenience reference to the media accessor.</param>
        protected void ImportSingleFile(ImportJob importJob, IResourceAccessor resourceAccessor,
                                        ICollection <IMetadataExtractor> metadataExtractors, IMediaBrowsing mediaBrowsing,
                                        IImportResultHandler resultHandler, IMediaAccessor mediaAccessor)
        {
            ResourcePath currentFilePath = resourceAccessor.CanonicalLocalResourcePath;

            try
            {
                ImportResource(importJob, resourceAccessor, Guid.Empty, metadataExtractors, resultHandler, mediaAccessor);
            }
            catch (Exception e)
            {
                CheckSuspended(e); // Throw ImportAbortException if suspended - will skip warning and tagging job as erroneous
                ServiceRegistration.Get <ILogger>().Warn("ImporterWorker: Problem while importing resource '{0}'", e, currentFilePath);
                importJob.State = ImportJobState.Erroneous;
            }
        }
コード例 #21
0
        static UPnPError OnGetResourceProviderMetadata(DvAction action, IList <object> inParams, out IList <object> outParams,
                                                       CallContext context)
        {
            Guid              resourceProviderId = MarshallingHelper.DeserializeGuid((string)inParams[0]);
            IMediaAccessor    mediaAccessor      = ServiceRegistration.Get <IMediaAccessor>();
            IResourceProvider rp;

            outParams = null;
            if (!mediaAccessor.LocalResourceProviders.TryGetValue(resourceProviderId, out rp))
            {
                return(new UPnPError(600, string.Format("No resource provider of id '{0}' present in system", resourceProviderId)));
            }
            outParams = new List <object> {
                rp.Metadata
            };
            return(null);
        }
コード例 #22
0
 /// <summary>
 /// Deletes all fanart for the given media item.
 /// </summary>
 /// <param name="mediaItemId"></param>
 protected Task DeleteFanArt(Guid mediaItemId)
 {
     try
     {
         //ToDo: Async deletion?
         IMediaAccessor mediaAccessor = ServiceRegistration.Get <IMediaAccessor>();
         foreach (IMediaFanArtHandler handler in mediaAccessor.LocalFanArtHandlers.Values)
         {
             handler.DeleteFanArt(mediaItemId);
         }
     }
     catch (Exception ex)
     {
         ServiceRegistration.Get <ILogger>().Error("FanArtActionBlock: Error deleting fanart for media item {0}.", ex, mediaItemId);
     }
     return(Task.CompletedTask);
 }
コード例 #23
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);
        }
コード例 #24
0
        static UPnPError OnExpandResourcePathFromString(DvAction action, IList <object> inParams, out IList <object> outParams,
                                                        CallContext context)
        {
            Guid              resourceProviderId = MarshallingHelper.DeserializeGuid((string)inParams[0]);
            string            pathStr            = (string)inParams[1];
            IMediaAccessor    mediaAccessor      = ServiceRegistration.Get <IMediaAccessor>();
            ResourcePath      result             = null;
            IResourceProvider rp;

            if (mediaAccessor.LocalResourceProviders.TryGetValue(resourceProviderId, out rp) && rp is IBaseResourceProvider)
            {
                result = ((IBaseResourceProvider)rp).ExpandResourcePathFromString(pathStr);
            }
            outParams = new List <object> {
                result == null ? null : result.Serialize()
            };
            return(null);
        }
コード例 #25
0
        static SeriesMetadataExtractor()
        {
            MediaCategory  seriesCategory;
            IMediaAccessor mediaAccessor = ServiceRegistration.Get <IMediaAccessor>();

            if (!mediaAccessor.MediaCategories.TryGetValue(MEDIA_CATEGORY_NAME_SERIES, out seriesCategory))
            {
                seriesCategory = mediaAccessor.RegisterMediaCategory(MEDIA_CATEGORY_NAME_SERIES, new List <MediaCategory> {
                    DefaultMediaCategories.Video
                });
            }
            MEDIA_CATEGORIES.Add(seriesCategory);

            // All non-default media item aspects must be registered
            IMediaItemAspectTypeRegistration miatr = ServiceRegistration.Get <IMediaItemAspectTypeRegistration>();

            miatr.RegisterLocallyKnownMediaItemAspectType(TempSeriesAspect.Metadata);
        }
コード例 #26
0
        /// <summary>
        /// Checks if a resource provider chain for this resource path can be created in the local system.
        /// This method only checks the availability of providers; it doesn't check if the given path is available
        /// in the providers.
        /// </summary>
        public void CheckValidLocalPath()
        {
            IMediaAccessor mediaAccessor = ServiceRegistration.Get <IMediaAccessor>();

            if (!IsAbsolute) // This will check the path itself. Below, we will check if the referenced resource providers implement the correct interfaces
            {
                throw new ArgumentException(string.Format(
                                                "Can only access media files at an absolute resource path (given relative path is '{0}')", Serialize()));
            }
            IEnumerator <ProviderPathSegment> enumer = _pathSegments.GetEnumerator();

            if (!enumer.MoveNext())
            {
                throw new UnexpectedStateException("Cannot build resource accessor for an empty resource path");
            }
            bool baseSegment = true;

            do
            {
                ProviderPathSegment pathSegment = enumer.Current;
                IResourceProvider   resourceProvider;
                if (!mediaAccessor.LocalResourceProviders.TryGetValue(pathSegment.ProviderId, out resourceProvider))
                {
                    throw new IllegalCallException("The resource provider with id '{0}' is not accessible in the current system", pathSegment.ProviderId);
                }
                if (baseSegment)
                {
                    IBaseResourceProvider baseProvider = resourceProvider as IBaseResourceProvider;
                    if (baseProvider == null)
                    {
                        throw new IllegalCallException("The resource provider with id '{0}' does not implement the {1} interface", pathSegment.ProviderId, typeof(IBaseResourceProvider).Name);
                    }
                    baseSegment = false;
                }
                else
                {
                    IChainedResourceProvider chainedProvider = resourceProvider as IChainedResourceProvider;
                    if (chainedProvider == null)
                    {
                        throw new IllegalCallException("The resource provider with id '{0}' does not implement the {1} interface", pathSegment.ProviderId, typeof(IChainedResourceProvider).Name);
                    }
                }
            } while (enumer.MoveNext());
        }
コード例 #27
0
        static MovieMetadataExtractor()
        {
            MediaCategory  movieCategory;
            IMediaAccessor mediaAccessor = ServiceRegistration.Get <IMediaAccessor>();

            if (!mediaAccessor.MediaCategories.TryGetValue(MEDIA_CATEGORY_NAME_MOVIE, out movieCategory))
            {
                movieCategory = mediaAccessor.RegisterMediaCategory(MEDIA_CATEGORY_NAME_MOVIE, new List <MediaCategory> {
                    DefaultMediaCategories.Video
                });
            }
            MEDIA_CATEGORIES.Add(movieCategory);

            // Register reimport support
            IMediaItemAspectTypeRegistration miatr = ServiceRegistration.Get <IMediaItemAspectTypeRegistration>();

            miatr.RegisterLocallySupportedReimportMediaItemAspectTypeAsync(MovieAspect.Metadata);
            miatr.RegisterLocallySupportedReimportMediaItemAspectTypeAsync(VideoAspect.Metadata);
        }
コード例 #28
0
        public IEnumerable <IResourceAccessor> GetResourceAccessors()
        {
            IMediaAccessor           mediaAccessor = ServiceRegistration.Get <IMediaAccessor>();
            List <IResourceAccessor> resources     = new List <IResourceAccessor>();

            foreach (var res in InputMediaFilePaths)
            {
                var path = ResourcePath.Deserialize(res.Value);
                if (TranscodeLiveAccessor.TRANSCODE_LIVE_PROVIDER_ID == path.BasePathSegment.ProviderId)
                {
                    resources.Add(new TranscodeLiveAccessor(Convert.ToInt32(path.BasePathSegment.Path)));
                }
                else if (path.TryCreateLocalResourceAccessor(out var accessor))
                {
                    resources.Add(accessor);
                }
            }
            return(resources);
        }
コード例 #29
0
        private static IDictionary <(Guid, Guid), IList <IRelationshipRoleExtractor> > GetExtractorsByRoleLinkedRole(IDictionary <Guid, IList <MediaItemAspect> > aspects)
        {
            IDictionary <(Guid, Guid), IList <IRelationshipRoleExtractor> > extractors = new Dictionary <(Guid, Guid), IList <IRelationshipRoleExtractor> >();
            IMediaAccessor mediaAccessor = ServiceRegistration.Get <IMediaAccessor>();

            foreach (IRelationshipExtractor extractor in mediaAccessor.LocalRelationshipExtractors.Values.OrderBy(r => (int)r.Metadata.Priority))
            {
                foreach (IRelationshipRoleExtractor roleExtractor in extractor.RoleExtractors.Where(r => r.RoleAspects.All(a => aspects.ContainsKey(a))))
                {
                    var key = (roleExtractor.Role, roleExtractor.LinkedRole);
                    IList <IRelationshipRoleExtractor> roleExtractors;
                    if (!extractors.TryGetValue(key, out roleExtractors))
                    {
                        extractors[key] = roleExtractors = new List <IRelationshipRoleExtractor>();
                    }
                    roleExtractors.Add(roleExtractor);
                }
            }
            return(extractors);
        }
コード例 #30
0
        protected VideoDriveHandler(DriveInfo driveInfo, IEnumerable <Guid> extractedMIATypeIds) : base(driveInfo)
        {
            IMediaAccessor    mediaAccessor = ServiceRegistration.Get <IMediaAccessor>();
            ResourcePath      rp            = LocalFsResourceProviderBase.ToResourcePath(driveInfo.Name);
            IResourceAccessor ra;

            if (!rp.TryCreateLocalResourceAccessor(out ra))
            {
                throw new ArgumentException(string.Format("Unable to access drive '{0}'", driveInfo.Name));
            }
            using (ra)
                _mediaItem = mediaAccessor.CreateLocalMediaItem(ra, mediaAccessor.GetMetadataExtractorsForMIATypes(extractedMIATypeIds));
            if (_mediaItem == null)
            {
                throw new Exception(string.Format("Could not create media item for drive '{0}'", driveInfo.Name));
            }
            MediaItemAspect mia = _mediaItem.Aspects[MediaAspect.ASPECT_ID];

            mia.SetAttribute(MediaAspect.ATTR_TITLE, mia.GetAttributeValue(MediaAspect.ATTR_TITLE) +
                             " (" + DriveUtils.GetDriveNameWithoutRootDirectory(driveInfo) + ")");
        }
コード例 #31
0
 /// <summary>
 /// Imports or refreshes a single file without a parent directory with the specified <paramref name="resourceAccessor"/>.
 /// </summary>
 /// <param name="importJob">The import job being processed.</param>
 /// <param name="resourceAccessor">Resource accessor for the file to import.</param>
 /// <param name="metadataExtractors">Metadata extractors to apply on the resource.</param>
 /// <param name="mediaBrowsing">Callback interface to the media library for the refresh import type.</param>
 /// <param name="resultHandler">Callback to notify the import result.</param>
 /// <param name="mediaAccessor">Convenience reference to the media accessor.</param>
 protected void ImportSingleFile(ImportJob importJob, IResourceAccessor resourceAccessor,
     ICollection<IMetadataExtractor> metadataExtractors, IMediaBrowsing mediaBrowsing,
     IImportResultHandler resultHandler, IMediaAccessor mediaAccessor)
 {
   ResourcePath currentFilePath = resourceAccessor.CanonicalLocalResourcePath;
   try
   {
     ImportResource(resourceAccessor, Guid.Empty, metadataExtractors, resultHandler, mediaAccessor);
   }
   catch (Exception e)
   {
     CheckSuspended(e); // Throw ImportAbortException if suspended - will skip warning and tagging job as erroneous
     ServiceRegistration.Get<ILogger>().Warn("ImporterWorker: Problem while importing resource '{0}'", e, currentFilePath);
     importJob.State = ImportJobState.Erroneous;
   }
 }
コード例 #32
0
 /// <summary>
 /// Imports the resource with the given <paramref name="mediaItemAccessor"/>.
 /// </summary>
 /// <remarks>
 /// This method will be called for file resources as well as for directory resources because some metadata extractors
 /// extract their metadata from directories.
 /// </remarks>
 /// <param name="mediaItemAccessor">File or directory resource to be imported.</param>
 /// <param name="parentDirectoryId">Media item id of the parent directory, if present, else <see cref="Guid.Empty"/>.</param>
 /// <param name="metadataExtractors">Collection of metadata extractors to apply to the given resoure.</param>
 /// <param name="resultHandler">Callback to notify the import results.</param>
 /// <param name="mediaAccessor">Convenience reference to the media accessor.</param>
 /// <returns><c>true</c>, if metadata could be extracted from the given <paramref name="mediaItemAccessor"/>, else
 /// <c>false</c>.</returns>
 protected bool ImportResource(IResourceAccessor mediaItemAccessor, Guid parentDirectoryId,
     ICollection<IMetadataExtractor> metadataExtractors, IImportResultHandler resultHandler, IMediaAccessor mediaAccessor)
 {
   const bool forceQuickMode = false; // Allow extractions with probably longer runtime.
   ResourcePath path = mediaItemAccessor.CanonicalLocalResourcePath;
   ImporterWorkerMessaging.SendImportMessage(ImporterWorkerMessaging.MessageType.ImportStatus, path);
   IDictionary<Guid, MediaItemAspect> aspects = mediaAccessor.ExtractMetadata(mediaItemAccessor, metadataExtractors, forceQuickMode);
   if (aspects == null)
     // No metadata could be extracted
     return false;
   resultHandler.UpdateMediaItem(parentDirectoryId, path, aspects.Values);
   resultHandler.DeleteUnderPath(path);
   return true;
 }
コード例 #33
0
 /// <summary>
 /// Imports or refreshes the directory with the specified <paramref name="directoryAccessor"/>. Sub directories will not
 /// be processed in this method.
 /// </summary>
 /// <param name="importJob">The import job being processed.</param>
 /// <param name="parentDirectoryId">Media item id of the parent directory, if present, else <see cref="Guid.Empty"/>.</param>
 /// <param name="directoryAccessor">Resource accessor for the directory to import.</param>
 /// <param name="metadataExtractors">Metadata extractors to apply on the resources.</param>
 /// <param name="mediaBrowsing">Callback interface to the media library for the refresh import type.</param>
 /// <param name="resultHandler">Callback to notify the import result.</param>
 /// <param name="mediaAccessor">Convenience reference to the media accessor.</param>
 /// <returns>Id of the directory's media item or <c>null</c>, if the given <paramref name="directoryAccessor"/>
 /// was imported as a media item or if an error occured. If <c>null</c> is returned, the directory import should be
 /// considered to be finished.</returns>
 protected Guid? ImportDirectory(ImportJob importJob, Guid parentDirectoryId, IFileSystemResourceAccessor directoryAccessor,
     ICollection<IMetadataExtractor> metadataExtractors, IMediaBrowsing mediaBrowsing,
     IImportResultHandler resultHandler, IMediaAccessor mediaAccessor)
 {
   ResourcePath currentDirectoryPath = directoryAccessor.CanonicalLocalResourcePath;
   try
   {
     ImporterWorkerMessaging.SendImportMessage(ImporterWorkerMessaging.MessageType.ImportStatus, currentDirectoryPath);
     if (ImportResource(directoryAccessor, parentDirectoryId, metadataExtractors, resultHandler, mediaAccessor))
       // The directory could be imported as a media item.
       // If the directory itself was identified as a normal media item, don't import its children.
       // Necessary for DVD directories, for example.
       return null;
     Guid directoryId = GetOrAddDirectory(directoryAccessor, parentDirectoryId, mediaBrowsing, resultHandler);
     IDictionary<string, MediaItem> path2Item = new Dictionary<string, MediaItem>();
     if (importJob.JobType == ImportJobType.Refresh)
     {
       foreach (MediaItem mediaItem in mediaBrowsing.Browse(directoryId,
           IMPORTER_PROVIDER_MIA_ID_ENUMERATION, EMPTY_MIA_ID_ENUMERATION))
       {
         MediaItemAspect providerResourceAspect;
         if (mediaItem.Aspects.TryGetValue(ProviderResourceAspect.ASPECT_ID, out providerResourceAspect))
           path2Item[providerResourceAspect.GetAttributeValue<string>(ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH)] = mediaItem;
       }
     }
     CheckImportStillRunning(importJob.State);
     ICollection<IFileSystemResourceAccessor> files = FileSystemResourceNavigator.GetFiles(directoryAccessor, false);
     if (files != null)
       foreach (IFileSystemResourceAccessor fileAccessor in files)
         using (fileAccessor)
         { // Add & update files
           ResourcePath currentFilePath = fileAccessor.CanonicalLocalResourcePath;
           string serializedFilePath = currentFilePath.Serialize();
           try
           {
             MediaItemAspect importerAspect;
             MediaItem mediaItem;
             if (importJob.JobType == ImportJobType.Refresh &&
                 path2Item.TryGetValue(serializedFilePath, out mediaItem) &&
                 mediaItem.Aspects.TryGetValue(ImporterAspect.ASPECT_ID, out importerAspect) &&
                 importerAspect.GetAttributeValue<DateTime>(ImporterAspect.ATTR_LAST_IMPORT_DATE) > fileAccessor.LastChanged)
             { // We can skip this file; it was imported after the last change time of the item
               path2Item.Remove(serializedFilePath);
               continue;
             }
             if (ImportResource(fileAccessor, directoryId, metadataExtractors, resultHandler, mediaAccessor))
               path2Item.Remove(serializedFilePath);
           }
           catch (Exception e)
           {
             CheckSuspended(e); // Throw ImportAbortException if suspended - will skip warning and tagging job as erroneous
             ServiceRegistration.Get<ILogger>().Warn("ImporterWorker: Problem while importing resource '{0}'", e, serializedFilePath);
             importJob.State = ImportJobState.Erroneous;
           }
           CheckImportStillRunning(importJob.State);
         }
     if (importJob.JobType == ImportJobType.Refresh)
     { // Remove remaining (= non-present) files
       foreach (string pathStr in path2Item.Keys)
       {
         ResourcePath path = ResourcePath.Deserialize(pathStr);
         try
         {
           IResourceAccessor ra;
           if (!path.TryCreateLocalResourceAccessor(out ra))
             throw new IllegalCallException("Unable to access resource path '{0}'", importJob.BasePath);
           using (ra)
           {
             IFileSystemResourceAccessor fsra = ra as IFileSystemResourceAccessor;
             if (fsra == null || !fsra.IsFile)
               // Don't touch directories because they will be imported in a different call of ImportDirectory
               continue;
           }
         }
         catch (IllegalCallException)
         {
           // This happens if the resource doesn't exist any more - we also catch missing directories here
         }
         // Delete all remaining items
         resultHandler.DeleteMediaItem(path);
         CheckImportStillRunning(importJob.State);
       }
     }
     return directoryId;
   }
   catch (ImportSuspendedException)
   {
     throw;
   }
   catch (ImportAbortException)
   {
     throw;
   }
   catch (UnauthorizedAccessException e)
   {
     // If the access to the file or folder was denied, simply continue with the others
     ServiceRegistration.Get<ILogger>().Warn("ImporterWorker: Problem accessing resource '{0}', continueing with one", e, currentDirectoryPath);
   }
   catch (Exception e)
   {
     CheckSuspended(e); // Throw ImportAbortException if suspended - will skip warning and tagging job as erroneous
     ServiceRegistration.Get<ILogger>().Warn("ImporterWorker: Problem while importing directory '{0}'", e, currentDirectoryPath);
     importJob.State = ImportJobState.Erroneous;
   }
   return null;
 }
コード例 #34
0
 /// <summary>
 /// Adds all media items which are found in the directory to the given <paramref name="directoryRA"/> or in any sub directory to
 /// the <paramref name="mediaItems"/> collection.
 /// </summary>
 /// <param name="directoryRA">Directory resource to be recursively examined.</param>
 /// <param name="mediaItems">Collection where the found media items are added.</param>
 /// <param name="metadataExtractorIds">Ids of the metadata extractors to be applied to the resources.
 /// See <see cref="IMediaAccessor.LocalMetadataExtractors"/>.</param>
 /// <param name="mediaAccessor">The media accessor of the system.</param>
 public static void AddLocalMediaItemsRecursive(IFileSystemResourceAccessor directoryRA, ICollection<MediaItem> mediaItems,
     IEnumerable<Guid> metadataExtractorIds, IMediaAccessor mediaAccessor)
 {
   ICollection<IFileSystemResourceAccessor> directoryRAs = FileSystemResourceNavigator.GetChildDirectories(directoryRA, false);
   if (directoryRAs != null)
     foreach (IFileSystemResourceAccessor subDirectoryRA in directoryRAs)
       using (subDirectoryRA)
         AddLocalMediaItemsRecursive(subDirectoryRA, mediaItems, metadataExtractorIds, mediaAccessor);
   ICollection<IFileSystemResourceAccessor> fileRAs = FileSystemResourceNavigator.GetFiles(directoryRA, false);
   if (fileRAs != null)
     foreach (IFileSystemResourceAccessor fileRA in fileRAs)
       using (fileRA)
       {
         MediaItem item = mediaAccessor.CreateLocalMediaItem(fileRA, metadataExtractorIds);
         if (item != null)
           mediaItems.Add(item);
       }
 }
コード例 #35
0
 /// <summary>
 /// Imports or refreshes a single file without a parent directory with the specified <paramref name="fileAccessor"/>.
 /// </summary>
 /// <param name="importJob">The import job being processed.</param>
 /// <param name="fileAccessor">Resource accessor for the file to import.</param>
 /// <param name="metadataExtractors">Metadata extractors to apply on the resource.</param>
 /// <param name="mediaBrowsing">Callback interface to the media library for the refresh import type.</param>
 /// <param name="resultHandler">Callback to notify the import result.</param>
 /// <param name="mediaAccessor">Convenience reference to the media accessor.</param>
 protected void ImportSingleFile(ImportJob importJob, IResourceAccessor fileAccessor,
     ICollection<IMetadataExtractor> metadataExtractors, IMediaBrowsing mediaBrowsing,
     IImportResultHandler resultHandler, IMediaAccessor mediaAccessor)
 {
   ResourcePath currentFilePath = fileAccessor.CanonicalLocalResourcePath;
   try
   {
     if (importJob.JobType == ImportJobType.Refresh)
     {
       MediaItem mediaItem = mediaBrowsing.LoadLocalItem(currentFilePath,
           IMPORTER_MIA_ID_ENUMERATION, EMPTY_MIA_ID_ENUMERATION);
       MediaItemAspect importerAspect;
       if (mediaItem != null && mediaItem.Aspects.TryGetValue(ImporterAspect.ASPECT_ID, out importerAspect) &&
           (DateTime) importerAspect[ImporterAspect.ATTR_LAST_IMPORT_DATE] > fileAccessor.LastChanged)
         return;
     }
     ImportResource(fileAccessor, Guid.Empty, metadataExtractors, resultHandler, mediaAccessor);
   }
   catch (Exception e)
   {
     CheckSuspended(e); // Throw ImportAbortException if suspended - will skip warning and tagging job as erroneous
     ServiceRegistration.Get<ILogger>().Warn("ImporterWorker: Problem while importing resource '{0}'", e, currentFilePath);
     importJob.State = ImportJobState.Erroneous;
   }
 }