Esempio n. 1
0
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services registration

            var container = new UnityContainer();

            var dataAccessRegistration = new DataAccessRegistration();
            var repositoryRegistation = new RepositoryRegistration();
            var serviceRegistration = new ServiceRegistration();

            dataAccessRegistration.Register(container);
            repositoryRegistation.Register(container);
            serviceRegistration.Register(container);

            config.DependencyResolver = new UnityResolver(container);

            config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false;

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
        public void Equals_ComparedToNull_AreNotEqual()
        {
            var firstRegistration = new ServiceRegistration();
            firstRegistration.ServiceType = typeof(int);
            firstRegistration.ServiceName = string.Empty;

            Assert.IsFalse(firstRegistration.Equals(null));
        }
        public void Equals_SameTypeSameServiceName_AreEqual()
        {
            var firstRegistration = new ServiceRegistration();
            firstRegistration.ServiceType = typeof(int);
            firstRegistration.ServiceName = string.Empty;

            var secondRegistration = new ServiceRegistration();
            secondRegistration.ServiceType = typeof(int);
            secondRegistration.ServiceName = string.Empty;

            Assert.AreEqual(firstRegistration, secondRegistration);
        }
        public void Equals_SameTypeDifferentServiceName_AreNotEqual()
        {
            var firstRegistration = new ServiceRegistration();
            firstRegistration.ServiceType = typeof(int);
            firstRegistration.ServiceName = string.Empty;

            var secondRegistration = new ServiceRegistration();
            secondRegistration.ServiceType = typeof(int);
            secondRegistration.ServiceName = "SomeName";

            Assert.NotEqual(firstRegistration, secondRegistration);
        }
        private bool Match(ServiceRegistration sr)
        {
            if (sr.ImplementingType != null)
            {
                var methods = sr.ImplementingType.GetMethods();

                if (methods.Select(methodInfo => methodInfo.GetCustomAttributes(typeof(AbstractAspectAttribute), true)).Any(attributes => attributes.Length > 0))
                {
                    return true;
                }
            }

            return false;
        }
Esempio n. 6
0
 public int CompareTo(StringId other)
 {
     return(string.Compare(ToString(), other.ToString(), false, ServiceRegistration.Get <ILocalization>().CurrentCulture));
 }
 /// <summary>
 /// Schedules an asynchronous call to <see cref="CheckMediaWorkflowStates_NoLock"/> at the global thread pool.
 /// </summary>
 protected void CheckMediaWorkflowStates_Async()
 {
     ServiceRegistration.Get <IThreadPool>().Add(new DoWorkHandler(CheckMediaWorkflowStates_NoLock), "PlayerContextManager: CheckMediaWorkflowStates");
 }
        public bool Play(MediaItem mediaItem, StartTime startTime)
        {
            IPlayer player = null;

            try
            {
                IReusablePlayer rp;
                lock (SyncObj)
                {
                    CheckActive();
                    player = _player;
                    rp     = _player as IReusablePlayer;
                }
                if (rp != null)
                {
                    if (rp.NextItem(mediaItem, startTime))
                    {
                        OnPlayerStarted(rp);
                        return(true);
                    }
                }
                ReleasePlayer_NoLock();
                ICollection <Exception> exceptions;
                player = _playerManager.BuildPlayer_NoLock(mediaItem, out exceptions);
                if (player == null)
                {
                    HandleUnableToPlay(mediaItem, exceptions);
                    OnPlaybackError(null);
                }
                else
                {
                    IMediaPlaybackControl mpc;
                    IDisposable           disposePlayer = null;
                    lock (SyncObj)
                    {
                        if (_player != null)
                        {
                            disposePlayer = _player as IDisposable; // If we got a race condition between the locks
                        }
                        _player = player;
                        mpc     = player as IMediaPlaybackControl;
                    }
                    RegisterPlayerEvents_NoLock(player);
                    CheckAudio_NoLock();
                    if (disposePlayer != null)
                    {
                        disposePlayer.Dispose();
                    }
                    OnPlayerStarted(player);

                    // Handling of resume info.
                    object resumeObject;
                    if (ContextVariables.TryGetValue(PlayerContext.KEY_RESUME_STATE, out resumeObject))
                    {
                        IResumeState     resumeState     = (IResumeState)resumeObject;
                        IResumablePlayer resumablePlayer = player as IResumablePlayer;
                        if (resumablePlayer != null)
                        {
                            resumablePlayer.SetResumeState(resumeState);
                        }
                    }

                    if (mpc != null)
                    {
                        mpc.Resume();
                    }
                    return(true);
                }
                return(false);
            }
            catch (Exception e)
            {
                ServiceRegistration.Get <ILogger>().Warn("PlayerSlotController: Error playing '{0}'", e, mediaItem);
                IDisposable disposePlayer = player as IDisposable;
                if (disposePlayer != null)
                {
                    disposePlayer.Dispose();
                }
                return(false);
            }
        }
Esempio n. 9
0
        public void ExitModelContext(NavigationContext oldContext, NavigationContext newContext)
        {
            INotificationService notificationService = ServiceRegistration.Get <INotificationService>();

            notificationService.CheckForTimeouts = true;
        }
Esempio n. 10
0
        public void GoToNotification()
        {
            IWorkflowManager workflowManager = ServiceRegistration.Get <IWorkflowManager>();

            workflowManager.NavigatePush(Consts.WF_STATE_ID_WATCH_NOTIFICATIONS);
        }
        /// <summary>
        /// Returns all child directories of the given directory.
        /// </summary>
        /// <remarks>
        /// This will return all native child directories of the given directory together with all virtual child
        /// directories. The native child directories are taken directly from the given <paramref name="directoryAccessor"/>,
        /// the virtual child directories are obtained by taking the root directories of each chained resource provider applied
        /// to the child files of the given directory.
        /// If, for example, the given <paramref name="directoryAccessor"/> contains a child directory "A" and a child
        /// archive file "B" which can work as input for an installed archive provider, providing the root directory "C"
        /// of that archive, this method will return the resource accessors for directories "A" and "C".
        /// </remarks>
        /// <param name="directoryAccessor">Directory resource accessor to get all child directories for.</param>
        /// <param name="showSystemResources">If set to <c>true</c>, system resources like the virtual drives and directories of the
        /// <see cref="IResourceMountingService"/> will also be returned, else removed from the result value.</param>
        /// <returns>Collection of directory accessors for all native and virtual child directories or <c>null</c>,
        /// if the given <paramref name="directoryAccessor"/> is not a <see cref="IFileSystemResourceAccessor"/> and
        /// if there is no chained resource provider to unfold the given directory.</returns>
        public static ICollection <IFileSystemResourceAccessor> GetChildDirectories(IFileSystemResourceAccessor directoryAccessor, bool showSystemResources)
        {
            IResourceMountingService    resourceMountingService = ServiceRegistration.Get <IResourceMountingService>();
            IFileSystemResourceAccessor chainedResourceAccesor; // Needed in multiple source locations, that's why we declare it here
            ICollection <IFileSystemResourceAccessor> childDirectories = directoryAccessor.GetChildDirectories();
            ICollection <IFileSystemResourceAccessor> result           = new List <IFileSystemResourceAccessor>();

            if (childDirectories != null)
            {
                // Directories are maybe filtered and then just added
                foreach (IFileSystemResourceAccessor childDirectoryAccessor in childDirectories)
                {
                    if (!showSystemResources && resourceMountingService.IsVirtualResource(childDirectoryAccessor.CanonicalLocalResourcePath))
                    {
                        childDirectoryAccessor.Dispose();
                        continue;
                    }
                    result.Add(childDirectoryAccessor);
                }
            }
            ICollection <IFileSystemResourceAccessor> files = directoryAccessor.GetFiles();

            if (files != null)
            {
                // For files, we try to chain up chained resource providers
                foreach (IFileSystemResourceAccessor fileAccessor in files)
                {
                    using (fileAccessor)
                    {
                        if (!showSystemResources && resourceMountingService.IsVirtualResource(fileAccessor.CanonicalLocalResourcePath))
                        {
                            continue;
                        }
                        if (TryUnfold(fileAccessor, out chainedResourceAccesor))
                        {
                            if (!chainedResourceAccesor.IsFile)
                            {
                                result.Add(chainedResourceAccesor);
                            }
                            else
                            {
                                chainedResourceAccesor.Dispose();
                            }
                        }
                        // Simply ignore files because we only want to return directories
                    }
                }
            }
            if (result.Count > 0)
            {
                return(result);
            }
            // Try to unfold simple resource
            if (TryUnfold(directoryAccessor, out chainedResourceAccesor))
            {
                if (!chainedResourceAccesor.IsFile)
                {
                    return(new List <IFileSystemResourceAccessor>(new IFileSystemResourceAccessor[] { chainedResourceAccesor }));
                }
                chainedResourceAccesor.Dispose();
            }
            return(null);
        }
