Beispiel #1
0
 public DlnaServerService(IDlnaManager dlnaManager, IContentDirectory contentDirectory, IConnectionManager connectionManager, IMediaReceiverRegistrar mediaReceiverRegistrar)
 {
     _dlnaManager            = dlnaManager;
     _contentDirectory       = contentDirectory;
     _connectionManager      = connectionManager;
     _mediaReceiverRegistrar = mediaReceiverRegistrar;
 }
        protected internal override void ReLoadItemsAndSubViewSpecifications(out IList <MediaItem> mediaItems, out IList <ViewSpecification> subViewSpecifications)
        {
            mediaItems            = null;
            subViewSpecifications = null;
            IContentDirectory cd = ServiceRegistration.Get <IServerConnectionManager>().ContentDirectory;

            if (cd == null)
            {
                return;
            }
            try
            {
                mediaItems = new List <MediaItem>(cd.Browse(_directoryId, _necessaryMIATypeIds, _optionalMIATypeIds));
                ICollection <MediaItem> childDirectories = cd.Browse(_directoryId, DIRECTORY_MIA_ID_ENUMERATION, EMPTY_ID_ENUMERATION);
                subViewSpecifications = new List <ViewSpecification>(childDirectories.Count);
                foreach (MediaItem childDirectory in childDirectories)
                {
                    MediaItemAspect ma  = childDirectory.Aspects[MediaAspect.ASPECT_ID];
                    MediaItemAspect pra = childDirectory.Aspects[ProviderResourceAspect.ASPECT_ID];
                    MediaLibraryBrowseViewSpecification subViewSpecification = new MediaLibraryBrowseViewSpecification(
                        (string)ma.GetAttributeValue(MediaAspect.ATTR_TITLE), childDirectory.MediaItemId,
                        (string)pra.GetAttributeValue(ProviderResourceAspect.ATTR_SYSTEM_ID),
                        ResourcePath.Deserialize((string)pra.GetAttributeValue(ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH)),
                        _necessaryMIATypeIds, _optionalMIATypeIds);
                    subViewSpecifications.Add(subViewSpecification);
                }
            }
            catch (UPnPRemoteException e)
            {
                ServiceRegistration.Get <ILogger>().Error("SimpleTextSearchViewSpecification.ReLoadItemsAndSubViewSpecifications: Error requesting server", e);
                mediaItems            = null;
                subViewSpecifications = null;
            }
        }
Beispiel #3
0
        /// <inheritdoc />
        public BackupResult BackupMovies(string path)
        {
            BackupResult result = new BackupResult {
                CollectedCount = 0, WatchedCount = 0
            };

            Guid[] types =
            {
                MediaAspect.ASPECT_ID,              MovieAspect.ASPECT_ID,            VideoAspect.ASPECT_ID, ImporterAspect.ASPECT_ID,
                ExternalIdentifierAspect.ASPECT_ID, ProviderResourceAspect.ASPECT_ID, VideoStreamAspect.ASPECT_ID
            };

            IContentDirectory contentDirectory = GetContentDirectory();
            Guid?userProfile = GetUserProfileId();

            IList <MediaItem> collectedMovieMediaItems = contentDirectory.SearchAsync(new MediaItemQuery(types, null, null), true, userProfile, false).Result;

            result.CollectedCount = collectedMovieMediaItems.Count;
            List <MediaItem>          watchedMovieMediaItems = collectedMovieMediaItems.Where(MediaItemAspectsUtl.IsWatched).ToList();
            IList <MediaLibraryMovie> watchedMovies          = new List <MediaLibraryMovie>();

            foreach (MediaItem watchedMovieItem in watchedMovieMediaItems)
            {
                watchedMovies.Add(new MediaLibraryMovie
                {
                    Title = MediaItemAspectsUtl.GetMovieTitle(watchedMovieItem),
                    Imdb  = MediaItemAspectsUtl.GetMovieImdbId(watchedMovieItem),
                    Year  = MediaItemAspectsUtl.GetMovieYear(watchedMovieItem)
                });
            }
            SaveLibraryMovies(path, watchedMovies);
            result.WatchedCount = watchedMovies.Count;

            return(result);
        }
        protected static async Task FillListAsync(IContentDirectory contentDirectory, Guid[] necessaryMIATypeIds, ItemsList list, MediaItemToListItemAction converterAction)
        {
            MediaItemQuery query = new MediaItemQuery(necessaryMIATypeIds, null)
            {
                Limit           = QUERY_LIMIT, // Last 5 imported items
                SortInformation = new List <ISortInformation> {
                    new AttributeSortInformation(ImporterAspect.ATTR_DATEADDED, SortDirection.Descending)
                }
            };

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

            if (userProfileDataManagement != null && userProfileDataManagement.IsValidUser)
            {
                userProfile = userProfileDataManagement.CurrentUser.ProfileId;
            }
            bool showVirtual = VirtualMediaHelper.ShowVirtualMedia(necessaryMIATypeIds);

            var items = await contentDirectory.SearchAsync(query, false, userProfile, showVirtual);

            list.Clear();
            foreach (MediaItem mediaItem in items)
            {
                PlayableMediaItem listItem = converterAction(mediaItem);
                listItem.Command = new MethodDelegateCommand(() => PlayItemsModel.CheckQueryPlayAction(listItem.MediaItem));
                list.Add(listItem);
            }
            list.FireChange();
        }
        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
        }
        public override void UpdateShare(RelocationMode relocationMode)
        {
            IContentDirectory contentDirectory = GetContentDirectoryService();

            contentDirectory.UpdateShare(_origShare.ShareId, ChoosenResourcePath, ShareName, UseShareWatcher, GetMediaCategoriesCleanedUp(), relocationMode);
            _serverSharesCache = null;
        }
