示例#1
0
        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());
        }
        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
        }
 protected void UpdateProperties_NoLock()
 {
     lock (_syncObj)
     {
         if (_updatingProperties)
         {
             return;
         }
         _updatingProperties = true;
     }
     try
     {
         IServerConnectionManager serverConnectionManager = ServiceRegistration.Get <IServerConnectionManager>();
         IsHomeServerConnected = serverConnectionManager.IsHomeServerConnected;
         SystemName homeServerSystem = serverConnectionManager.LastHomeServerSystem;
         IsLocalHomeServer = homeServerSystem != null && homeServerSystem.IsLocalSystem();
         lock (_syncObj)
         {
             _isAttached         = homeServerSystem != null;
             _enableLocalShares  = !IsLocalHomeServer;
             _enableServerShares = IsHomeServerConnected;
         }
     }
     finally
     {
         lock (_syncObj)
             _updatingProperties = false;
     }
 }
示例#4
0
        protected static void NotifyPlayback(MediaItem mediaItem, int playPercentage)
        {
            ISettingsManager      settingsManager = ServiceRegistration.Get <ISettingsManager>();
            PlayerManagerSettings settings        = settingsManager.Load <PlayerManagerSettings>();
            bool watched = playPercentage >= settings.WatchedPlayPercentage;

            if (watched)
            {
                playPercentage = 100;
            }

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

            // Server will update the PlayCount of MediaAspect in ML, this does not affect loaded items.
            if (cd != null)
            {
                cd.NotifyPlayback(mediaItem.MediaItemId, watched);
            }

            // Update loaded item also, so changes will be visible in GUI without reloading
            if (!mediaItem.UserData.ContainsKey(UserDataKeysKnown.KEY_PLAY_PERCENTAGE))
            {
                mediaItem.UserData.Add(UserDataKeysKnown.KEY_PLAY_PERCENTAGE, "0");
            }
            mediaItem.UserData[UserDataKeysKnown.KEY_PLAY_PERCENTAGE] = playPercentage.ToString();

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

            if (userProfileDataManagement.IsValidUser)
            {
                userProfileDataManagement.UserProfileDataManagement.SetUserMediaItemData(userProfileDataManagement.CurrentUser.ProfileId, mediaItem.MediaItemId,
                                                                                         UserDataKeysKnown.KEY_PLAY_PERCENTAGE, playPercentage.ToString());
            }

            if (watched)
            {
                // Update loaded item also, so changes will be visible in GUI without reloading
                int currentPlayCount;
                if (MediaItemAspect.TryGetAttribute(mediaItem.Aspects, MediaAspect.ATTR_PLAYCOUNT, 0, out currentPlayCount))
                {
                    MediaItemAspect.SetAttribute(mediaItem.Aspects, MediaAspect.ATTR_PLAYCOUNT, ++currentPlayCount);
                }

                if (!mediaItem.UserData.ContainsKey(UserDataKeysKnown.KEY_PLAY_COUNT))
                {
                    mediaItem.UserData.Add(UserDataKeysKnown.KEY_PLAY_COUNT, "0");
                }
                currentPlayCount = Convert.ToInt32(mediaItem.UserData[UserDataKeysKnown.KEY_PLAY_COUNT]);
                currentPlayCount++;
                mediaItem.UserData[UserDataKeysKnown.KEY_PLAY_COUNT] = currentPlayCount.ToString();

                if (userProfileDataManagement.IsValidUser)
                {
                    userProfileDataManagement.UserProfileDataManagement.SetUserMediaItemData(userProfileDataManagement.CurrentUser.ProfileId, mediaItem.MediaItemId,
                                                                                             UserDataKeysKnown.KEY_PLAY_COUNT, currentPlayCount.ToString());
                }
            }
            ContentDirectoryMessaging.SendMediaItemChangedMessage(mediaItem, ContentDirectoryMessaging.MediaItemChangeType.Updated);
        }
示例#5
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));
            }
        }
示例#6
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));
        }