Esempio n. 12
0
        /// <summary>
        /// Unregisters the service with the specified name.
        /// </summary>
        /// <param name="serviceType">The type of service to be removed.</param>
        /// <param name="key">
        /// The name the object was registered with. Can be <see langword="null"/> or empty. 
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="serviceType"/> is <see langword="null"/>.
        /// </exception>
        public void Unregister(Type serviceType, string key)
        {
            ThrowIfDisposed();

            if (serviceType == null)
                throw new ArgumentNullException(nameof(serviceType));

            var registration = new ServiceRegistration(serviceType, key);
            lock (_registry)
            {
                ServiceEntry entry;
                if (_registry.TryGetValue(registration, out entry))
                {
                    DisposeInstances(entry);
                    _registry.Remove(registration);
                }
            }
        }
Esempio n. 13
0
 public void Init()
 {
     ServiceRegistration.Set <ILocalization>(new NoLocalization());
 }
 public string GetModelURL(CultureInfo culture)
 {
     return(StringUtils.TrimToNull(ServiceRegistration.Get <ILocalization>().ToString(RES_MODEL_URL)));
 }
 public string GetModelDescription(CultureInfo culture)
 {
     return(StringUtils.TrimToNull(ServiceRegistration.Get <ILocalization>().ToString(RES_MODEL_DESCRIPTION)));
 }
 public string GetManufacturerURL(CultureInfo culture)
 {
     return(StringUtils.TrimToNull(ServiceRegistration.Get <ILocalization>().ToString(RES_MANUFACTURER_URL)));
 }
Esempio n. 17
0
        protected bool TryMatch(string seriesNameOrImdbId, bool isImdbId, bool cacheOnly, out TvdbSeries seriesDetail, int tvdbid = 0)
        {
            seriesDetail = null;
            try
            {
                // Prefer memory cache
                CheckCacheAndRefresh();
                if (_memoryCache.TryGetValue(seriesNameOrImdbId, out seriesDetail))
                {
                    if (tvdbid == 0 || seriesDetail.Id == tvdbid)
                    {
                        return(true);
                    }
                }

                // Load cache or create new list
                List <SeriesMatch> matches;
                lock (_syncObj)
                    matches = Settings.Load <List <SeriesMatch> >(MatchesSettingsFile) ?? new List <SeriesMatch>();

                // Init empty
                seriesDetail = null;

                // Use cached values before doing online query
                SeriesMatch match = matches.Find(m =>
                                                 (
                                                     string.Equals(m.ItemName, seriesNameOrImdbId, StringComparison.OrdinalIgnoreCase) ||
                                                     string.Equals(m.TvDBName, seriesNameOrImdbId, StringComparison.OrdinalIgnoreCase)
                                                 ) && (tvdbid == 0 || m.Id == tvdbid));

                ServiceRegistration.Get <ILogger>().Debug("SeriesTvDbMatcher: Try to lookup series \"{0}\" from cache: {1}", seriesNameOrImdbId, match != null && match.Id != 0);

                // Try online lookup
                if (!Init())
                {
                    return(false);
                }

                // If this is a known series, only return the series details (including episodes).
                if (match != null)
                {
                    return(match.Id != 0 && _tv.GetSeries(match.Id, true, out seriesDetail));
                }

                if (cacheOnly)
                {
                    return(false);
                }

                TvdbSearchResult matchedSeries = null;
                bool             foundResult   = false;
                if (tvdbid != 0)
                {
                    foundResult = _tv.GetSeries(tvdbid, true, out seriesDetail);
                }
                else
                if (isImdbId)
                {
                    // If we got an IMDBID, use it to lookup by key directly
                    _tv.GetSeries(seriesNameOrImdbId, out matchedSeries);
                }
                else
                {
                    // Otherwise we try to find unique series by name
                    List <TvdbSearchResult> series;
                    if (_tv.SearchSeriesUnique(seriesNameOrImdbId, out series))
                    {
                        matchedSeries = series[0];
                    }
                }

                if (matchedSeries != null)
                {
                    ServiceRegistration.Get <ILogger>().Debug("SeriesTvDbMatcher: Found unique online match for \"{0}\": \"{1}\" [Lang: {2}]", seriesNameOrImdbId, matchedSeries.SeriesName, matchedSeries.Language);
                    foundResult = _tv.GetSeries(matchedSeries.Id, true, out seriesDetail);
                }
                if (foundResult)
                {
                    ServiceRegistration.Get <ILogger>().Debug("SeriesTvDbMatcher: Loaded details for \"{0}\"", seriesDetail.SeriesName);
                    // Add this match to cache
                    SeriesMatch onlineMatch = new SeriesMatch
                    {
                        ItemName = seriesNameOrImdbId,
                        Id       = seriesDetail.Id,
                        TvDBName = seriesDetail.SeriesName
                    };

                    // Save cache
                    _storage.TryAddMatch(onlineMatch);
                    return(true);
                }

                ServiceRegistration.Get <ILogger>().Debug("SeriesTvDbMatcher: No unique match found for \"{0}\"", seriesNameOrImdbId);
                // Also save "non matches" to avoid retrying
                _storage.TryAddMatch(new SeriesMatch {
                    ItemName = seriesNameOrImdbId
                });
                return(false);
            }
            catch (Exception ex)
            {
                ServiceRegistration.Get <ILogger>().Debug("SeriesTvDbMatcher: Exception while processing series {0}", ex, seriesNameOrImdbId);
                return(false);
            }
            finally
            {
                if (seriesDetail != null)
                {
                    _memoryCache.TryAdd(seriesNameOrImdbId, seriesDetail);
                }
            }
        }