Beispiel #7
0
        public static ICollection <PlaylistInformationData> GetPlaylists()
        {
            IContentDirectory contentDirectory = GetContentDirectoryService();

            return(contentDirectory == null ? new List <PlaylistInformationData>(0) :
                   contentDirectory.GetPlaylists());
        }
        public override bool Process(MediaItem mediaItem, out ContentDirectoryMessaging.MediaItemChangeType changeType)
        {
            changeType = ContentDirectoryMessaging.MediaItemChangeType.None;
            IContentDirectory cd = ServiceRegistration.Get <IServerConnectionManager>().ContentDirectory;

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

            var rl = mediaItem.GetResourceLocator();

            Guid parentDirectoryId;

            if (!MediaItemAspect.TryGetAttribute(mediaItem.Aspects, ProviderResourceAspect.ATTR_PARENT_DIRECTORY_ID, out parentDirectoryId))
            {
                return(false);
            }

            MediaItemAspect.SetAttribute(mediaItem.Aspects, MediaAspect.ATTR_PLAYCOUNT, GetNewPlayCount());

            cd.AddOrUpdateMediaItem(parentDirectoryId, rl.NativeSystemId, rl.NativeResourcePath, mediaItem.Aspects.Values);

            changeType = ContentDirectoryMessaging.MediaItemChangeType.Updated;
            return(true);
        }
Beispiel #9
0
        public override async Task <ICollection <FilterValue> > GetAvailableValuesAsync(IEnumerable <Guid> necessaryMIATypeIds, IFilter selectAttributeFilter, IFilter filter)
        {
            IContentDirectory cd = ServiceRegistration.Get <IServerConnectionManager>().ContentDirectory;

            if (cd == null)
            {
                throw new NotConnectedException("The MediaLibrary is not connected");
            }

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

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

            IEnumerable <Guid> mias    = _necessaryMIATypeIds ?? necessaryMIATypeIds;
            IEnumerable <Guid> optMias = _optionalMIATypeIds != null?_optionalMIATypeIds.Except(mias) : null;

            bool    showVirtual = VirtualMediaHelper.ShowVirtualMedia(necessaryMIATypeIds);
            IFilter queryFilter = new FilteredRelationshipFilter(_role, _linkedRole, filter);

            MediaItemQuery query = new MediaItemQuery(mias, optMias, queryFilter);

            if (_sortInformation != null)
            {
                query.SortInformation = new List <ISortInformation> {
                    _sortInformation
                }
            }
            ;

            IList <MediaItem> items = await cd.SearchAsync(query, true, userProfile, showVirtual);

            CertificationHelper.ConvertCertifications(items);
            IList <FilterValue> result = new List <FilterValue>(items.Count);

            foreach (MediaItem item in items)
            {
                string name;
                MediaItemAspect.TryGetAttribute(item.Aspects, MediaAspect.ATTR_TITLE, out name);
                result.Add(new FilterValue(name,
                                           new FilterTreePath(_role),
                                           null,
                                           item,
                                           this));
            }

            //ToDo: Add support for an empty entry for all filtered items that don't have this relationship
            //The below works OK in simple cases but results in an extra, relatively long running query. Maybe this should be handled
            //at the server for all relationship queries...
            //IFilter emptyRelationshipFilter = new NotFilter(new RelationshipFilter(_linkedRole, _role, Guid.Empty));
            //queryFilter = filter != null ? BooleanCombinationFilter.CombineFilters(BooleanOperator.And, filter, emptyRelationshipFilter) : emptyRelationshipFilter;
            //int numEmptyEntries = cd.CountMediaItems(necessaryMIATypeIds, queryFilter, true, showVirtual);
            //if(numEmptyEntries > 0)
            //  result.Insert(0, new FilterValue(Consts.RES_VALUE_EMPTY_TITLE, emptyRelationshipFilter, null, this));

            return(result);
        }
        public async Task <bool> LoadPlaylist()
        {
            IServerConnectionManager scm = ServiceRegistration.Get <IServerConnectionManager>();
            IContentDirectory        cd  = scm.ContentDirectory;

            if (cd == null)
            {
                ShowServerNotConnectedDialog();
                return(false);
            }
            // Big playlists cannot be loaded in one single step. We have several problems if we try to do so:
            // 1) Loading the playlist at once at the server results in one huge SQL IN statement which might break the SQL engine
            // 2) The time to load the playlist might lead the UPnP call to break because of the timeout when calling methods
            // 3) The resulting UPnP XML document might be too big to fit into memory

            // For that reason, we load the playlist in two steps:
            // 1) Load media item ids in the playlist
            // 2) Load media items in clusters - for each cluster, an own query will be executed at the content directory
            PlaylistRawData playlistData = await cd.ExportPlaylistAsync(_playlistId);

            List <MediaItem> result = new List <MediaItem>();

            foreach (IList <Guid> itemIds in CollectionUtils.Cluster(playlistData.MediaItemIds, 500))
            {
                result.AddRange(await cd.LoadCustomPlaylistAsync(itemIds, Consts.NECESSARY_AUDIO_MIAS, Consts.EMPTY_GUID_ENUMERATION));
            }
            _mediaItems = result;
            return(true);
        }
        public void TestEpisodeNumbers()
        {
            Guid[] types =
            {
                MediaAspect.ASPECT_ID,            EpisodeAspect.ASPECT_ID, VideoAspect.ASPECT_ID, ImporterAspect.ASPECT_ID,
                ProviderResourceAspect.ASPECT_ID, ExternalIdentifierAspect.ASPECT_ID
            };

            IContentDirectory contentDirectory = ServiceRegistration.Get <IServerConnectionManager>().ContentDirectory;

            if (contentDirectory == null)
            {
                return;
            }

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

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

            IList <MediaItem> collectedEpisodeMediaItems = contentDirectory.SearchAsync(new MediaItemQuery(types, null, null), true, userProfile, false).Result;
            List <MediaItem>  watchedEpisodeMediaItems   = collectedEpisodeMediaItems.Where(IsWatched).ToList();

            foreach (MediaItem episodeMediaItem in watchedEpisodeMediaItems)
            {
                List <int> episodeNumbers = GetEpisodeNumbers(episodeMediaItem);
            }
        }