示例#7
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));
            }
        }
        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);
        }
        protected bool BuildBaseUrl()
        {
            IServerConnectionManager scm = ServiceRegistration.Get <IServerConnectionManager>();

            // In case we lost the connection clear the url so it can be looked up later again
            if (!scm.IsHomeServerConnected)
            {
                _baseUrl = null;
                return(false);
            }
            if (!string.IsNullOrWhiteSpace(_baseUrl))
            {
                return(true);
            }

            // We need to know the base url of the server's remote access service, so we can use the IP and port number.
            try
            {
                IRemoteResourceInformationService rris = ServiceRegistration.Get <IRemoteResourceInformationService>();
                string    resourceUrl;
                IPAddress localIpAddress;
                if (!rris.GetFileHttpUrl(scm.HomeServerSystemId, ResourcePath.BuildBaseProviderPath(Guid.Empty, string.Empty), out resourceUrl, out localIpAddress))
                {
                    return(false);
                }

                Uri uri = new Uri(resourceUrl);
                _baseUrl = uri.Authority;
                return(true);
            }
            catch
            {
                return(false);
            }
        }
示例#10
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;
        }
        public bool CanEnterState(NavigationContext oldContext, NavigationContext newContext)
        {
            lock (_syncObj)
                if (_mode != Mode.None)
                {
                    return(false);
                }       // We are already active
            _detachConfirmDialogHandle = Guid.Empty;
            _attachInfoDialogHandle    = null;
            IServerConnectionManager scm = ServiceRegistration.Get <IServerConnectionManager>();

            if (newContext.WorkflowState.StateId == Consts.WF_STATE_ID_ATTACH_TO_SERVER)
            {
                if (scm.HomeServerSystemId != null)
                {
                    return(false);
                }
            }
            else if (newContext.WorkflowState.StateId == Consts.WF_STATE_ID_DETACH_FROM_SERVER)
            {
                if (scm.HomeServerSystemId == null)
                {
                    return(false);
                }
            }
            return(true);
        }
示例#12
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);
                }
            }
        }
示例#13
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));
        }
示例#14
0
        public override SystemName GetSystemNameForSystemId(string systemId)
        {
            if (systemId == _localSystemId)
            {
                // Shortcut for local system
                return(SystemName.GetLocalSystemName());
            }
            IServerConnectionManager serverConnectionManager = ServiceRegistration.Get <IServerConnectionManager>();

            if (systemId == serverConnectionManager.HomeServerSystemId)
            { // Shortcut for home server
                SystemName result = serverConnectionManager.LastHomeServerSystem;
                if (result != null)
                {
                    return(result);
                }
            }
            IServerController sc = serverConnectionManager.ServerController;

            if (sc == null)
            {
                return(null);
            }
            return(sc.GetSystemNameForSystemId(systemId));
        }
示例#15
0
        protected void Update()
        {
            IServerConnectionManager scm = ServiceRegistration.Get <IServerConnectionManager>();

            _titleRes = LocalizationHelper.CreateResourceString(string.IsNullOrEmpty(scm.HomeServerSystemId) ? Consts.RES_SEARCH_FOR_SERVERS : Consts.RES_DETACH_FROM_SERVER);
            FireStateChanged();
        }
示例#16
0
        /// <summary>
        /// Tries to find the resource path corresponding to the given media library <paramref name="viewSpecification"/>.
        /// </summary>
        /// <param name="viewSpecification">View specification to be examined.</param>
        /// <param name="path">Path corresponding to the given <paramref name="viewSpecification"/>, if it is a media library view specification (i.e. one of the
        /// view specifications which are created in any of the sub views of this view specification). Else, this parameter will return <c>null</c>.</param>
        /// <returns><c>true</c>, if the given <paramref name="viewSpecification"/> is one of the direct or indirect view specifications which are created as sub view specifications
        /// of this view specification.</returns>
        public static bool TryGetLocalBrowseViewPath(ViewSpecification viewSpecification, out ResourcePath path)
        {
            MediaLibraryBrowseViewSpecification mlbvs = viewSpecification as MediaLibraryBrowseViewSpecification;

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

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

            if (ssvs != null || asvs != null || bmrvs != null)
            { // If the current browsing state shows one of the root browse states, we can just set the path to null
                path = null;
                return(true);
            }
            path = null;
            return(false);
        }
