Ejemplo n.º 1
0
 public RokuSessionController(IHttpClient httpClient, IJsonSerializer json, IServerApplicationHost appHost, SessionInfo session)
 {
     _httpClient = httpClient;
     _json = json;
     _appHost = appHost;
     Session = session;
 }
Ejemplo n.º 2
0
        /// <summary>
        /// Gets the session info dto.
        /// </summary>
        /// <param name="session">The session.</param>
        /// <returns>SessionInfoDto.</returns>
        public static SessionInfoDto GetSessionInfoDto(SessionInfo session)
        {
            var dto = new SessionInfoDto
            {
                Client = session.Client,
                DeviceId = session.DeviceId,
                DeviceName = session.DeviceName,
                Id = session.Id,
                LastActivityDate = session.LastActivityDate,
                NowPlayingPositionTicks = session.NowPlayingPositionTicks,
                SupportsRemoteControl = session.SupportsRemoteControl,
                IsPaused = session.IsPaused,
                NowViewingContext = session.NowViewingContext,
                NowViewingItemId = session.NowViewingItemId,
                NowViewingItemName = session.NowViewingItemName,
                NowViewingItemType = session.NowViewingItemType,
                ApplicationVersion = session.ApplicationVersion
            };

            if (session.NowPlayingItem != null)
            {
                dto.NowPlayingItem = DtoBuilder.GetBaseItemInfo(session.NowPlayingItem);
            }

            if (session.User != null)
            {
                dto.UserId = session.User.Id.ToString("N");
                dto.UserName = session.User.Name;
            }

            return dto;
        }
Ejemplo n.º 3
0
 public PlayToController(SessionInfo session, ISessionManager sessionManager, IItemRepository itemRepository, ILibraryManager libraryManager, ILogger logger, INetworkManager networkManager)
 {
     _session = session;
     _itemRepository = itemRepository;
     _sessionManager = sessionManager;
     _libraryManager = libraryManager;
     _networkManager = networkManager;
     _logger = logger;
 }
Ejemplo n.º 4
0
        public ISessionController GetSessionController(SessionInfo session)
        {
            if (string.Equals(session.Client, "roku", StringComparison.OrdinalIgnoreCase))
            {
                return new RokuSessionController(_httpClient, _json, _appHost, session);
            }

            return null;
        }
Ejemplo n.º 5
0
        public Task SendMessageCommand(SessionInfo session, MessageCommand command, CancellationToken cancellationToken)
        {
            var socket = GetSocket(session);

            return socket.SendAsync(new WebSocketMessage<MessageCommand>
            {
                MessageType = "MessageCommand",
                Data = command

            }, cancellationToken);
        }
Ejemplo n.º 6
0
        public Task SendSystemCommand(SessionInfo session, SystemCommand command, CancellationToken cancellationToken)
        {
            var socket = GetSocket(session);

            return socket.SendAsync(new WebSocketMessage<string>
            {
                MessageType = "SystemCommand",
                Data = command.ToString()

            }, cancellationToken);
        }
Ejemplo n.º 7
0
        public ISessionController GetSessionController(SessionInfo session)
        {
            if (string.Equals(session.Client, "roku", StringComparison.OrdinalIgnoreCase))
            {
                session.PlayableMediaTypes = new List<string> { MediaType.Video, MediaType.Audio };

                return new RokuSessionController(_httpClient, _json, _appHost, session);
            }

            return null;
        }
Ejemplo n.º 8
0
        public Task SendPlaystateCommand(SessionInfo session, PlaystateRequest command, CancellationToken cancellationToken)
        {
            var socket = GetSocket(session);

            return socket.SendAsync(new WebSocketMessage<PlaystateRequest>
            {
                MessageType = "Playstate",
                Data = command

            }, cancellationToken);
        }