Beispiel #12
0
        public override async Task <IEnumerable <MediaItem> > GetAllMediaItems()
        {
            IContentDirectory cd = ServiceRegistration.Get <IServerConnectionManager>().ContentDirectory;

            if (cd == null)
            {
                return(new List <MediaItem>());
            }

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

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

            MediaItemQuery query = new MediaItemQuery(
                _necessaryMIATypeIds,
                _optionalMIATypeIds,
                UserHelper.GetUserRestrictionFilter(_necessaryMIATypeIds, userProfile, new BooleanCombinationFilter(BooleanOperator.And,
                                                                                                                    new IFilter[]
            {
                new RelationalFilter(ProviderResourceAspect.ATTR_SYSTEM_ID, RelationalOperator.EQ, _systemId),
                new LikeFilter(ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH, SqlUtils.LikeEscape(_basePath.Serialize(), '\\') + "%", '\\', true)
            })));

            bool showVirtual = VirtualMediaHelper.ShowVirtualMedia(_necessaryMIATypeIds);

            return(await cd.SearchAsync(query, false, userProfile?.ProfileId, showVirtual));
        }
Beispiel #13
0
        protected internal override void ReLoadItemsAndSubViewSpecifications(out IList <MediaItem> mediaItems, out IList <ViewSpecification> subViewSpecifications)
        {
            mediaItems            = new List <MediaItem>();
            subViewSpecifications = new List <ViewSpecification>();
            IServerConnectionManager scm = ServiceRegistration.Get <IServerConnectionManager>();
            IContentDirectory        cd  = scm.ContentDirectory;

            if (cd == null)
            {
                return;
            }
            foreach (Share share in cd.GetShares(_systemId, SharesFilter.All))
            {
                // Check if we want to filter only for given MediaCategories
                if (_restrictedMediaCategories != null && !share.MediaCategories.Intersect(_restrictedMediaCategories).Any())
                {
                    continue;
                }
                MediaItem parentDirectory = cd.LoadItem(share.SystemId, share.BaseResourcePath, DIRECTORY_MIA_ID_ENUMERATION, EMPTY_ID_ENUMERATION);
                if (parentDirectory == null)
                {
                    continue;
                }
                MediaItemAspect pra = parentDirectory.Aspects[ProviderResourceAspect.ASPECT_ID];
                subViewSpecifications.Add(new MediaLibraryBrowseViewSpecification(share.Name, parentDirectory.MediaItemId,
                                                                                  (string)pra.GetAttributeValue(ProviderResourceAspect.ATTR_SYSTEM_ID),
                                                                                  ResourcePath.Deserialize((string)pra.GetAttributeValue(ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH)),
                                                                                  _necessaryMIATypeIds, _optionalMIATypeIds));
            }
        }
        protected internal override void ReLoadItemsAndSubViewSpecifications(out IList <MediaItem> mediaItems, out IList <ViewSpecification> subViewSpecifications)
        {
            mediaItems            = null;
            subViewSpecifications = new List <ViewSpecification>();
            IContentDirectory cd = ServiceRegistration.Get <IServerConnectionManager>().ContentDirectory;

            if (cd == null)
            {
                return;
            }

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

            if (userProfileDataManagement != null && userProfileDataManagement.IsValidUser)
            {
                userProfile = userProfileDataManagement.CurrentUser.ProfileId;
            }
            bool showVirtual = VirtualMediaHelper.ShowVirtualMedia(_necessaryMIATypeIds);

            try
            {
                MediaItemQuery query = new MediaItemQuery(_necessaryMIATypeIds, _optionalMIATypeIds, _filter)
                {
                    Limit = Consts.MAX_NUM_ITEMS_VISIBLE
                };
                mediaItems = cd.SearchAsync(query, true, userProfile, showVirtual).Result;
            }
            catch (UPnPRemoteException e)
            {
                ServiceRegistration.Get <ILogger>().Error("SimpleTextSearchViewSpecification.ReLoadItemsAndSubViewSpecifications: Error requesting server", e);
                mediaItems = new List <MediaItem>();
            }
        }
 public DlnaServerService(IDlnaManager dlnaManager, IContentDirectory contentDirectory, IConnectionManager connectionManager, IConfigurationManager config)
 {
     _dlnaManager = dlnaManager;
     _contentDirectory = contentDirectory;
     _connectionManager = connectionManager;
     _config = config;
 }