示例#17
0
        public override void AddShare()
        {
            IServerConnectionManager serverConnectionManager = ServiceRegistration.Get <IServerConnectionManager>();
            IContentDirectory        contentDirectory        = GetContentDirectoryService();

            contentDirectory.RegisterShare(Share.CreateNewShare(serverConnectionManager.HomeServerSystemId, ChoosenResourcePath, ShareName, MediaCategories));
            _serverSharesCache = null;
        }
示例#18
0
        public static IEnumerable <Share> GetShares()
        {
            IServerConnectionManager serverConnectionManager = ServiceRegistration.Get <IServerConnectionManager>();
            IContentDirectory        contentDirectory        = GetContentDirectoryService();

            _serverSharesCache = new List <Share>(contentDirectory.GetShares(serverConnectionManager.HomeServerSystemId, SharesFilter.All));
            return(_serverSharesCache);
        }
示例#19
0
        public void Execute()
        {
            IWorkflowManager         workflowManager = ServiceRegistration.Get <IWorkflowManager>();
            IServerConnectionManager scm             = ServiceRegistration.Get <IServerConnectionManager>();

            workflowManager.NavigatePush(string.IsNullOrEmpty(scm.HomeServerSystemId) ?
                                         Consts.WF_STATE_ID_ATTACH_TO_SERVER : Consts.WF_STATE_ID_DETACH_FROM_SERVER);
        }
        /// <summary>
        /// Called from the skin to connect to one of the available servers.
        /// </summary>
        /// <param name="availableServerItem">One of the items in the <see cref="AvailableServers"/> collection</param>
        public void ChooseNewHomeServerAndClose(ListItem availableServerItem)
        {
            ServerDescriptor         sd  = (ServerDescriptor)availableServerItem.AdditionalProperties[Consts.KEY_SERVER_DESCRIPTOR];
            IServerConnectionManager scm = ServiceRegistration.Get <IServerConnectionManager>();

            scm.SetNewHomeServer(sd.MPBackendServerUUID);
            ShowAttachInformationDialogAndClose(sd);
        }