Esempio n. 18
0
        public virtual Task <bool> TryExtractMetadataAsync(IResourceAccessor mediaItemAccessor, IDictionary <Guid, IList <MediaItemAspect> > extractedAspectData, bool forceQuickMode)
        {
            try
            {
                IResourceAccessor metaFileAccessor;
                if (!CanExtract(mediaItemAccessor, extractedAspectData, out metaFileAccessor))
                {
                    return(Task.FromResult(false));
                }

                Tags tags;
                using (metaFileAccessor)
                {
                    using (Stream metaStream = ((IFileSystemResourceAccessor)metaFileAccessor).OpenRead())
                        tags = (Tags)GetTagsXmlSerializer().Deserialize(metaStream);
                }

                //Assign all tags to the aspects for both tv and radio recordings
                string value;
                MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_ISVIRTUAL, false);
                if (TryGet(tags, TAG_TITLE, out value) && !string.IsNullOrEmpty(value))
                {
                    if (value.Equals("manual", StringComparison.InvariantCultureIgnoreCase))
                    {
                        value = ResourcePathHelper.GetFileNameWithoutExtension(metaFileAccessor.Path);
                    }

                    MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_TITLE, value);
                    MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_SORT_TITLE, BaseInfo.GetSortTitle(value));
                }

                if (TryGet(tags, TAG_CHANNEL, out value))
                {
                    MediaItemAspect.SetAttribute(extractedAspectData, RecordingAspect.ATTR_CHANNEL, value);
                }

                // Recording date formatted: 2011-11-04 20:55
                DateTime tmpValue;
                DateTime?recordingStart = null;
                DateTime?recordingEnd   = null;
                DateTime?programStart   = null;
                DateTime?programEnd     = null;

                // First try to read program start and end times, they will be preferred.
                if (TryGet(tags, TAG_PROGRAMSTARTTIME, out value) && DateTime.TryParse(value, out tmpValue))
                {
                    programStart = tmpValue;
                }

                if (TryGet(tags, TAG_PROGRAMENDTIME, out value) && DateTime.TryParse(value, out tmpValue))
                {
                    programEnd = tmpValue;
                }

                if (TryGet(tags, TAG_STARTTIME, out value) && DateTime.TryParse(value, out tmpValue))
                {
                    recordingStart = tmpValue;
                }

                if (TryGet(tags, TAG_ENDTIME, out value) && DateTime.TryParse(value, out tmpValue))
                {
                    recordingEnd = tmpValue;
                }

                // Correct start time if recording started before the program (skip pre-recording offset)
                if (programStart.HasValue && recordingStart.HasValue && programStart > recordingStart)
                {
                    recordingStart = programStart;
                }

                // Correct end time if recording ended after the program (skip the post-recording offset)
                if (programEnd.HasValue && recordingEnd.HasValue && programEnd < recordingEnd)
                {
                    recordingEnd = programEnd;
                }

                if (recordingStart.HasValue)
                {
                    MediaItemAspect.SetAttribute(extractedAspectData, RecordingAspect.ATTR_STARTTIME, recordingStart.Value);
                }
                if (recordingEnd.HasValue)
                {
                    MediaItemAspect.SetAttribute(extractedAspectData, RecordingAspect.ATTR_ENDTIME, recordingEnd.Value);
                    RecordingUtils.CheckAndPrepareAspectRefresh(extractedAspectData);
                }

                if (extractedAspectData.ContainsKey(VideoAspect.ASPECT_ID)) //Only add video information for actual video recordings
                {
                    // Force MimeType
                    IList <MultipleMediaItemAspect> providerAspects;
                    MediaItemAspect.TryGetAspects(extractedAspectData, ProviderResourceAspect.Metadata, out providerAspects);
                    foreach (MultipleMediaItemAspect aspect in providerAspects)
                    {
                        aspect.SetAttribute(ProviderResourceAspect.ATTR_MIME_TYPE, "slimtv/video");
                    }

                    MediaItemAspect.SetAttribute(extractedAspectData, VideoAspect.ATTR_ISDVD, false);
                    if (TryGet(tags, TAG_PLOT, out value))
                    {
                        MediaItemAspect.SetAttribute(extractedAspectData, VideoAspect.ATTR_STORYPLOT, value);
                        Match yearMatch = _yearMatcher.Match(value);
                        int   guessedYear;
                        if (int.TryParse(yearMatch.Value, out guessedYear))
                        {
                            MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_RECORDINGTIME, new DateTime(guessedYear, 1, 1));
                        }
                    }
                    if (TryGet(tags, TAG_GENRE, out value) && !string.IsNullOrEmpty(value?.Trim()))
                    {
                        List <GenreInfo> genreList = new List <GenreInfo>(new GenreInfo[] { new GenreInfo {
                                                                                                Name = value.Trim()
                                                                                            } });
                        IGenreConverter converter = ServiceRegistration.Get <IGenreConverter>();
                        foreach (var genre in genreList)
                        {
                            if (!genre.Id.HasValue && converter.GetGenreId(genre.Name, GenreCategory.Movie, null, out int genreId))
                            {
                                genre.Id = genreId;
                            }
                        }
                        MultipleMediaItemAspect genreAspect = MediaItemAspect.CreateAspect(extractedAspectData, GenreAspect.Metadata);
                        genreAspect.SetAttribute(GenreAspect.ATTR_ID, genreList[0].Id);
                        genreAspect.SetAttribute(GenreAspect.ATTR_GENRE, genreList[0].Name);
                    }
                }
                else //Add comment for radio recordings
                {
                    if (TryGet(tags, TAG_PLOT, out value))
                    {
                        MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_COMMENT, value);
                    }
                    if (TryGet(tags, TAG_GENRE, out value) && !string.IsNullOrEmpty(value?.Trim()))
                    {
                        List <GenreInfo> genreList = new List <GenreInfo>(new GenreInfo[] { new GenreInfo {
                                                                                                Name = value.Trim()
                                                                                            } });
                        IGenreConverter converter = ServiceRegistration.Get <IGenreConverter>();
                        foreach (var genre in genreList)
                        {
                            if (!genre.Id.HasValue && converter.GetGenreId(genre.Name, GenreCategory.Music, null, out int genreId))
                            {
                                genre.Id = genreId;
                            }
                        }
                        MultipleMediaItemAspect genreAspect = MediaItemAspect.CreateAspect(extractedAspectData, GenreAspect.Metadata);
                        genreAspect.SetAttribute(GenreAspect.ATTR_ID, genreList[0].Id);
                        genreAspect.SetAttribute(GenreAspect.ATTR_GENRE, genreList[0].Name);
                    }
                }

                return(Task.FromResult(true));
            }
            catch (Exception e)
            {
                // Only log at the info level here - And simply return false. This lets the caller know that we
                // couldn't perform our task here.
                ServiceRegistration.Get <ILogger>().Info("Tve3RecordingMetadataExtractor: Exception reading resource '{0}' (Text: '{1}')", mediaItemAccessor.CanonicalLocalResourcePath, e.Message);
            }
            return(Task.FromResult(false));
        }
 public void ToString_WithNullProperty_ReturnsEasyToReadRepresentation()
 {
     var sr = new ServiceRegistration();
     sr.ServiceType = typeof(IFoo);
     sr.ServiceName = "AnotherFoo";
     sr.ImplementingType = null;
     var toString = sr.ToString();
     Assert.Equal("ServiceType: 'LightInject.SampleLibrary.IFoo', ServiceName: 'AnotherFoo', ImplementingType: '', Lifetime: 'Transient'", toString);
 }
