SessionInfo.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text.Json.Serialization;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using MediaBrowser.Controller.Entities;
  10. using MediaBrowser.Model.Dto;
  11. using MediaBrowser.Model.Session;
  12. using Microsoft.Extensions.Logging;
  13. namespace MediaBrowser.Controller.Session
  14. {
  15. /// <summary>
  16. /// Class SessionInfo.
  17. /// </summary>
  18. public sealed class SessionInfo : IAsyncDisposable, IDisposable
  19. {
  20. // 1 second
  21. private const long ProgressIncrement = 10000000;
  22. private readonly ISessionManager _sessionManager;
  23. private readonly ILogger _logger;
  24. private readonly object _progressLock = new object();
  25. private Timer _progressTimer;
  26. private PlaybackProgressInfo _lastProgressInfo;
  27. private bool _disposed = false;
  28. public SessionInfo(ISessionManager sessionManager, ILogger logger)
  29. {
  30. _sessionManager = sessionManager;
  31. _logger = logger;
  32. AdditionalUsers = Array.Empty<SessionUserInfo>();
  33. PlayState = new PlayerStateInfo();
  34. SessionControllers = Array.Empty<ISessionController>();
  35. NowPlayingQueue = Array.Empty<QueueItem>();
  36. NowPlayingQueueFullItems = Array.Empty<BaseItemDto>();
  37. }
  38. public PlayerStateInfo PlayState { get; set; }
  39. public SessionUserInfo[] AdditionalUsers { get; set; }
  40. public ClientCapabilities Capabilities { get; set; }
  41. /// <summary>
  42. /// Gets or sets the remote end point.
  43. /// </summary>
  44. /// <value>The remote end point.</value>
  45. public string RemoteEndPoint { get; set; }
  46. /// <summary>
  47. /// Gets the playable media types.
  48. /// </summary>
  49. /// <value>The playable media types.</value>
  50. public IReadOnlyList<string> PlayableMediaTypes
  51. {
  52. get
  53. {
  54. if (Capabilities is null)
  55. {
  56. return Array.Empty<string>();
  57. }
  58. return Capabilities.PlayableMediaTypes;
  59. }
  60. }
  61. /// <summary>
  62. /// Gets or sets the id.
  63. /// </summary>
  64. /// <value>The id.</value>
  65. public string Id { get; set; }
  66. /// <summary>
  67. /// Gets or sets the user id.
  68. /// </summary>
  69. /// <value>The user id.</value>
  70. public Guid UserId { get; set; }
  71. /// <summary>
  72. /// Gets or sets the username.
  73. /// </summary>
  74. /// <value>The username.</value>
  75. public string UserName { get; set; }
  76. /// <summary>
  77. /// Gets or sets the type of the client.
  78. /// </summary>
  79. /// <value>The type of the client.</value>
  80. public string Client { get; set; }
  81. /// <summary>
  82. /// Gets or sets the last activity date.
  83. /// </summary>
  84. /// <value>The last activity date.</value>
  85. public DateTime LastActivityDate { get; set; }
  86. /// <summary>
  87. /// Gets or sets the last playback check in.
  88. /// </summary>
  89. /// <value>The last playback check in.</value>
  90. public DateTime LastPlaybackCheckIn { get; set; }
  91. /// <summary>
  92. /// Gets or sets the last paused date.
  93. /// </summary>
  94. /// <value>The last paused date.</value>
  95. public DateTime? LastPausedDate { get; set; }
  96. /// <summary>
  97. /// Gets or sets the name of the device.
  98. /// </summary>
  99. /// <value>The name of the device.</value>
  100. public string DeviceName { get; set; }
  101. /// <summary>
  102. /// Gets or sets the type of the device.
  103. /// </summary>
  104. /// <value>The type of the device.</value>
  105. public string DeviceType { get; set; }
  106. /// <summary>
  107. /// Gets or sets the now playing item.
  108. /// </summary>
  109. /// <value>The now playing item.</value>
  110. public BaseItemDto NowPlayingItem { get; set; }
  111. public BaseItem FullNowPlayingItem { get; set; }
  112. public BaseItemDto NowViewingItem { get; set; }
  113. /// <summary>
  114. /// Gets or sets the device id.
  115. /// </summary>
  116. /// <value>The device id.</value>
  117. public string DeviceId { get; set; }
  118. /// <summary>
  119. /// Gets or sets the application version.
  120. /// </summary>
  121. /// <value>The application version.</value>
  122. public string ApplicationVersion { get; set; }
  123. /// <summary>
  124. /// Gets or sets the session controller.
  125. /// </summary>
  126. /// <value>The session controller.</value>
  127. [JsonIgnore]
  128. public ISessionController[] SessionControllers { get; set; }
  129. public TranscodingInfo TranscodingInfo { get; set; }
  130. /// <summary>
  131. /// Gets a value indicating whether this instance is active.
  132. /// </summary>
  133. /// <value><c>true</c> if this instance is active; otherwise, <c>false</c>.</value>
  134. public bool IsActive
  135. {
  136. get
  137. {
  138. var controllers = SessionControllers;
  139. foreach (var controller in controllers)
  140. {
  141. if (controller.IsSessionActive)
  142. {
  143. return true;
  144. }
  145. }
  146. if (controllers.Length > 0)
  147. {
  148. return false;
  149. }
  150. return true;
  151. }
  152. }
  153. public bool SupportsMediaControl
  154. {
  155. get
  156. {
  157. if (Capabilities is null || !Capabilities.SupportsMediaControl)
  158. {
  159. return false;
  160. }
  161. var controllers = SessionControllers;
  162. foreach (var controller in controllers)
  163. {
  164. if (controller.SupportsMediaControl)
  165. {
  166. return true;
  167. }
  168. }
  169. return false;
  170. }
  171. }
  172. public bool SupportsRemoteControl
  173. {
  174. get
  175. {
  176. if (Capabilities is null || !Capabilities.SupportsMediaControl)
  177. {
  178. return false;
  179. }
  180. var controllers = SessionControllers;
  181. foreach (var controller in controllers)
  182. {
  183. if (controller.SupportsMediaControl)
  184. {
  185. return true;
  186. }
  187. }
  188. return false;
  189. }
  190. }
  191. public IReadOnlyList<QueueItem> NowPlayingQueue { get; set; }
  192. public IReadOnlyList<BaseItemDto> NowPlayingQueueFullItems { get; set; }
  193. public bool HasCustomDeviceName { get; set; }
  194. public string PlaylistItemId { get; set; }
  195. public string ServerId { get; set; }
  196. public string UserPrimaryImageTag { get; set; }
  197. /// <summary>
  198. /// Gets the supported commands.
  199. /// </summary>
  200. /// <value>The supported commands.</value>
  201. public IReadOnlyList<GeneralCommandType> SupportedCommands
  202. => Capabilities is null ? Array.Empty<GeneralCommandType>() : Capabilities.SupportedCommands;
  203. public Tuple<ISessionController, bool> EnsureController<T>(Func<SessionInfo, ISessionController> factory)
  204. {
  205. var controllers = SessionControllers.ToList();
  206. foreach (var controller in controllers)
  207. {
  208. if (controller is T)
  209. {
  210. return new Tuple<ISessionController, bool>(controller, false);
  211. }
  212. }
  213. var newController = factory(this);
  214. _logger.LogDebug("Creating new {0}", newController.GetType().Name);
  215. controllers.Add(newController);
  216. SessionControllers = controllers.ToArray();
  217. return new Tuple<ISessionController, bool>(newController, true);
  218. }
  219. public void AddController(ISessionController controller)
  220. {
  221. var controllers = SessionControllers.ToList();
  222. controllers.Add(controller);
  223. SessionControllers = controllers.ToArray();
  224. }
  225. public bool ContainsUser(Guid userId)
  226. {
  227. if (UserId.Equals(userId))
  228. {
  229. return true;
  230. }
  231. foreach (var additionalUser in AdditionalUsers)
  232. {
  233. if (additionalUser.UserId.Equals(userId))
  234. {
  235. return true;
  236. }
  237. }
  238. return false;
  239. }
  240. public void StartAutomaticProgress(PlaybackProgressInfo progressInfo)
  241. {
  242. if (_disposed)
  243. {
  244. return;
  245. }
  246. lock (_progressLock)
  247. {
  248. _lastProgressInfo = progressInfo;
  249. if (_progressTimer is null)
  250. {
  251. _progressTimer = new Timer(OnProgressTimerCallback, null, 1000, 1000);
  252. }
  253. else
  254. {
  255. _progressTimer.Change(1000, 1000);
  256. }
  257. }
  258. }
  259. private async void OnProgressTimerCallback(object state)
  260. {
  261. if (_disposed)
  262. {
  263. return;
  264. }
  265. var progressInfo = _lastProgressInfo;
  266. if (progressInfo is null)
  267. {
  268. return;
  269. }
  270. if (progressInfo.IsPaused)
  271. {
  272. return;
  273. }
  274. var positionTicks = progressInfo.PositionTicks ?? 0;
  275. if (positionTicks < 0)
  276. {
  277. positionTicks = 0;
  278. }
  279. var newPositionTicks = positionTicks + ProgressIncrement;
  280. var item = progressInfo.Item;
  281. long? runtimeTicks = item?.RunTimeTicks;
  282. // Don't report beyond the runtime
  283. if (runtimeTicks.HasValue && newPositionTicks >= runtimeTicks.Value)
  284. {
  285. return;
  286. }
  287. progressInfo.PositionTicks = newPositionTicks;
  288. try
  289. {
  290. await _sessionManager.OnPlaybackProgress(progressInfo, true).ConfigureAwait(false);
  291. }
  292. catch (Exception ex)
  293. {
  294. _logger.LogError(ex, "Error reporting playback progress");
  295. }
  296. }
  297. public void StopAutomaticProgress()
  298. {
  299. lock (_progressLock)
  300. {
  301. if (_progressTimer is not null)
  302. {
  303. _progressTimer.Dispose();
  304. _progressTimer = null;
  305. }
  306. _lastProgressInfo = null;
  307. }
  308. }
  309. /// <inheritdoc />
  310. public void Dispose()
  311. {
  312. _disposed = true;
  313. StopAutomaticProgress();
  314. var controllers = SessionControllers.ToList();
  315. SessionControllers = Array.Empty<ISessionController>();
  316. foreach (var controller in controllers)
  317. {
  318. if (controller is IDisposable disposable)
  319. {
  320. _logger.LogDebug("Disposing session controller synchronously {TypeName}", disposable.GetType().Name);
  321. disposable.Dispose();
  322. }
  323. }
  324. }
  325. public async ValueTask DisposeAsync()
  326. {
  327. _disposed = true;
  328. StopAutomaticProgress();
  329. var controllers = SessionControllers.ToList();
  330. foreach (var controller in controllers)
  331. {
  332. if (controller is IAsyncDisposable disposableAsync)
  333. {
  334. _logger.LogDebug("Disposing session controller asynchronously {TypeName}", disposableAsync.GetType().Name);
  335. await disposableAsync.DisposeAsync().ConfigureAwait(false);
  336. }
  337. }
  338. }
  339. }
  340. }