示例#21
0
        protected static async Task NotifyPlayback(MediaItem mediaItem, int playPercentage, double playDuration)
        {
            ISettingsManager      settingsManager = ServiceRegistration.Get <ISettingsManager>();
            PlayerManagerSettings settings        = settingsManager.Load <PlayerManagerSettings>();
            bool watched = playPercentage >= settings.WatchedPlayPercentage;

            if (watched && mediaItem.IsLastPart)
            {
                playPercentage = 100;
            }
            else if (watched && !mediaItem.IsLastPart)
            {
                playPercentage = 50;
            }

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

            if (cd != null)
            {
                IUserManagement userProfileDataManagement = ServiceRegistration.Get <IUserManagement>();
                if (userProfileDataManagement.IsValidUser)
                {
                    bool updatePlayDate = (watched || playDuration >= MINIMUM_WATCHED_SEC || playPercentage >= MINIMUM_WATCHED_PERCENT);
                    await cd.NotifyUserPlaybackAsync(userProfileDataManagement.CurrentUser.ProfileId, mediaItem.MediaItemId, playPercentage, updatePlayDate);
                }
                else
                {
                    await cd.NotifyPlaybackAsync(mediaItem.MediaItemId, watched);
                }
            }

            // Update loaded item also, so changes will be visible in GUI without reloading
            if (!mediaItem.UserData.ContainsKey(UserDataKeysKnown.KEY_PLAY_PERCENTAGE))
            {
                mediaItem.UserData.Add(UserDataKeysKnown.KEY_PLAY_PERCENTAGE, "0");
            }
            mediaItem.UserData[UserDataKeysKnown.KEY_PLAY_PERCENTAGE] = UserDataKeysKnown.GetSortablePlayPercentageString(playPercentage);

            if (watched)
            {
                // Update loaded item also, so changes will be visible in GUI without reloading
                int currentPlayCount;
                if (MediaItemAspect.TryGetAttribute(mediaItem.Aspects, MediaAspect.ATTR_PLAYCOUNT, 0, out currentPlayCount))
                {
                    MediaItemAspect.SetAttribute(mediaItem.Aspects, MediaAspect.ATTR_PLAYCOUNT, ++currentPlayCount);
                }

                if (!mediaItem.UserData.ContainsKey(UserDataKeysKnown.KEY_PLAY_COUNT))
                {
                    mediaItem.UserData.Add(UserDataKeysKnown.KEY_PLAY_COUNT, UserDataKeysKnown.GetSortablePlayCountString(0));
                }
                currentPlayCount = Convert.ToInt32(mediaItem.UserData[UserDataKeysKnown.KEY_PLAY_COUNT]);
                currentPlayCount++;
                mediaItem.UserData[UserDataKeysKnown.KEY_PLAY_COUNT] = UserDataKeysKnown.GetSortablePlayCountString(currentPlayCount);
            }
            ContentDirectoryMessaging.SendMediaItemChangedMessage(mediaItem, ContentDirectoryMessaging.MediaItemChangeType.Updated);
        }
        public override async Task <ICollection <FilterValue> > GetAvailableValuesAsync(IEnumerable <Guid> necessaryMIATypeIds, IFilter selectAttributeFilter, IFilter filter)
        {
            IServerConnectionManager serverConnectionManager = ServiceRegistration.Get <IServerConnectionManager>();
            IServerController        serverController        = serverConnectionManager.ServerController;

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

            IDictionary <string, string> systemNames = new Dictionary <string, string>();

            foreach (MPClientMetadata client in serverController.GetAttachedClients())
            {
                systemNames.Add(client.SystemId, client.LastClientName);
            }
            systemNames.Add(serverConnectionManager.HomeServerSystemId, serverConnectionManager.LastHomeServerName);

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

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

            bool showVirtual = VirtualMediaHelper.ShowVirtualMedia(necessaryMIATypeIds);

            HomogenousMap valueGroups = await cd.GetValueGroupsAsync(ProviderResourceAspect.ATTR_SYSTEM_ID, null, ProjectionFunction.None, necessaryMIATypeIds, filter, true, showVirtual);

            IList <FilterValue> result = new List <FilterValue>(valueGroups.Count);
            int numEmptyEntries        = 0;

            foreach (KeyValuePair <object, object> group in valueGroups)
            {
                string name = group.Key as string ?? string.Empty;
                name = name.Trim();
                if (name == string.Empty)
                {
                    numEmptyEntries += (int)group.Value;
                }
                else
                {
                    string systemName;
                    if (systemNames.TryGetValue(name, out systemName) && !string.IsNullOrEmpty(systemName))
                    {
                        name = systemName;
                    }
                    result.Add(new FilterValue(name,
                                               new RelationalFilter(ProviderResourceAspect.ATTR_SYSTEM_ID, RelationalOperator.EQ, group.Key), null, (int)group.Value, this));
                }
            }
            if (numEmptyEntries > 0)
            {
                result.Insert(0, new FilterValue(Consts.RES_VALUE_EMPTY_TITLE, new EmptyFilter(ProviderResourceAspect.ATTR_SYSTEM_ID), null, numEmptyEntries, this));
            }
            return(result);
        }
示例#23
0
        protected void Page_Load(object sender, EventArgs e)
        {
            _serverConnection = new ServerConnectionManager();
            var stats = _serverConnection.GetAnswerStats();

            var data = JsonConvert.SerializeObject(stats);

            chartData.Value = data;
        }
示例#24
0
        public bool Connect()
        {
            try
            {
                stateService = new SystemStateService();
                ServiceRegistration.Set <ISystemStateService>(stateService);

                stateService.SwitchSystemState(SystemState.Initializing, false);

                logger.Info("Initialising core services");
                ApplicationCore.RegisterVitalCoreServices(false);
                ApplicationCore.RegisterCoreServices();

                logger.Info("Starting localization");
                ServiceRegistration.Set <ILocalization>(new NoLocalization());

                logger.Info("Initialising system resolver");
                ServiceRegistration.Set <ISystemResolver>(new SystemResolver());

                ServerConnectionReceiver reciever = new ServerConnectionReceiver();

                ServiceRegistration.Get <IMessageBroker>().RegisterMessageReceiver(ServerConnectionMessaging.CHANNEL, reciever);

                logger.Info("Initialising server connection manger");
                connectionManager = new ServerConnectionManager();
                ServiceRegistration.Set <IServerConnectionManager>(connectionManager);

                logger.Info("Starting up server connection manger");
                connectionManager.Startup();

                bool connected = reciever.Connect();

                if (connected)
                {
                    logger.Info("Initialising media item aspect type registration");
                    ServiceRegistration.Set <IMediaItemAspectTypeRegistration>(new MediaItemAspectTypeRegistration());

                    ICollection <Guid> types = GetAllManagedMediaItemAspectTypes();
                    foreach (Guid type in types)
                    {
                        MediaItemAspectMetadata metadata = GetMediaItemAspectMetadata(type);
                        logger.Info("Registering media item {0}...", metadata.Name);
                        ServiceRegistration.Get <IMediaItemAspectTypeRegistration>().RegisterLocallyKnownMediaItemAspectTypeAsync(metadata).Wait();
                    }
                }

                Connected = connected;

                return(connected);
            }
            catch (Exception e)
            {
                logger.Error("Cannot connect", e);
                return(false);
            }
        }