Esempio n. 20
0
        /// <summary>
        /// Adds the TsReader filter to the graph.
        /// </summary>
        protected override void AddSourceFilter()
        {
            // Render the file
            _sourceFilter = FilterLoader.LoadFilterFromDll("TsReader.ax", typeof(TsReader).GUID, true);

            IFileSourceFilter fileSourceFilter = (IFileSourceFilter)_sourceFilter;
            ITsReader         tsReader         = (ITsReader)_sourceFilter;

            tsReader.SetRelaxedMode(1);
            tsReader.SetTsReaderCallback(this);
            tsReader.SetRequestAudioChangeCallback(this);

            _graphBuilder.AddFilter(_sourceFilter, TSREADER_FILTER_NAME);

            _subtitleRenderer = new SubtitleRenderer(OnTextureInvalidated);
            _subtitleFilter   = _subtitleRenderer.AddSubtitleFilter(_graphBuilder);
            if (_subtitleFilter != null)
            {
                _subtitleRenderer.RenderSubtitles = true;
                _subtitleRenderer.SetPlayer(this);
            }

            if (_resourceLocator.NativeResourcePath.IsNetworkResource)
            {
                // _resourceAccessor points to an rtsp:// stream or network file
                var sourcePathOrUrl = SourcePathOrUrl;

                if (sourcePathOrUrl == null)
                {
                    throw new IllegalCallException("The TsVideoPlayer can only play network resources of type INetworkResourceAccessor");
                }

                ServiceRegistration.Get <ILogger>().Debug("{0}: Initializing for stream '{1}'", PlayerTitle, sourcePathOrUrl);

                IDisposable accessEnsurer = null;
                if (IsLocalFilesystemResource)
                {
                    accessEnsurer = ((ILocalFsResourceAccessor)_resourceAccessor).EnsureLocalFileSystemAccess();
                }
                using (accessEnsurer)
                {
                    int hr = fileSourceFilter.Load(SourcePathOrUrl, null);
                    new HRESULT(hr).Throw();
                }
            }
            else
            {
                // _resourceAccessor points to a local or remote mapped .ts file
                _localFsRaHelper = new LocalFsResourceAccessorHelper(_resourceAccessor);
                var localFileSystemResourceAccessor = _localFsRaHelper.LocalFsResourceAccessor;

                if (localFileSystemResourceAccessor == null)
                {
                    throw new IllegalCallException("The TsVideoPlayer can only play file resources of type ILocalFsResourceAccessor");
                }

                using (localFileSystemResourceAccessor.EnsureLocalFileSystemAccess())
                {
                    ServiceRegistration.Get <ILogger>().Debug("{0}: Initializing for stream '{1}'", PlayerTitle, localFileSystemResourceAccessor.LocalFileSystemPath);
                    int hr = fileSourceFilter.Load(localFileSystemResourceAccessor.LocalFileSystemPath, null);
                    new HRESULT(hr).Throw();
                }
            }
            // Init GraphRebuilder
            _graphRebuilder = new GraphRebuilder(_graphBuilder, _sourceFilter, OnAfterGraphRebuild)
            {
                PlayerName = PlayerTitle
            };
        }
        /// <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 (mediaType != FanArtMediaTypes.ChannelTv && mediaType != FanArtMediaTypes.ChannelRadio)
            {
                return(false);
            }

            try
            {
                string designsFolder = _designsFolder ?? FileUtils.BuildAssemblyRelativePath("Designs");

                ChannelType  logoChannelType = mediaType == FanArtMediaTypes.ChannelTv ? ChannelType.Tv : ChannelType.Radio;
                ThemeHandler themeHandler    = new ThemeHandler();
                Theme        theme           = themeHandler.Load(Path.Combine(designsFolder, _settings.LogoTheme));

                string logoFolder   = Path.Combine(_dataFolder, string.Format("{0}-{1}-{2}", logoChannelType, theme.DesignName, theme.ThemeName));
                string logoFileName = Path.Combine(logoFolder, FileUtils.GetSafeFilename(string.Format("{0}.png", name)));

                if (!Directory.Exists(logoFolder))
                {
                    Directory.CreateDirectory(logoFolder);
                }

                if (File.Exists(logoFileName) && IsCacheValid(theme, logoFileName))
                {
                    return(BuildLogoResourceLocatorAndReturn(ref result, logoFileName));
                }

                LogoProcessor processor = new LogoProcessor {
                    DesignsFolder = designsFolder
                };

                // From repository
                using (var repo = new LogoRepository {
                    RepositoryUrl = _settings.RepositoryUrl
                })
                {
                    var stream = repo.Download(name, logoChannelType, _country.TwoLetterISORegionName);
                    if (stream == null)
                    {
                        return(BuildLogoResourceLocatorAndReturn(ref result, logoFileName));
                    }
                    using (stream)
                    {
                        // First download and process the new logo, but keep the existing file if something fails.
                        string tmpLogoFileName = Path.ChangeExtension(logoFileName, ".tmplogo");
                        if (processor.CreateLogo(theme, stream, tmpLogoFileName))
                        {
                            if (File.Exists(logoFileName))
                            {
                                File.Delete(logoFileName);
                            }
                            File.Move(tmpLogoFileName, logoFileName);
                        }
                        return(BuildLogoResourceLocatorAndReturn(ref result, logoFileName));
                    }
                }
            }
            catch (Exception ex)
            {
                ServiceRegistration.Get <ILogger>().Error("SlimTv Logos: Error processing logo image.", ex);
            }
            return(false);
        }
    /// <summary>
    /// Loads the plugin descriptor file (plugin.xml) from a plugin directory.
    /// </summary>
    /// <param name="pluginDirectoryPath">Root directory path of the plugin to load the metadata.</param>
    /// <returns><c>true</c>, if the plugin descriptor could successfully be loaded, else <c>false</c>.
    /// </returns>
    protected bool Load(string pluginDirectoryPath)
    {
      string path = Path.Combine(pluginDirectoryPath, PLUGIN_META_FILE);
      if (!File.Exists(path))
        return false;
      _pluginFilePath = path;
      try
      {
        using (Stream pluginFileStream = File.OpenRead(_pluginFilePath))
        {
          XPathDocument doc = new XPathDocument(pluginFileStream);
          XPathNavigator nav = doc.CreateNavigator();
          nav.MoveToChild(XPathNodeType.Element);
          if (nav.LocalName != "Plugin")
            throw new ArgumentException(
                "File is no plugin descriptor file (document element must be 'Plugin')");

          bool versionOk = false;
          bool pluginIdSet = false;
          XPathNavigator attrNav = nav.Clone();
          if (attrNav.MoveToFirstAttribute())
            do
            {
              switch (attrNav.Name)
              {
                case "DescriptorVersion":
                  Versions.CheckVersionCompatible(attrNav.Value, PLUGIN_DESCRIPTOR_VERSION_MAJOR, MIN_PLUGIN_DESCRIPTOR_VERSION_MINOR);
                  //string specVersion = attr.Value; <- if needed
                  versionOk = true;
                  break;
                case "Name":
                  _name = attrNav.Value;
                  break;
                case "PluginId":
                  _pluginId = new Guid(attrNav.Value);
                  pluginIdSet = true;
                  break;
                case "Author":
                  _author = attrNav.Value;
                  break;
                case "Copyright":
                  _copyright = attrNav.Value;
                  break;
                case "Description":
                  _description = attrNav.Value;
                  break;
                case "AutoActivate":
                  _autoActivate = Boolean.Parse(attrNav.Value);
                  break;
                default:
                  throw new ArgumentException("'Plugin' element doesn't support an attribute '" + attrNav.Name + "'");
              }
            } while (attrNav.MoveToNextAttribute());
          if (!versionOk)
            throw new ArgumentException("'Version' attribute not found");

          if (!pluginIdSet)
            throw new ArgumentException("'PluginId' attribute not found");

          XPathNavigator childNav = nav.Clone();
          if (childNav.MoveToChild(XPathNodeType.Element))
            do
            {
              switch (childNav.LocalName)
              {
                case "Version":
                  ParseVersionElement(childNav.Clone());
                  break;
                case "Runtime":
                  ParseRuntimeElement(childNav.Clone(), pluginDirectoryPath);
                  break;
                case "Builder":
                  if (_builders == null)
                    _builders = new Dictionary<string, string>();
                  _builders.Add(ParseBuilderElement(childNav.Clone()));
                  break;
                case "Register":
                  CollectionUtils.AddAll(_itemsMetadata, ParseRegisterElement(childNav.Clone()));
                  break;
                case "DependsOn":
                  CollectionUtils.AddAll(_dependsOn, ParsePluginDependencies(childNav.Clone()));
                  break;
                case "ConflictsWith":
                  CollectionUtils.AddAll(_conflictsWith, ParsePluginIdEnumeration(childNav.Clone()));
                  break;
                default:
                  throw new ArgumentException("'Plugin' element doesn't support a child element '" + childNav.Name + "'");
              }
            } while (childNav.MoveToNext(XPathNodeType.Element));
        }
      }
      catch (Exception e)
      {
        ServiceRegistration.Get<ILogger>().Error("Error parsing plugin descriptor file '" + _pluginFilePath + "'", e);
        return false;
      }
      return true;
    }