Beispiel #16
0
        protected async Task NotifyPlayback()
        {
            IUserManagement       userProfileDataManagement = ServiceRegistration.Get <IUserManagement>();
            ISettingsManager      settingsManager           = ServiceRegistration.Get <ISettingsManager>();
            PlayerManagerSettings settings = settingsManager.Load <PlayerManagerSettings>();
            int  playPercentage            = GetCurrentPlayPercentage();
            bool played = playPercentage >= settings.WatchedPlayPercentage;

            if (played)
            {
                playPercentage = 100;
            }

            IServerConnectionManager scm = ServiceRegistration.Get <IServerConnectionManager>();
            IContentDirectory        cd  = scm.ContentDirectory;

            if (_mediaItemId.HasValue && _mediaItemId.Value != Guid.Empty && cd != null)
            {
                if (userProfileDataManagement.IsValidUser)
                {
                    bool updateLastPlayed = (played || playPercentage >= PLAY_THRESHOLD_PERCENT || CurrentTime.TotalSeconds >= PLAY_THRESHOLD_SEC);
                    await cd.NotifyUserPlaybackAsync(userProfileDataManagement.CurrentUser.ProfileId, _mediaItemId.Value, playPercentage, updateLastPlayed);
                }
                else
                {
                    await cd.NotifyPlaybackAsync(_mediaItemId.Value, played);
                }
            }
        }
        //Performs the actual query and updates the target property with the returned media item(s)
        protected void QueryMediaItems()
        {
            IFilter filter = Filter;

            if (filter == null)
            {
                //Set target property to null if invalid to remove any previously assigned media items
                UpdateTargetProperty(null, QueryMode);
                return;
            }

            IContentDirectory cd = ServiceRegistration.Get <IServerConnectionManager>().ContentDirectory;

            if (cd == null)
            {
                return;
            }

            MediaItemQueryMode queryMode = QueryMode;
            MediaItemQuery     query     = new MediaItemQuery(NecessaryRequestedMIAs, OptionalRequestedMIAs, filter);

            if (queryMode == MediaItemQueryMode.SingleItem)
            {
                query.Limit = 1;
            }

            IList <MediaItem> items = cd.Search(query, true, GetCurrentUserId(), false);

            UpdateTargetProperty(items, queryMode);
        }
Beispiel #18
0
        protected void CheckDataValid()
        {
            bool result = true;

            ErrorHint = null;
            IServerConnectionManager scm = ServiceRegistration.Get <IServerConnectionManager>();
            IContentDirectory        cd  = scm.ContentDirectory;

            if (cd == null)
            {
                ErrorHint = Consts.RES_SERVER_NOT_CONNECTED;
                result    = false;
            }
            else if (string.IsNullOrEmpty(PlaylistName))
            {
                ErrorHint = Consts.RES_PLAYLIST_NAME_EMPTY;
                result    = false;
            }
            else if (PlaylistNameExists(cd, PlaylistName))
            {
                ErrorHint = Consts.RES_PLAYLIST_NAME_EXISTS;
                result    = false;
            }
            else if (!File.Exists(ImportFile))
            {
                ErrorHint = Consts.RES_IMPORT_FILE_INVALID;
                result    = false;
            }
            IsDataValid = result;
        }
Beispiel #19
0
        protected void RunImportOperationAsync(IContentDirectory cd, IList <string> mediaFiles)
        {
            ILogger logger = ServiceRegistration.Get <ILogger>();

            _importPlaylistOperation = new ImportPlaylistOperation();
            IList <Guid> items = _importPlaylistOperation.Execute(mediaFiles, GetShareLocation());

            if (items == null)
            {
                logger.Info("PlaylistImportModel: Playlist import cancelled");
                return;
            }
            IDialogManager dialogManager = ServiceRegistration.Get <IDialogManager>();

            if (items.Count == 0)
            {
                dialogManager.ShowDialog(Consts.RES_PLAYLIST_SAVE_FAILED_TITLE,
                                         Consts.RES_NO_ITEMS_WERE_IMPORTED_SKIPPING_SAVE_TEXT, DialogType.OkDialog, false, DialogButtonType.Ok);
                return;
            }
            string          playlistName    = PlaylistName;
            PlaylistRawData playlistRawData = new PlaylistRawData(Guid.NewGuid(), playlistName, ManagePlaylistsModel.ConvertAVTypeToPlaylistType(AVType.Audio), items);

            try
            {
                cd.SavePlaylist(playlistRawData);
                dialogManager.ShowDialog(Consts.RES_PLAYLIST_SAVED_SUCCESSFULLY_TITLE,
                                         LocalizationHelper.Translate(Consts.RES_PLAYLIST_SAVED_SUCCESSFULLY_TEXT, playlistName), DialogType.OkDialog, false, DialogButtonType.Ok);
            }
            catch (Exception e)
            {
                dialogManager.ShowDialog(Consts.RES_PLAYLIST_SAVE_FAILED_TITLE, e.Message, DialogType.OkDialog, false, DialogButtonType.Ok);
            }
            _importPlaylistOperation = null;
        }