示例#25
0
        protected static bool IsSingleSeat(IServerConnectionManager serverConnectionManager)
        {
            SystemName             homeServerSystem      = serverConnectionManager.LastHomeServerSystem;
            bool                   isLocalHomeServer     = homeServerSystem != null && homeServerSystem.IsLocalSystem();
            IServerController      serverController      = serverConnectionManager.ServerController;
            ILocalSharesManagement localSharesManagement = ServiceRegistration.Get <ILocalSharesManagement>();
            ICollection <Share>    localClientShares     = localSharesManagement.Shares.Values;

            return(serverController != null && serverController.GetAttachedClients().Count == 1 && isLocalHomeServer && localClientShares.Count == 0);
        }
示例#26
0
        public void RegisterConfiguration(ConfigBase configItem)
        {
            IServerConnectionManager scm = ServiceRegistration.Get <IServerConnectionManager>();
            IContentDirectory        cd  = scm.ContentDirectory;

            // Set initial "Enabled" value, depending on current connection state.
            configItem.Enabled = cd != null;
            // Set initial "Visible" value, depending on attachment state.
            configItem.Visible = scm.HomeServerSystemId != null;
            _configItems.Add(configItem);
        }
        protected void GetShares(out ICollection <Share> localServerShares, out ICollection <Share> localClientShares)
        {
            IServerConnectionManager serverConnectionManager = ServiceRegistration.Get <IServerConnectionManager>();
            SystemName             homeServerSystem          = serverConnectionManager.LastHomeServerSystem;
            bool                   isLocalHomeServer         = homeServerSystem != null && homeServerSystem.IsLocalSystem();
            IContentDirectory      cd = serverConnectionManager.ContentDirectory;
            ILocalSharesManagement localSharesManagement = ServiceRegistration.Get <ILocalSharesManagement>();

            localServerShares = (isLocalHomeServer && cd != null) ? cd.GetShares(serverConnectionManager.HomeServerSystemId, SharesFilter.All) : new List <Share>();
            localClientShares = localSharesManagement.Shares.Values;
        }
        public void ReImportShare(Share share)
        {
            IServerConnectionManager scm = ServiceRegistration.Get <IServerConnectionManager>();
            IServerController        sc  = scm.ServerController;

            if (sc == null)
            {
                return;
            }
            sc.ScheduleImports(new Guid[] { share.ShareId }, ImportJobType.Refresh);
        }
            public IList <Guid> Execute(IList <string> mediaFiles, ShareLocation shareLocation)
            {
                NumFiles = mediaFiles.Count;
                IServerConnectionManager scm = ServiceRegistration.Get <IServerConnectionManager>();
                IContentDirectory        cd  = scm.ContentDirectory;
                string systemId = shareLocation == ShareLocation.Local ? ServiceRegistration.Get <ISystemResolver>().LocalSystemId : scm.HomeServerSystemId;

                Guid[] necessaryAudioAspectIds = null;
                Guid[] optionalAudioAspectIds  = null;

                ILogger        logger        = ServiceRegistration.Get <ILogger>();
                IScreenManager screenManager = ServiceRegistration.Get <IScreenManager>();
                Guid?          dialogId      = screenManager.ShowDialog(Consts.DIALOG_IMPORT_PLAYLIST_PROGRESS, (dialogName, dialogInstanceId) => Cancel());

                if (!dialogId.HasValue)
                {
                    logger.Warn("ImportPlaylistOperation: Error showing progress dialog");
                    return(null);
                }

                IList <Guid> result = new List <Guid>();

                NumMatched   = 0;
                NumProcessed = 0;
                NumMatched   = 0;
                UpdateScreenData();
                try
                {
                    foreach (string localMediaFile in mediaFiles)
                    {
                        if (IsCancelled)
                        {
                            return(null);
                        }
                        CheckUpdateScreenData();
                        MediaItem item = cd.LoadItem(systemId, LocalFsResourceProviderBase.ToResourcePath(localMediaFile), necessaryAudioAspectIds, optionalAudioAspectIds);
                        NumProcessed++;
                        if (item == null)
                        {
                            logger.Warn("ImportPlaylistOperation: Media item '{0}' was not found in the media library", localMediaFile);
                            continue;
                        }
                        logger.Debug("ImportPlaylistOperation: Matched media item '{0}' in media library", localMediaFile);
                        NumMatched++;
                        result.Add(item.MediaItemId);
                    }
                }
                catch (Exception e)
                {
                    logger.Warn("ImportPlaylistOperation: Error importing playlist", e);
                }
                screenManager.CloseDialog(dialogId.Value);
                return(result);
            }