Ejemplo n.º 9
0
        private IWebSocketConnection GetSocket(SessionInfo session)
        {
            var socket = session.WebSockets.OrderByDescending(i => i.LastActivityDate).FirstOrDefault(i => i.State == WebSocketState.Open);


            if (socket == null)
            {
                throw new InvalidOperationException("The requested session does not have an open web socket.");
            }

            return socket;
        }
Ejemplo n.º 10
0
 public PlayToController(SessionInfo session, ISessionManager sessionManager, IItemRepository itemRepository, ILibraryManager libraryManager, ILogger logger, INetworkManager networkManager, IDlnaManager dlnaManager, IUserManager userManager, IServerApplicationHost appHost)
 {
     _session = session;
     _itemRepository = itemRepository;
     _sessionManager = sessionManager;
     _libraryManager = libraryManager;
     _networkManager = networkManager;
     _dlnaManager = dlnaManager;
     _userManager = userManager;
     _appHost = appHost;
     _logger = logger;
 }
Ejemplo n.º 11
0
 public PlayToController(SessionInfo session, ISessionManager sessionManager, IItemRepository itemRepository, ILibraryManager libraryManager, ILogger logger, IDlnaManager dlnaManager, IUserManager userManager, IImageProcessor imageProcessor, string serverAddress, DeviceDiscovery deviceDiscovery)
 {
     _session = session;
     _itemRepository = itemRepository;
     _sessionManager = sessionManager;
     _libraryManager = libraryManager;
     _dlnaManager = dlnaManager;
     _userManager = userManager;
     _imageProcessor = imageProcessor;
     _serverAddress = serverAddress;
     _deviceDiscovery = deviceDiscovery;
     _logger = logger;
 }
Ejemplo n.º 12
0
        private ClientInfo GetNewClientInfo(SessionInfo session)
        {
            var info = new ClientInfo
            {
                AppName = session.Client,
                AppVersion = session.ApplicationVersion,
                DeviceName = session.DeviceName,
                DeviceId = session.DeviceId
            };

            ReportNewSession(info);

            return info;
        }
        public HttpSessionController(IHttpClient httpClient,
            IJsonSerializer json,
            SessionInfo session,
            string postUrl, ISessionManager sessionManager)
        {
            _httpClient = httpClient;
            _json = json;
            Session = session;
            _postUrl = postUrl;
            _sessionManager = sessionManager;

            _pingTimer = new Timer(PingTimerCallback, null, Timeout.Infinite, Timeout.Infinite);

            ResetPingTimer();
        }