Beispiel #20
0
        public void ImportPlaylist()
        {
            ILogger logger = ServiceRegistration.Get <ILogger>();

            SaveSettings();
            string importFile = ImportFile;

            if (!File.Exists(importFile))
            {
                logger.Warn("PlaylistImportModel: Cannot import playlist, playlist file '{0}' does not exist", importFile);
                return;
            }
            logger.Info("PlaylistImportModel: Importing playlist '{0}'", importFile);
            IServerConnectionManager scm = ServiceRegistration.Get <IServerConnectionManager>();
            IContentDirectory        cd  = scm.ContentDirectory;

            if (cd == null)
            {
                logger.Warn("PlaylistImportModel: Cannot import playlist, the server is not connected");
                return;
            }
            IList <string> mediaFiles = M3U.ExtractFileNamesFromPlaylist(importFile);
            IThreadPool    threadPool = ServiceRegistration.Get <IThreadPool>();

            threadPool.Add(() => RunImportOperationAsync(cd, mediaFiles));
        }
Beispiel #21
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DlnaServerController"/> class.
 /// </summary>
 /// <param name="dlnaManager">Instance of the <see cref="IDlnaManager"/> interface.</param>
 public DlnaServerController(IDlnaManager dlnaManager)
 {
     _dlnaManager            = dlnaManager;
     _contentDirectory       = DlnaEntryPoint.Current.ContentDirectory;
     _connectionManager      = DlnaEntryPoint.Current.ConnectionManager;
     _mediaReceiverRegistrar = DlnaEntryPoint.Current.MediaReceiverRegistrar;
 }
Beispiel #22
0
        public void Should_BackupTwoEpisodes_When_FourEpisodesCollectedAndFourWatched_WithDuplicatedEpisodeNumbers()
        {
            // Arrange
            IMediaPortalServices mediaPortalServices = Substitute.For <IMediaPortalServices>();
            IContentDirectory    contentDirectory    = Substitute.For <IContentDirectory>();
            IList <MediaItem>    databaseMediaItems  = new List <MediaItem>
            {
                new MockedDatabaseEpisode("272127", 1, new List <int> {
                    7, 8
                }, 100).Episode,
                new MockedDatabaseEpisode("275278", 2, new List <int> {
                    1, 1, 1
                }, 100).Episode,
                new MockedDatabaseEpisode("275278", 4, new List <int> {
                    10, 10
                }, 100).Episode,
                new MockedDatabaseEpisode("275271", 2, new List <int> {
                    11, 12
                }, 90).Episode
            };

            contentDirectory.SearchAsync(Arg.Any <MediaItemQuery>(), true, null, false).Returns(databaseMediaItems);
            mediaPortalServices.GetServerConnectionManager().ContentDirectory.Returns(contentDirectory);
            IFileOperations fileOperations = Substitute.For <IFileOperations>();

            IMoverOperations operations = new MoverOperations(mediaPortalServices, fileOperations);

            // Act
            BackupResult result = operations.BackupSeries(FakePath);

            // Assert
            Assert.Equal(4, result.WatchedCount);
            Assert.Equal(6, result.CollectedCount);
        }
Beispiel #23
0
        protected internal override void ReLoadItemsAndSubViewSpecifications(out IList <MediaItem> mediaItems, out IList <ViewSpecification> subViewSpecifications)
        {
            mediaItems            = new List <MediaItem>();
            subViewSpecifications = new List <ViewSpecification>();
            IServerConnectionManager scm = ServiceRegistration.Get <IServerConnectionManager>();
            IContentDirectory        cd  = scm.ContentDirectory;
            IServerController        sc  = scm.ServerController;

            if (cd == null || sc == null)
            {
                return;
            }
            ICollection <KeyValuePair <string, string> > systems = new List <KeyValuePair <string, string> >(
                sc.GetAttachedClients().Select(client => new KeyValuePair <string, string>(client.SystemId, client.LastClientName)))
            {
                new KeyValuePair <string, string>(scm.HomeServerSystemId, scm.LastHomeServerName) // Add the server too
            };

            foreach (KeyValuePair <string, string> kvp in BuildSystemsDictNames2Ids(systems))
            {
                var clientShares = cd.GetSharesAsync(kvp.Value, SharesFilter.All).Result;
                if (clientShares.Count == 0)
                {
                    continue;
                }

                // Check if we want to filter only for given MediaCategories
                if (_restrictedMediaCategories != null && !clientShares.Any(share => share.MediaCategories.Intersect(_restrictedMediaCategories).Any()))
                {
                    continue;
                }
                subViewSpecifications.Add(new SystemSharesViewSpecification(kvp.Value, kvp.Key, _necessaryMIATypeIds, _optionalMIATypeIds, _restrictedMediaCategories));
            }
        }