Esempio n. 23
0
        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));
        }
Esempio n. 24
0
        /// <summary>
        /// Dequeues the current notification and makes the next notification available.
        /// </summary>
        public void DequeueNotification()
        {
            INotificationService notificationService = ServiceRegistration.Get <INotificationService>();

            notificationService.DequeueNotification();
        }
Esempio n. 25
0
        public void OnTsPacket(byte[] tsPacket, UInt64 presentTime)
        {
            // ServiceRegistration.Get<ILogger>().Debug("PESDECODER ONTSPACKET");
            TSHeader header = new TSHeader(tsPacket);

            if (!SanityCheck(header, tsPacket))
            {
                return;
            }

            int pos = header.PayLoadStart; // where in the pes packet does the payload data start?

            if (header.PayloadUnitStart)   // if this header starts a new PES packet
            {
                //ServiceRegistration.Get<ILogger>().Debug("PESDECODER: PayLoadUnitStart");
                _hasPayloadStart = true;
                if (tsPacket[pos + 0] == 0 && tsPacket[pos + 1] == 0 && tsPacket[pos + 2] == 1)
                {
                    if (_iStreamId < 0)
                    {
                        //if stream id not set yet, get it from this
                        _iStreamId = tsPacket[pos + 3];
                        if (_iStreamId < 0)
                        {
                            throw new Exception("Stream id less than zero :" + _iStreamId);
                        }
                    }
                    else
                    {
                        Assert(_iStreamId == tsPacket[pos + 3], "Stream id changed!"); // stream id should not change!
                    }
                    if (_iWritePos != 0)
                    {
                        //throw new Exception("Buffer is not empty, but new packet is being received!");
                        ServiceRegistration.Get <ILogger>().Warn("PESDECODER: Buffer is not empty, but new packet is being received!");
                    }
                    _iWritePos = 0;

                    _iPesHeaderLen = tsPacket[pos + 8] + 9;

                    if (_pesHeader.Length < _iPesHeaderLen)
                    {
                        ServiceRegistration.Get <ILogger>().Error(
                            "PESDecoder: Reported header length is bigger than header buffer! : {0} vs {1}", _pesHeader.Length,
                            _iPesHeaderLen);
                    }
                    Array.Copy(tsPacket, pos, _pesHeader, 0, _iPesHeaderLen);
                    //above replaces -> memcpy(m_pesHeader,&tsPacket[pos],m_iPesHeaderLen);

                    pos    += (_iPesHeaderLen);
                    _bStart = true;

                    int a = _pesHeader[4];
                    int b = _pesHeader[5];

                    _iPesLength = (a << 8) + b - (_iPesHeaderLen - 6); // calculate expected actual payload length
                }
            }
            else if (!_hasPayloadStart)
            {
                //ServiceRegistration.Get<ILogger>().Debug("PACKET DISCARDED: END OF PACKET FOR WHICH WE DONT HAVE START");
                return;
            }

            if (_iWritePos < 0)
            {
                ServiceRegistration.Get <ILogger>().Debug("m_iWritePos < 0");
                return;
            }
            if (_iStreamId <= 0)
            {
                ServiceRegistration.Get <ILogger>().Debug("m_iStreamId <= 0");
                return;
            }

            Assert(pos > 0 && pos < 188, "Pos error : " + pos);
            Assert(_iWritePos + 188 - pos <= MAX_PES_PACKET, "About to exceed buffer size!");
            // check that the buffer is not overrunning

            int bytesToWrite = 188 - pos;

            Assert(bytesToWrite < 188, "Bytes to write too big : " + bytesToWrite);
            Array.Copy(tsPacket, pos, _pesBuffer, _iWritePos, bytesToWrite);
            _iWritePos += bytesToWrite;

            if (_iPesLength == _iWritePos) // we have the expected data
            {
                // ServiceRegistration.Get<ILogger>().Debug("PESDECODER: GOT COMPLETE PACKET");

                // assert(cb != null, "cb is null!");
                if (_iWritePos > 0 && _cb != null)
                {
                    //ServiceRegistration.Get<ILogger>().Debug("PESDECODER: CALLING CALLBACK");
                    _cb(_iStreamId, _pesHeader, _iPesHeaderLen, _pesBuffer, _iWritePos, _bStart, presentTime);

                    _bStart          = false;
                    _iWritePos       = 0;
                    _hasPayloadStart = false;
                }
            }
        }
Esempio n. 26
0
        public bool CanEnterState(NavigationContext oldContext, NavigationContext newContext)
        {
            INotificationService notificationService = ServiceRegistration.Get <INotificationService>();

            return(notificationService.Notifications.Count > 0);
        }
Esempio n. 27
0
        private static ServiceRegistration CreateConsulAgentRegistration(this IConveyBuilder builder,
                                                                         ConsulOptions options)
        {
            var enabled       = options.Enabled;
            var consulEnabled = Environment.GetEnvironmentVariable("CONSUL_ENABLED")?.ToLowerInvariant();

            if (!string.IsNullOrWhiteSpace(consulEnabled))
            {
                enabled = consulEnabled == "true" || consulEnabled == "1";
            }

            if (!enabled)
            {
                return(null);
            }

            if (string.IsNullOrWhiteSpace(options.Address))
            {
                throw new ArgumentException("Consul address can not be empty.",
                                            nameof(options.PingEndpoint));
            }

            builder.Services.AddHttpClient <IConsulService, ConsulService>(c => c.BaseAddress = new Uri(options.Url));

            if (builder.Services.All(x => x.ServiceType != typeof(ConsulHostedService)))
            {
                builder.Services.AddHostedService <ConsulHostedService>();
            }

            var serviceId = string.Empty;

            using (var serviceProvider = builder.Services.BuildServiceProvider())
            {
                serviceId = serviceProvider.GetRequiredService <IServiceId>().Id;
            }

            var registration = new ServiceRegistration
            {
                Name              = options.Service,
                Id                = $"{options.Service}:{serviceId}",
                Address           = options.Address,
                Port              = options.Port,
                Tags              = options.Tags,
                Meta              = options.Meta,
                EnableTagOverride = options.EnableTagOverride,
                Connect           = options.Connect?.Enabled == true ? new Connect() : null
            };

            if (!options.PingEnabled)
            {
                return(registration);
            }

            var pingEndpoint = string.IsNullOrWhiteSpace(options.PingEndpoint) ? string.Empty :
                               options.PingEndpoint.StartsWith("/") ? options.PingEndpoint : $"/{options.PingEndpoint}";

            if (pingEndpoint.EndsWith("/"))
            {
                pingEndpoint = pingEndpoint.Substring(0, pingEndpoint.Length - 1);
            }

            var scheme = options.Address.StartsWith("http", StringComparison.InvariantCultureIgnoreCase)
                ? string.Empty
                : "http://";
            var check = new ServiceCheck
            {
                Interval = ParseTime(options.PingInterval),
                DeregisterCriticalServiceAfter = ParseTime(options.RemoveAfterInterval),
                Http = $"{scheme}{options.Address}{(options.Port > 0 ? $":{options.Port}" : string.Empty)}" +
                       $"{pingEndpoint}"
            };

            registration.Checks = new[] { check };

            return(registration);
        }