Ejemplo n.º 14
0
        private ClientInfo GetNewClientInfo(SessionInfo session)
        {
            var info = new ClientInfo
            {
                AppName = session.Client,
                AppVersion = session.ApplicationVersion,
                DeviceName = session.DeviceName,
                DeviceId = session.DeviceId
            };

            // Report usage to remote server, except for web client, since we already have data on that
            if (!string.Equals(info.AppName, "Dashboard", StringComparison.OrdinalIgnoreCase))
            {
                ReportNewSession(info);
            }

            return info;
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Updates the now playing item id.
        /// </summary>
        /// <param name="session">The session.</param>
        /// <param name="info">The information.</param>
        /// <param name="libraryItem">The library item.</param>
        private void UpdateNowPlayingItem(SessionInfo session, PlaybackProgressInfo info, BaseItem libraryItem)
        {
            var runtimeTicks = libraryItem == null ? null : libraryItem.RunTimeTicks;

            if (string.IsNullOrWhiteSpace(info.MediaSourceId))
            {
                info.MediaSourceId = info.ItemId;
            }

            if (!string.Equals(info.ItemId, info.MediaSourceId) &&
                !string.IsNullOrWhiteSpace(info.MediaSourceId))
            {
                runtimeTicks = _libraryManager.GetItemById(new Guid(info.MediaSourceId)).RunTimeTicks;
            }

            if (!string.IsNullOrWhiteSpace(info.ItemId) && libraryItem != null)
            {
                var current = session.NowPlayingItem;

                if (current == null || !string.Equals(current.Id, info.ItemId, StringComparison.OrdinalIgnoreCase))
                {
                    info.Item = GetItemInfo(libraryItem, libraryItem, info.MediaSourceId);
                }
                else
                {
                    info.Item = current;
                }

                info.Item.RunTimeTicks = runtimeTicks;
            }

            session.NowPlayingItem = info.Item;
            session.LastActivityDate = DateTime.UtcNow;

            session.PlayState.IsPaused = info.IsPaused;
            session.PlayState.PositionTicks = info.PositionTicks;
            session.PlayState.MediaSourceId = info.MediaSourceId;
            session.PlayState.CanSeek = info.CanSeek;
            session.PlayState.IsMuted = info.IsMuted;
            session.PlayState.VolumeLevel = info.VolumeLevel;
            session.PlayState.AudioStreamIndex = info.AudioStreamIndex;
            session.PlayState.SubtitleStreamIndex = info.SubtitleStreamIndex;
            session.PlayState.PlayMethod = info.PlayMethod;
        }
Ejemplo n.º 16
0
        private async void OnSessionEnded(SessionInfo info)
        {
            try
            {
                await SendSessionEndedNotification(info, CancellationToken.None).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Error in SendSessionEndedNotification", ex);
            }

            EventHelper.QueueEventIfNotNull(SessionEnded, this, new SessionEventArgs
            {
                SessionInfo = info

            }, _logger);

            var disposable = info.SessionController as IDisposable;

            if (disposable != null)
            {
                _logger.Debug("Disposing session controller {0}", disposable.GetType().Name);

                try
                {
                    disposable.Dispose();
                }
                catch (Exception ex)
                {
                    _logger.ErrorException("Error disposing session controller", ex);
                }
            }
        }
Ejemplo n.º 17
0
        private void OnSessionStarted(SessionInfo info)
        {
            EventHelper.QueueEventIfNotNull(SessionStarted, this, new SessionEventArgs
            {
                SessionInfo = info

            }, _logger);

            if (!string.IsNullOrWhiteSpace(info.DeviceId))
            {
                var capabilities = GetSavedCapabilities(info.DeviceId);

                if (capabilities != null)
                {
                    ReportCapabilities(info, capabilities, false);
                }
            }
        }
Ejemplo n.º 18
0
        public SessionInfoDto GetSessionInfoDto(SessionInfo session)
        {
            var dto = new SessionInfoDto
            {
                Client = session.Client,
                DeviceId = session.DeviceId,
                DeviceName = session.DeviceName,
                Id = session.Id,
                LastActivityDate = session.LastActivityDate,
                NowViewingItem = session.NowViewingItem,
                ApplicationVersion = session.ApplicationVersion,
                QueueableMediaTypes = session.QueueableMediaTypes,
                PlayableMediaTypes = session.PlayableMediaTypes,
                AdditionalUsers = session.AdditionalUsers,
                SupportedCommands = session.SupportedCommands,
                UserName = session.UserName,
                NowPlayingItem = session.NowPlayingItem,
                SupportsRemoteControl = session.SupportsMediaControl,
                PlayState = session.PlayState,
                TranscodingInfo = session.NowPlayingItem == null ? null : session.TranscodingInfo
            };

            if (session.UserId.HasValue)
            {
                dto.UserId = session.UserId.Value.ToString("N");

                var user = _userManager.GetUserById(session.UserId.Value);

                if (user != null)
                {
                    dto.UserPrimaryImageTag = GetImageCacheTag(user, ImageType.Primary);
                }
            }

            return dto;
        }
Ejemplo n.º 19
0
        private async void ReportCapabilities(SessionInfo session,
            SessionCapabilities capabilities,
            bool saveCapabilities)
        {
            session.PlayableMediaTypes = capabilities.PlayableMediaTypes;
            session.SupportedCommands = capabilities.SupportedCommands;

            if (!string.IsNullOrWhiteSpace(capabilities.MessageCallbackUrl))
            {
                var controller = session.SessionController as HttpSessionController;

                if (controller == null)
                {
                    session.SessionController = new HttpSessionController(_httpClient, _jsonSerializer, session, capabilities.MessageCallbackUrl, this);
                }
            }

            EventHelper.FireEventIfNotNull(CapabilitiesChanged, this, new SessionEventArgs
            {
                SessionInfo = session

            }, _logger);

            if (saveCapabilities)
            {
                await SaveCapabilities(session.DeviceId, capabilities).ConfigureAwait(false);
            }
        }
Ejemplo n.º 20
0
        public Task SendPlaybackStoppedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
        {
            var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
            var dto = GetSessionInfoDto(sessionInfo);

            var tasks = sessions.Select(session => Task.Run(async () =>
            {
                try
                {
                    await session.SessionController.SendPlaybackStoppedNotification(dto, cancellationToken).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    _logger.ErrorException("Error in SendPlaybackStoppedNotification.", ex);
                }

            }, cancellationToken));

            return Task.WhenAll(tasks);
        }
Ejemplo n.º 21
0
 /// <summary>
 /// Gets the controllers.
 /// </summary>
 /// <param name="session">The session.</param>
 /// <returns>IEnumerable{ISessionRemoteController}.</returns>
 private IEnumerable<ISessionRemoteController> GetControllers(SessionInfo session)
 {
     return _remoteControllers.Where(i => i.Supports(session));
 }
Ejemplo n.º 22
0
 public WebSocketController(SessionInfo session, IServerApplicationHost appHost)
 {
     Session = session;
     _appHost = appHost;
     Sockets = new List<IWebSocketConnection>();
 }
Ejemplo n.º 23
0
        public SessionInfoDto GetSessionInfoDto(SessionInfo session)
        {
            var dto = new SessionInfoDto
            {
                Client = session.Client,
                DeviceId = session.DeviceId,
                DeviceName = session.DeviceName,
                Id = session.Id.ToString("N"),
                LastActivityDate = session.LastActivityDate,
                NowPlayingPositionTicks = session.NowPlayingPositionTicks,
                SupportsRemoteControl = session.SupportsRemoteControl,
                IsPaused = session.IsPaused,
                IsMuted = session.IsMuted,
                NowViewingContext = session.NowViewingContext,
                NowViewingItemId = session.NowViewingItemId,
                NowViewingItemName = session.NowViewingItemName,
                NowViewingItemType = session.NowViewingItemType,
                ApplicationVersion = session.ApplicationVersion,
                CanSeek = session.CanSeek,
                QueueableMediaTypes = session.QueueableMediaTypes,
                PlayableMediaTypes = session.PlayableMediaTypes,
                RemoteEndPoint = session.RemoteEndPoint,
                AdditionalUsers = session.AdditionalUsers
            };

            if (session.NowPlayingItem != null)
            {
                dto.NowPlayingItem = GetBaseItemInfo(session.NowPlayingItem);
            }

            if (session.UserId.HasValue)
            {
                dto.UserId = session.UserId.Value.ToString("N");
            }
            dto.UserName = session.UserName;

            return dto;
        }
Ejemplo n.º 24
0
 /// <summary>
 /// Removes the now playing item id.
 /// </summary>
 /// <param name="session">The session.</param>
 /// <param name="item">The item.</param>
 private void RemoveNowPlayingItem(SessionInfo session, BaseItem item)
 {
     if (session.NowPlayingItem != null && session.NowPlayingItem.Id == item.Id)
     {
         session.NowPlayingItem = null;
         session.NowPlayingPositionTicks = null;
         session.IsPaused = null;
     }
 }
Ejemplo n.º 25
0
        private List<User> GetUsers(SessionInfo session)
        {
            var users = new List<User>();

            if (session.UserId.HasValue)
            {
                var user = _userManager.GetUserById(session.UserId.Value);

                if (user == null)
                {
                    throw new InvalidOperationException("User not found");
                }

                users.Add(user);

                var additionalUsers = session.AdditionalUsers
                    .Select(i => _userManager.GetUserById(new Guid(i.UserId)))
                    .Where(i => i != null);

                users.AddRange(additionalUsers);
            }

            return users;
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Removes the now playing item id.
        /// </summary>
        /// <param name="session">The session.</param>
        /// <exception cref="System.ArgumentNullException">item</exception>
        private void RemoveNowPlayingItem(SessionInfo session)
        {
            session.NowPlayingItem = null;
            session.PlayState = new PlayerStateInfo();

            if (!string.IsNullOrEmpty(session.DeviceId))
            {
                ClearTranscodingInfo(session.DeviceId);
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Gets the connection.
        /// </summary>
        /// <param name="clientType">Type of the client.</param>
        /// <param name="appVersion">The app version.</param>
        /// <param name="deviceId">The device id.</param>
        /// <param name="deviceName">Name of the device.</param>
        /// <param name="remoteEndPoint">The remote end point.</param>
        /// <param name="userId">The user identifier.</param>
        /// <param name="username">The username.</param>
        /// <returns>SessionInfo.</returns>
        private async Task<SessionInfo> GetSessionInfo(string clientType, string appVersion, string deviceId, string deviceName, string remoteEndPoint, Guid? userId, string username)
        {
            var key = GetSessionKey(clientType, appVersion, deviceId);

            await _sessionLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);

            try
            {
                var connection = _activeConnections.GetOrAdd(key, keyName =>
                {
                    var sessionInfo = new SessionInfo
                    {
                        Client = clientType,
                        DeviceId = deviceId,
                        ApplicationVersion = appVersion,
                        Id = Guid.NewGuid().ToString("N")
                    };

                    OnSessionStarted(sessionInfo);

                    return sessionInfo;
                });

                connection.DeviceName = deviceName;
                connection.UserId = userId;
                connection.UserName = username;
                connection.RemoteEndPoint = remoteEndPoint;

                if (!userId.HasValue)
                {
                    connection.AdditionalUsers.Clear();
                }

                if (connection.SessionController == null)
                {
                    connection.SessionController = _sessionFactories
                        .Select(i => i.GetSessionController(connection))
                        .FirstOrDefault(i => i != null);
                }

                return connection;
            }
            finally
            {
                _sessionLock.Release();
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Removes the now playing item id.
        /// </summary>
        /// <param name="session">The session.</param>
        /// <param name="item">The item.</param>
        private void RemoveNowPlayingItem(SessionInfo session, BaseItem item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }

            if (session.NowPlayingItem != null && session.NowPlayingItem.Id == item.Id)
            {
                session.NowPlayingItem = null;
                session.NowPlayingPositionTicks = null;
                session.IsPaused = false;
            }
        }
Ejemplo n.º 29
0
 private void AssertCanControl(SessionInfo session, SessionInfo controllingSession)
 {
     if (session == null)
     {
         throw new ArgumentNullException("session");
     }
     if (controllingSession == null)
     {
         throw new ArgumentNullException("controllingSession");
     }
 }
Ejemplo n.º 30
0
 /// <summary>
 /// Updates the now playing item id.
 /// </summary>
 /// <param name="session">The session.</param>
 /// <param name="item">The item.</param>
 /// <param name="isPaused">if set to <c>true</c> [is paused].</param>
 /// <param name="currentPositionTicks">The current position ticks.</param>
 private void UpdateNowPlayingItem(SessionInfo session, BaseItem item, bool isPaused, long? currentPositionTicks = null)
 {
     session.IsPaused = isPaused;
     session.NowPlayingPositionTicks = currentPositionTicks;
     session.NowPlayingItem = item;
     session.LastActivityDate = DateTime.UtcNow;
 }