Beispiel #24
0
        public override ICollection <FilterValue> GetAvailableValues(IEnumerable <Guid> necessaryMIATypeIds, IFilter selectAttributeFilter, IFilter filter)
        {
            IContentDirectory cd = ServiceRegistration.Get <IServerConnectionManager>().ContentDirectory;

            if (cd == null)
            {
                throw new NotConnectedException("The MediaLibrary is not connected");
            }
            HomogenousMap       valueGroups = cd.GetValueGroups(_attributeType, selectAttributeFilter, ProjectionFunction.None, necessaryMIATypeIds, filter, true);
            IList <FilterValue> result      = new List <FilterValue>(valueGroups.Count);
            int numEmptyEntries             = 0;

            foreach (KeyValuePair <object, object> group in valueGroups)
            {
                string name = GetDisplayName(group.Key);
                if (name == string.Empty)
                {
                    numEmptyEntries += (int)group.Value;
                }
                else
                {
                    result.Add(new FilterValue(name, new RelationalFilter(_attributeType, RelationalOperator.EQ, group.Key), null, (int)group.Value, this));
                }
            }
            if (numEmptyEntries > 0)
            {
                result.Insert(0, new FilterValue(Consts.RES_VALUE_EMPTY_TITLE, new EmptyFilter(_attributeType), null, numEmptyEntries, this));
            }
            return(result);
        }
        private MediaItem GetMediaItem(Guid filter, Guid[] aspects)
        {
            IServerConnectionManager scm = ServiceRegistration.Get <IServerConnectionManager>();
            IContentDirectory        cd  = scm.ContentDirectory;

            return(cd?.SearchAsync(new MediaItemQuery(aspects, new Guid[] { }, new MediaItemIdFilter(filter)), false, null, true).Result.First());
        }
Beispiel #26
0
        public override ICollection <FilterValue> GroupValues(ICollection <Guid> necessaryMIATypeIds, IFilter selectAttributeFilter, IFilter filter)
        {
            IContentDirectory cd = ServiceRegistration.Get <IServerConnectionManager>().ContentDirectory;

            if (cd == null)
            {
                throw new NotConnectedException("The MediaLibrary is not connected");
            }
            IList <MLQueryResultGroup> valueGroups = cd.GroupValueGroups(_attributeType, selectAttributeFilter, ProjectionFunction.None,
                                                                         necessaryMIATypeIds, filter, true, GroupingFunction.FirstCharacter);
            IList <FilterValue> result = new List <FilterValue>(valueGroups.Count);
            int numEmptyEntries        = 0;

            foreach (MLQueryResultGroup group in valueGroups)
            {
                string name = string.Format("{0}", group.GroupKey);
                name = name.Trim();
                if (name == string.Empty)
                {
                    numEmptyEntries += group.NumItemsInGroup;
                }
                else
                {
                    result.Add(new FilterValue(name, null, group.AdditionalFilter, group.NumItemsInGroup, this));
                }
            }
            if (numEmptyEntries > 0)
            {
                result.Insert(0, new FilterValue(Consts.RES_VALUE_EMPTY_TITLE, new EmptyFilter(_attributeType), null, numEmptyEntries, this));
            }
            return(result);
        }
Beispiel #27
0
        protected override ViewSpecification NavigateCreateViewSpecification(string systemId, IFileSystemResourceAccessor viewRA)
        {
            IServerConnectionManager serverConnectionManager = ServiceRegistration.Get <IServerConnectionManager>();

            IContentDirectory cd = serverConnectionManager.ContentDirectory;

            if (cd == null)
            {
                return(null);
            }

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

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

            ResourcePath directoryPath = viewRA.CanonicalLocalResourcePath;
            MediaItem    directoryItem = cd.LoadItemAsync(systemId, directoryPath,
                                                          SystemSharesViewSpecification.DIRECTORY_MIA_ID_ENUMERATION, SystemSharesViewSpecification.EMPTY_ID_ENUMERATION, userProfile).Result;

            if (directoryItem == null)
            {
                return(null);
            }
            return(new MediaLibraryBrowseViewSpecification(viewRA.ResourceName, directoryItem.MediaItemId, systemId,
                                                           directoryPath, _necessaryMIATypeIds, _optionalMIATypeIds));
        }
Beispiel #28
0
        /// <inheritdoc />
        public RestoreResult RestoreWatchedSeries(string path)
        {
            RestoreResult result = new RestoreResult {
                SavedWatchedCount = 0, MarkedWatchedCount = 0
            };

            IList <MediaLibraryEpisode> watchedEpisodes = ReadSavedWatchedEpisodes(path);

            result.SavedWatchedCount = watchedEpisodes.Count;

            Guid[] types =
            {
                MediaAspect.ASPECT_ID,            EpisodeAspect.ASPECT_ID, VideoAspect.ASPECT_ID, ImporterAspect.ASPECT_ID,
                ProviderResourceAspect.ASPECT_ID, ExternalIdentifierAspect.ASPECT_ID
            };

            IContentDirectory contentDirectory = GetContentDirectory();
            Guid?userProfile = GetUserProfileId();

            IList <MediaItem> localEpisodes = contentDirectory.SearchAsync(new MediaItemQuery(types, null, null), true, userProfile, false).Result;
            ILookup <string, MediaLibraryEpisode> loadedEpisodes = watchedEpisodes.ToLookup(twe => CreateLookupKey(twe), twe => twe);

            foreach (MediaItem episode in localEpisodes)
            {
                MatchEpisodeAndMarkAsWatched(result, loadedEpisodes, episode);
            }
            return(result);
        }