Esempio n. 28
0
        protected void Update()
        {
            ISystemStateService sss = ServiceRegistration.Get <ISystemStateService>();

            if (sss.CurrentState != SystemState.Running)
            {
                return;
            }
            INotificationService notificationService = ServiceRegistration.Get <INotificationService>();
            int numNotifications             = notificationService.Notifications.Count;
            IWorkflowManager workflowManager = ServiceRegistration.Get <IWorkflowManager>();

            if (numNotifications == 0 && workflowManager.CurrentNavigationContext.WorkflowState.StateId == Consts.WF_STATE_ID_WATCH_NOTIFICATIONS)
            {
                // Don't pop the watch-notifications state from the navigation stack if we are in a sub state
                workflowManager.NavigatePopToStateAsync(Consts.WF_STATE_ID_WATCH_NOTIFICATIONS, true);
            }
            IsNotificationsHintVisible         = !workflowManager.IsStateContainedInNavigationStack(Consts.WF_STATE_ID_WATCH_NOTIFICATIONS) && numNotifications > 0;
            NumNotificationsTotal              = numNotifications;
            IsNotificationsAvailable           = numNotifications > 0;
            IsMoreThanOneNotificationAvailable = numNotifications > 1;
            if (numNotifications <= 1)
            {
                NMoreNotificationsText = string.Empty;
            }
            else if (numNotifications == 2)
            {
                NMoreNotificationsText = LocalizationHelper.Translate(Consts.RES_ONE_MORE_NOTIFICATION);
            }
            else
            {
                NMoreNotificationsText = LocalizationHelper.Translate(Consts.RES_N_MORE_NOTIFICATIONS, numNotifications - 1);
            }
            INotification notification = notificationService.PeekNotification();

            CurrentNotification = notification;
            if (notification != null)
            {
                if (string.IsNullOrEmpty(notification.CustomIconPath))
                {
                    switch (notification.Type)
                    {
                    case NotificationType.UserInteractionRequired:
                        NotificationSymbolRelFilePath = Consts.REL_PATH_USER_INTERACTION_REQUIRED_ICON;
                        break;

                    case NotificationType.Info:
                        NotificationSymbolRelFilePath = Consts.REL_PATH_INFO_ICON;
                        break;

                    case NotificationType.Warning:
                        NotificationSymbolRelFilePath = Consts.REL_PATH_WARNING_ICON;
                        break;

                    case NotificationType.Error:
                        NotificationSymbolRelFilePath = Consts.REL_PATH_ERROR_ICON;
                        break;
                    }
                }
                else
                {
                    NotificationSymbolRelFilePath = notification.CustomIconPath;
                }
                HasSubWorkflow = notification.HandlerWorkflowState.HasValue;
            }
        }
Esempio n. 29
0
 public SystemResolver()
 {
     ServiceRegistration.Get <ILogger>().Info("SystemResolver: Local system id is '{0}'", _localSystemId);
 }
 public void Init()
 {
     ServiceRegistration.Set <IPathManager>(new PathManager());
     ServiceRegistration.Set <ISettingsManager>(new NoSettingsManager());
     ServiceRegistration.Set <ILocalization>(new NoLocalization());
 }
Esempio n. 31
0
        protected void ShowServerNotConnectedDialog()
        {
            IDialogManager dialogManager = ServiceRegistration.Get <IDialogManager>();

            dialogManager.ShowDialog(Consts.RES_SERVER_NOT_CONNECTED_DIALOG_HEADER, Consts.RES_SERVER_NOT_CONNECTED_DIALOG_TEXT, DialogType.OkDialog, false, null);
        }
        /// <summary>
        /// Checks if our "currently playing" and "fullscreen content" states still fit to the
        /// appropriate players, i.e. if we are in a "currently playing" state and the current player context was
        /// changed, the workflow state will be adapted to match the new current player context's "currently playing" state.
        /// The same check will happen for the primary player context and the "fullscreen content" state.
        /// </summary>
        /// <remarks>
        /// This method must not be called when the player manager's lock is held.
        /// </remarks>
        protected void CheckMediaWorkflowStates_NoLock()
        {
            ISystemStateService sss = ServiceRegistration.Get <ISystemStateService>();

            if (sss.CurrentState != SystemState.Running)
            {
                // Only automatically change workflow states in running state
                return;
            }
            IWorkflowManager workflowManager = ServiceRegistration.Get <IWorkflowManager>();

            workflowManager.StartBatchUpdateAsync();
            ILogger        log           = ServiceRegistration.Get <ILogger>();
            IPlayerManager playerManager = ServiceRegistration.Get <IPlayerManager>();

            try
            {
                for (int i = 0; i < _playerWfStateInstances.Count; i++)
                {
                    // Find the first workflow state of our cached player workflow states which doesn't fit any more
                    // and update to the new player workflow state of the same player workflow state type, if necessary.
                    PlayerWFStateInstance wfStateInstance = _playerWfStateInstances[i];
                    Guid?  newStateId;
                    string stateName;
                    switch (wfStateInstance.WFStateType)
                    {
                    case PlayerWFStateType.CurrentlyPlaying:
                        newStateId = GetPotentialCPStateId();
                        stateName  = "Currently Playing";
                        break;

                    case PlayerWFStateType.FullscreenContent:
                        newStateId = GetPotentialFSCStateId();
                        stateName  = "Fullscreen Content";
                        break;

                    default:
                        throw new NotImplementedException(string.Format("No handler for player workflow state type '{0}'",
                                                                        wfStateInstance.WFStateType));
                    }
                    if (newStateId != wfStateInstance.WFStateId)
                    {
                        // Found the first player workflow state which doesn't fit any more
                        log.Debug("PlayerContextManager: {0} Workflow State '{1}' doesn't fit any more to the current situation. Leaving workflow state.",
                                  stateName, wfStateInstance.WFStateId);
                        lock (playerManager.SyncObj)
                            // Remove all workflow states until the player workflow state which doesn't fit any more
                            _playerWfStateInstances.RemoveRange(i, _playerWfStateInstances.Count - i);
                        workflowManager.NavigatePopToStateAsync(wfStateInstance.WFStateId, true);
                        if (newStateId.HasValue)
                        {
                            log.Debug("PlayerContextManager: Auto-switching to new {0} Workflow State '{1}'",
                                      stateName, newStateId.Value);
                            workflowManager.NavigatePushAsync(newStateId.Value);
                        }
                        break;
                    }
                }
            }
            finally
            {
                workflowManager.EndBatchUpdateAsync();
            }
        }
Esempio n. 33
0
        protected void LeavePartyMode()
        {
            IWorkflowManager workflowManager = ServiceRegistration.Get <IWorkflowManager>();

            workflowManager.NavigatePopToStateAsync(Consts.WF_STATE_ID_PARTY_MUSIC_PLAYER, true);
        }
 public void ToString_WithLifetime_ReturnsEasyToReadRepresentation()
 {
     var sr = new ServiceRegistration();
     sr.ServiceType = typeof(IFoo);
     sr.ServiceName = "AnotherFoo";
     sr.Lifetime = new PerContainerLifetime();
     var toString = sr.ToString();
     Assert.Equal("ServiceType: 'LightInject.SampleLibrary.IFoo', ServiceName: 'AnotherFoo', ImplementingType: '', Lifetime: 'LightInject.PerContainerLifetime'", toString);
 }
        public void GetInstance_ReadOnlyRegistration_ReturnsOriginalRegistration()
        {
            var container = CreateContainer();
            var registration = new ServiceRegistration();
            registration.ServiceType = typeof (IFoo);
            registration.ServiceName = "";
            registration.ImplementingType = typeof (Foo);
            registration.IsReadOnly = true;
            container.Register(registration);

            container.Register<IFoo, AnotherFoo>();

            var instance = container.GetInstance<IFoo>();

            Assert.IsType(typeof (Foo), instance);
        }
 public object Any(ServiceRegistration registration)
 {
     return Discovery.Registration;
 }
        public static void SendPluginManagerMessage(MessageType messageType)
        {
            SystemMessage msg = new SystemMessage(messageType);

            ServiceRegistration.Get <IMessageBroker>().Send(CHANNEL, msg);
        }