示例#30
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;
            }

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

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

            ICollection <Guid> allowedShares = null;

            if (userProfile?.RestrictShares == true)
            {
                allowedShares = userProfile.GetAllowedShares();
            }

            foreach (Share share in cd.GetSharesAsync(_systemId, SharesFilter.All).Result)
            {
                if (allowedShares?.Contains(share.ShareId) ?? true)
                {
                    // Check if we want to filter only for given MediaCategories
                    if (_restrictedMediaCategories != null && !share.MediaCategories.Intersect(_restrictedMediaCategories).Any())
                    {
                        continue;
                    }
                    MediaItem parentDirectory = cd.LoadItemAsync(share.SystemId, share.BaseResourcePath, DIRECTORY_MIA_ID_ENUMERATION, EMPTY_ID_ENUMERATION, userProfile?.ProfileId).Result;
                    if (parentDirectory == null)
                    {
                        continue;
                    }
                    IList <MultipleMediaItemAspect> pras = null;
                    MediaItemAspect.TryGetAspects(parentDirectory.Aspects, ProviderResourceAspect.Metadata, out pras);
                    foreach (MultipleMediaItemAspect pra in pras)
                    {
                        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));
                    }
                }
            }
        }
示例#31
0
        public RootViewModel(IEventAggregator events, INavigator navigator, ITheaterApplicationHost appHost, IServerConnectionManager serverManager, RootContext rootContext)
        {
            _navigator = navigator;
            _serverManager = serverManager;
            _rootContext = rootContext;
            Notifications = new NotificationTrayViewModel(events);
            Commands = new CommandBarViewModel(appHost, navigator);
            Clock = new ClockViewModel();
            IsInFocus = true;

            events.Get<ShowPageEvent>().Subscribe(message => ActivePage = message.ViewModel);
            events.Get<PlaybackStopEventArgs>().Subscribe(message => IsInternalMediaPlaying = false);
            events.Get<PlaybackStartEventArgs>().Subscribe(message => {
                if (message.Player is IInternalMediaPlayer && message.Player is IVideoPlayer && message.Options.Items[0].IsVideo) {
                    IsInternalMediaPlaying = true;
                }
            });
        }
 protected static bool IsSingleSeat(IServerConnectionManager serverConnectionManager)
 {
   SystemName homeServerSystem = serverConnectionManager.LastHomeServerSystem;
   bool isLocalHomeServer = homeServerSystem != null && homeServerSystem.IsLocalSystem();
   IServerController serverController = serverConnectionManager.ServerController;
   ILocalSharesManagement localSharesManagement = ServiceRegistration.Get<ILocalSharesManagement>();
   ICollection<Share> localClientShares = localSharesManagement.Shares.Values;
   return serverController != null && serverController.GetAttachedClients().Count == 1 && isLocalHomeServer && localClientShares.Count == 0;
 }