Beispiel #29
0
        public override async Task <ICollection <FilterValue> > GetAvailableValuesAsync(IEnumerable <Guid> necessaryMIATypeIds, IFilter selectAttributeFilter, IFilter filter)
        {
            IContentDirectory cd = ServiceRegistration.Get <IServerConnectionManager>().ContentDirectory;

            if (cd == null)
            {
                throw new NotConnectedException("The MediaLibrary is not connected");
            }

            IUserManagement userProfileDataManagement = ServiceRegistration.Get <IUserManagement>();

            if (!userProfileDataManagement.IsValidUser)
            {
                return(new List <FilterValue>());
            }

            IFilter unwatchedFilter = new RelationalUserDataFilter(userProfileDataManagement.CurrentUser.ProfileId, UserDataKeysKnown.KEY_PLAY_PERCENTAGE, RelationalOperator.EQ, UserDataKeysKnown.GetSortablePlayPercentageString(0), true);
            IFilter watchedFilter   = new RelationalUserDataFilter(userProfileDataManagement.CurrentUser.ProfileId, UserDataKeysKnown.KEY_PLAY_PERCENTAGE, RelationalOperator.GT, UserDataKeysKnown.GetSortablePlayPercentageString(0));
            bool    showVirtual     = VirtualMediaHelper.ShowVirtualMedia(necessaryMIATypeIds);
            var     taskUnwatched   = cd.CountMediaItemsAsync(necessaryMIATypeIds, BooleanCombinationFilter.CombineFilters(BooleanOperator.And, filter, unwatchedFilter), true, showVirtual);
            var     taskWatched     = cd.CountMediaItemsAsync(necessaryMIATypeIds, BooleanCombinationFilter.CombineFilters(BooleanOperator.And, filter, watchedFilter), true, showVirtual);
            var     counts          = await Task.WhenAll(taskUnwatched, taskWatched);

            return(new List <FilterValue>(new FilterValue[]
            {
                new FilterValue(Consts.RES_VALUE_UNWATCHED, unwatchedFilter, null, counts[0], this),
                new FilterValue(Consts.RES_VALUE_WATCHED, watchedFilter, null, counts[1], this),
            }.Where(fv => !fv.NumItems.HasValue || fv.NumItems.Value > 0)));
        }
        public override bool Process(MediaItem mediaItem, out ContentDirectoryMessaging.MediaItemChangeType changeType)
        {
            changeType = ContentDirectoryMessaging.MediaItemChangeType.None;

            var rl = mediaItem.GetResourceLocator();

            using (var ra = rl.CreateAccessor())
            {
                var rad = ra as IResourceDeletor;
                if (rad == null)
                {
                    return(false);
                }

                // First try to delete the file from storage.
                if (rad.Delete())
                {
                    changeType = ContentDirectoryMessaging.MediaItemChangeType.Deleted;

                    // If the MediaItem was loaded from ML, remove it there as well.
                    if (IsManagedByMediaLibrary(mediaItem))
                    {
                        IContentDirectory cd = ServiceRegistration.Get <IServerConnectionManager>().ContentDirectory;
                        if (cd == null)
                        {
                            return(true);
                        }

                        cd.DeleteMediaItemOrPath(rl.NativeSystemId, rl.NativeResourcePath, true);
                        return(true);
                    }
                }
            }
            return(false);
        }