Esempio n. 38
0
        public static void SendNavigationCompleteMessage()
        {
            SystemMessage msg = new SystemMessage(MessageType.NavigationComplete);

            ServiceRegistration.Get <IMessageBroker>().Send(CHANNEL, msg);
        }
Esempio n. 39
0
        private object GetInstanceImpl(Type serviceType, string key, bool onlyShared = false)
        {
            lock (_registry)
            {
                // Try to locate matching service entry in the current or a parent container.
                ServiceRegistration registration = new ServiceRegistration(serviceType, key);
                ServiceEntry entry;
                ServiceContainer container;

                if (_registry.TryGetValue(registration, out entry))
                {
                    // Service entry found in local registry.
                    container = this;
                }
                else
                {
                    // Check parent containers.
                    container = _parent;
                    while (container != null)
                    {
                        lock (container._registry)
                        {
                            if (container._registry.TryGetValue(registration, out entry))
                                break;
                        }

                        container = container._parent;
                    }
                }

                if (entry != null)
                {
                    // Resolve instance from service entry.
                    if (entry.CreationPolicy == CreationPolicy.NonShared)
                    {
                        if (onlyShared)
                            return null;

                        // Create non-shared (transient) service instance.
                        var instance = entry.CreateInstance(this);

                        // Track for disposal, if necessary.
                        StoreInstance(entry, instance);

                        return instance;
                    }

                    if (entry.CreationPolicy == CreationPolicy.LocalShared && container != this)
                    {
                        // Service entry was found in a parent container, but the service is 
                        // configured to be created per container. --> Copy into local registry.
                        entry = new ServiceEntry(entry);
                        _registry.Add(registration, entry);
                        container = this;
                    }

                    // Create shared service instance, if not already cached.
                    // (Double-check to avoid unnecessary lock.)
                    if (entry.Instances == null)
                    {
                        lock (entry)
                        {
                            if (entry.Instances == null)
                            {
                                var instance = entry.CreateInstance(container);
                                StoreInstance(entry, instance);
                            }
                        }
                    }

                    return entry.Instances;
                }
            }

            // The requested service type is not directly registered. 

            // Other supported types are:  
            // - IEnumerable<TService> ... service instance collection
            // - Func<TService> .......... factory method for lazy resolution

#if !NETFX_CORE && !NET45
            if (serviceType.IsGenericType)
#else
            if (serviceType.GetTypeInfo().IsGenericType)
#endif
            {
                var genericType = serviceType.GetGenericTypeDefinition();
                if (genericType == typeof(IEnumerable<>))
                {
                    // Requested type is IEnumerable<TService>.

                    // Get typeof(TService).
#if !NETFX_CORE && !NET45
                    Type actualServiceType = serviceType.GetGenericArguments()[0];
#else
                    Type actualServiceType = serviceType.GetTypeInfo().GenericTypeArguments[0];
#endif

                    // Get array of all named TService instances.
                    object[] instances = GetAllInstancesImpl(actualServiceType).ToArray();

                    // Create and fill TService[] array.
                    Array array = Array.CreateInstance(actualServiceType, instances.Length);
                    for (int i = 0; i < array.Length; i++)
                        array.SetValue(instances[i], i);

                    return array;
                }

                if (genericType == typeof(Func<>))
                {
                    // Requested type is Func<TService>.
#if !NETFX_CORE && !NET45
                    var actualServiceType = serviceType.GetGenericArguments()[0];
                    var factoryFactoryType = typeof(ServiceFactoryFactory<>).MakeGenericType(actualServiceType);
                    var factoryFactoryInstance = Activator.CreateInstance(factoryFactoryType);
                    var factoryFactoryMethod = factoryFactoryType.GetMethod("Create");
#else
                    var actualServiceType = serviceType.GetTypeInfo().GenericTypeArguments[0];
                    var factoryFactoryType = typeof(ServiceFactoryFactory<>).MakeGenericType(actualServiceType);
                    var factoryFactoryInstance = Activator.CreateInstance(factoryFactoryType);
                    var factoryFactoryMethod = factoryFactoryType.GetTypeInfo().GetDeclaredMethod("Create");
#endif
                    return factoryFactoryMethod.Invoke(factoryFactoryInstance, new object[] { this, key });
                }

                //if (genericType == typeof(Func<,>) && serviceType.GetGenericArguments()[0] == typeof(string))
                //{
                //  // Requested type is Func<string, TService> where the argument is the name of the service.
                //  ...
                //}
            }

            return null;
        }
        /// <summary>
        /// Registers the servicestack apphost with the local consul agent
        /// </summary>
        /// <exception cref="GatewayServiceDiscoveryException">throws exception if registration was not successful</exception>
        public static void RegisterService(ServiceRegistration registration)
        {
            var consulServiceRegistration = new ConsulServiceRegistration(registration.Id, registration.Name)
                                   {
                                        Address = registration.Address,
                                        Tags = registration.Tags,
                                        Port = registration.Port
                                   };

            ServiceValidator.ValidateAndThrow(consulServiceRegistration);

            var registrationUrl = ConsulUris.LocalAgent.CombineWith(consulServiceRegistration.ToPutUrl());
            registrationUrl.PostJsonToUrl(consulServiceRegistration, null,
                response =>
                {
                    var logger = LogManager.GetLogger(typeof(ConsulClient));
                    if (response.StatusCode.IsErrorResponse())
                    {
                        logger.Fatal(
                            $"Could not register appHost with Consul. It will not be discoverable: {consulServiceRegistration}");
                        throw new GatewayServiceDiscoveryException("Failed to register service with consul");
                    }
                    else
                    {
                        logger.Info($"Registered service with Consul {consulServiceRegistration}");
                        AppDomain.CurrentDomain.ProcessExit +=
                            (sender, args) => UnregisterService(consulServiceRegistration.ID);
                        AppDomain.CurrentDomain.UnhandledException +=
                            (sender, args) => UnregisterService(consulServiceRegistration.ID);
                    }
                });
        }
Esempio n. 41
0
        /// <summary>
        /// Adds a source filter to the graph and sets the input.
        /// </summary>
        protected override void AddSourceFilter()
        {
            if (!_useTsReader)
            {
                base.AddSourceFilter();
                return;
            }

            // Render the file
            // Notes Morpheus_xx, 2017-04-19:
            // In contrast to TV we need to use a relative path here, as the method is located inside the SlimTV assembly.
            // For TV part, the base class inside VideoPlayers is used and thus the correct path to TsReader.ax
            // The problem with different paths appears only inside RELEASE builds, but not DEBUG. Why this happens I don't know.
            _sourceFilter = FilterLoader.LoadFilterFromDll("..\\VideoPlayers\\TsReader.ax", typeof(TsReader).GUID, true);
            var baseFilter = _sourceFilter.GetFilter();

            IFileSourceFilter fileSourceFilter = (IFileSourceFilter)baseFilter;

            _tsReader = (ITsReader)baseFilter;
            _tsReader.SetRelaxedMode(1);
            _tsReader.SetTsReaderCallback(this);
            _tsReader.SetRequestAudioChangeCallback(this);

            _graphBuilder.AddFilter(baseFilter, TSREADER_FILTER_NAME);

            if (_resourceLocator.NativeResourcePath.IsNetworkResource)
            {
                // _resourceAccessor points to an rtsp:// stream or network file
                var sourcePathOrUrl = SourcePathOrUrl;

                if (sourcePathOrUrl == null)
                {
                    throw new IllegalCallException("The LiveRadioPlayer can only play network resources of type INetworkResourceAccessor");
                }

                ServiceRegistration.Get <ILogger>().Debug("{0}: Initializing for stream '{1}'", PlayerTitle, sourcePathOrUrl);

                IDisposable accessEnsurer = null;
                if (IsLocalFilesystemResource)
                {
                    accessEnsurer = ((ILocalFsResourceAccessor)_resourceAccessor).EnsureLocalFileSystemAccess();
                }
                using (accessEnsurer)
                {
                    int hr = fileSourceFilter.Load(SourcePathOrUrl, null);
                    new HRESULT(hr).Throw();
                }
            }
            else
            {
                //_resourceAccessor points to a local .ts file
                var localFileSystemResourceAccessor = _resourceAccessor as ILocalFsResourceAccessor;

                if (localFileSystemResourceAccessor == null)
                {
                    throw new IllegalCallException("The LiveRadioPlayer can only play file resources of type ILocalFsResourceAccessor");
                }

                using (localFileSystemResourceAccessor.EnsureLocalFileSystemAccess())
                {
                    ServiceRegistration.Get <ILogger>().Debug("{0}: Initializing for stream '{1}'", PlayerTitle, localFileSystemResourceAccessor.LocalFileSystemPath);
                    fileSourceFilter.Load(localFileSystemResourceAccessor.LocalFileSystemPath, null);
                }
            }
        }
        /// <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;
            Guid mediaItemId;

            if (mediaType != FanArtMediaTypes.Series && mediaType != FanArtMediaTypes.Episode)
            {
                return(false);
            }

            // Don't try to load "fanart" for images
            if (!Guid.TryParse(name, out mediaItemId) || mediaType == FanArtMediaTypes.Image)
            {
                return(false);
            }

            IMediaLibrary mediaLibrary = ServiceRegistration.Get <IMediaLibrary>(false);

            if (mediaLibrary == null)
            {
                return(false);
            }

            IFilter filter = null;

            if (mediaType == FanArtMediaTypes.Series)
            {
                filter = new RelationshipFilter(EpisodeAspect.ROLE_EPISODE, SeriesAspect.ROLE_SERIES, mediaItemId);
            }
            else if (mediaType == FanArtMediaTypes.Episode)
            {
                filter = new MediaItemIdFilter(mediaItemId);
            }
            MediaItemQuery episodeQuery = new MediaItemQuery(NECESSARY_MIAS, filter);

            episodeQuery.Limit = 1;
            IList <MediaItem> items = mediaLibrary.Search(episodeQuery, false, null, false);

            if (items == null || items.Count == 0)
            {
                return(false);
            }

            MediaItem mediaItem = items.First();

            // Virtual resources won't have any local fanart
            if (mediaItem.IsVirtual)
            {
                return(false);
            }
            var mediaIteamLocator = mediaItem.GetResourceLocator();
            var fanArtPaths       = new List <ResourcePath>();
            var files             = new List <IResourceLocator>();

            // File based access
            try
            {
                var mediaItemPath                     = mediaIteamLocator.NativeResourcePath;
                var mediaItemDirectoryPath            = ResourcePathHelper.Combine(mediaItemPath, "../../");
                var mediaItemFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(mediaItemPath.ToString()).ToLowerInvariant();
                var mediaItemExtension                = ResourcePathHelper.GetExtension(mediaItemPath.ToString());

                using (var directoryRa = new ResourceLocator(mediaIteamLocator.NativeSystemId, mediaItemDirectoryPath).CreateAccessor())
                {
                    var directoryFsra = directoryRa as IFileSystemResourceAccessor;
                    if (directoryFsra != null)
                    {
                        var potentialFanArtFiles = LocalFanartHelper.GetPotentialFanArtFiles(directoryFsra);

                        if (fanArtType == FanArtTypes.Thumbnail)
                        {
                            fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByName(potentialFanArtFiles, LocalFanartHelper.THUMB_FILENAMES));
                        }

                        if (fanArtType == FanArtTypes.Poster)
                        {
                            fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByName(potentialFanArtFiles, LocalFanartHelper.POSTER_FILENAMES));
                        }

                        if (fanArtType == FanArtTypes.Banner)
                        {
                            fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByName(potentialFanArtFiles, LocalFanartHelper.BANNER_FILENAMES));
                        }

                        if (fanArtType == FanArtTypes.Logo)
                        {
                            fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByName(potentialFanArtFiles, LocalFanartHelper.LOGO_FILENAMES));
                        }

                        if (fanArtType == FanArtTypes.ClearArt)
                        {
                            fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByName(potentialFanArtFiles, LocalFanartHelper.CLEARART_FILENAMES));
                        }

                        if (fanArtType == FanArtTypes.FanArt)
                        {
                            fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.BACKDROP_FILENAMES));

                            if (directoryFsra.ResourceExists("ExtraFanArt/"))
                            {
                                using (var extraFanArtDirectoryFsra = directoryFsra.GetResource("ExtraFanArt/"))
                                    fanArtPaths.AddRange(LocalFanartHelper.GetPotentialFanArtFiles(extraFanArtDirectoryFsra));
                            }
                        }

                        files.AddRange(fanArtPaths.Select(path => new ResourceLocator(mediaIteamLocator.NativeSystemId, path)));
                    }
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                ServiceRegistration.Get <ILogger>().Warn("LocalSeriesFanArtProvider: Error while searching fanart of type '{0}' for '{1}'", ex, fanArtType, mediaIteamLocator);
#endif
            }
            result = files;
            return(files.Count > 0);
        }
Esempio n. 43
0
        /// <overloads>
        /// <summary>
        /// Registers a service.
        /// </summary>
        /// </overloads>
        /// 
        /// <summary>
        /// Registers a service using a custom factory method and certain creation and disposal
        /// policies.
        /// </summary>
        /// <param name="serviceType">The type of the service.</param>
        /// <param name="key">
        /// The name under which the object should be registered. Can be <see langword="null"/> or
        /// empty.
        /// </param>
        /// <param name="createInstance">
        /// The factory method responsible for serving the requests from the container.
        /// </param>
        /// <param name="creationPolicy">
        /// The creation policy that specifies when and how a service will be instantiated.
        /// </param>
        /// <param name="disposalPolicy">
        /// The disposal policy that specifies when a service instance will be disposed. (Only
        /// relevant if the service instance implements <see cref="IDisposable"/>.)
        /// </param>
        /// <remarks>
        /// If a service with the same type and name is already registered, the existing entry will
        /// be replaced.
        /// </remarks>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="serviceType"/> or <paramref name="createInstance"/> is
        /// <see langword="null"/>.
        /// </exception>
        public void Register(Type serviceType, string key, Func<ServiceContainer, object> createInstance, CreationPolicy creationPolicy, DisposalPolicy disposalPolicy)
        {
            ThrowIfDisposed();

            if (serviceType == null)
                throw new ArgumentNullException(nameof(serviceType));
            if (createInstance == null)
                throw new ArgumentNullException(nameof(createInstance));

            var registration = new ServiceRegistration(serviceType, key);
            var entry = new ServiceEntry(createInstance, creationPolicy, disposalPolicy);
            lock (_registry)
            {
                _registry[registration] = entry;
            }
        }