Beispiel #31
0
        public override async Task <ICollection <FilterValue> > GetAvailableValuesAsync(IEnumerable <Guid> necessaryMIATypeIds, IFilter selectAttributeFilter, IFilter filter)
        {
            IContentDirectory cd = ServiceRegistration.Get <IServerConnectionManager>().ContentDirectory;

            if (cd == null)
            {
                throw new NotConnectedException("The MediaLibrary is not connected");
            }

            bool showVirtual = VirtualMediaHelper.ShowVirtualMedia(necessaryMIATypeIds);

            IFilter emptyFilter      = new EmptyFilter(AudioAlbumAspect.ATTR_COMPILATION);
            IFilter compiledFilter   = new RelationalFilter(AudioAlbumAspect.ATTR_COMPILATION, RelationalOperator.EQ, true);
            IFilter uncompiledFilter = new RelationalFilter(AudioAlbumAspect.ATTR_COMPILATION, RelationalOperator.EQ, false);
            var     taskEmpty        = cd.CountMediaItemsAsync(necessaryMIATypeIds, emptyFilter, true, showVirtual);
            var     taskCompiled     = cd.CountMediaItemsAsync(necessaryMIATypeIds, compiledFilter, true, showVirtual);
            var     taskUncompiled   = cd.CountMediaItemsAsync(necessaryMIATypeIds, uncompiledFilter, true, showVirtual);

            var counts = await Task.WhenAll(taskEmpty, taskCompiled, taskUncompiled);

            return(new List <FilterValue>(new FilterValue[]
            {
                new FilterValue(Consts.RES_VALUE_EMPTY_TITLE, emptyFilter, null, counts[0], this),
                new FilterValue(Consts.RES_COMPILATION_FILTER_COMPILED, compiledFilter, null, counts[1], this),
                new FilterValue(Consts.RES_COMPILATION_FILTER_UNCOMPILED, uncompiledFilter, null, counts[2], this),
            }.Where(fv => !fv.NumItems.HasValue || fv.NumItems.Value > 0)));
        }
 protected bool PlaylistNameExists(IContentDirectory cd, string playlistName)
 {
   return cd.GetPlaylists().FirstOrDefault(playlistData => playlistData.Name == playlistName) != null;
 }
 protected void UpdatePlaylists(IContentDirectory cd)
 {
   _playlists.Clear();
   ICollection<PlaylistInformationData> playlists = cd.GetPlaylists();
   foreach (PlaylistInformationData playlist in playlists)
   {
     Guid playlistId = playlist.PlaylistId;
     string playlistName = playlist.Name;
     ListItem playlistItem = new ListItem(Consts.KEY_NAME, playlistName)
       {
           Command = new MethodDelegateCommand(() => SetPlaylist(playlistId, playlistName))
       };
     playlistItem.AdditionalProperties[Consts.KEY_PLAYLIST_ID] = playlistId;
     _playlists.Add(playlistItem);
   }
 }
 public ImporterCallback(IContentDirectory contentDirectory)
 {
   _contentDirectory = contentDirectory;
   _localSystemId = ServiceRegistration.Get<ISystemResolver>().LocalSystemId;
 }
 public DlnaServerService(IDlnaManager dlnaManager, IContentDirectory contentDirectory, IConnectionManager connectionManager, IMediaReceiverRegistrar mediaReceiverRegistrar)
 {
     _dlnaManager = dlnaManager;
     _contentDirectory = contentDirectory;
     _connectionManager = connectionManager;
     _mediaReceiverRegistrar = mediaReceiverRegistrar;
 }
 protected void FillList_Async(IContentDirectory contentDirectory, Guid[] necessaryMIAs, ItemsList list, MediaItemToListItemAction converterAction)
 {
   IThreadPool threadPool = ServiceRegistration.Get<IThreadPool>();
   threadPool.Add(() => FillList(contentDirectory, necessaryMIAs, list, converterAction));
 }
    protected void FillList(IContentDirectory contentDirectory, Guid[] necessaryMIAs, ItemsList list, MediaItemToListItemAction converterAction)
    {
      MediaItemQuery query = new MediaItemQuery(necessaryMIAs, null)
      {
        Limit = (uint)QueryLimit, // Last 5 imported items
        SortInformation = new List<SortInformation> { new SortInformation(ImporterAspect.ATTR_DATEADDED, SortDirection.Descending) }
      };

      var items = contentDirectory.Search(query, false);
      list.Clear();
      foreach (MediaItem mediaItem in items)
      {
        PlayableMediaItem listItem = converterAction(mediaItem);
        listItem.Command = new MethodDelegateCommand(() => PlayItemsModel.CheckQueryPlayAction(listItem.MediaItem));
        list.Add(listItem);
      }
      list.FireChange();
    }
 public DlnaServerService(IDlnaManager dlnaManager, IContentDirectory contentDirectory, IEventManager eventManager)
 {
     _dlnaManager = dlnaManager;
     _contentDirectory = contentDirectory;
     _eventManager = eventManager;
 }
 protected void RunImportOperationAsync(IContentDirectory cd, IList<string> mediaFiles)
 {
   ILogger logger = ServiceRegistration.Get<ILogger>();
   _importPlaylistOperation = new ImportPlaylistOperation();
   IList<Guid> items = _importPlaylistOperation.Execute(mediaFiles, GetShareLocation());
   if (items == null)
   {
     logger.Info("PlaylistImportModel: Playlist import cancelled");
     return;
   }
   IDialogManager dialogManager = ServiceRegistration.Get<IDialogManager>();
   if (items.Count == 0)
   {
     dialogManager.ShowDialog(Consts.RES_PLAYLIST_SAVE_FAILED_TITLE,
         Consts.RES_NO_ITEMS_WERE_IMPORTED_SKIPPING_SAVE_TEXT, DialogType.OkDialog, false, DialogButtonType.Ok);
     return;
   }
   string playlistName = PlaylistName;
   PlaylistRawData playlistRawData = new PlaylistRawData(Guid.NewGuid(), playlistName, ManagePlaylistsModel.ConvertAVTypeToPlaylistType(AVType.Audio), items);
   try
   {
     cd.SavePlaylist(playlistRawData);
     dialogManager.ShowDialog(Consts.RES_PLAYLIST_SAVED_SUCCESSFULLY_TITLE,
         LocalizationHelper.Translate(Consts.RES_PLAYLIST_SAVED_SUCCESSFULLY_TEXT, playlistName), DialogType.OkDialog, false, DialogButtonType.Ok);
   }
   catch (Exception e)
   {
     dialogManager.ShowDialog(Consts.RES_PLAYLIST_SAVE_FAILED_TITLE, e.Message, DialogType.OkDialog, false, DialogButtonType.Ok);
   }
   _importPlaylistOperation = null;
 }