SessionInfo.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. #nullable disable
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text.Json.Serialization;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using Jellyfin.Data.Enums;
  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
  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();
  25. private Timer _progressTimer;
  26. private PlaybackProgressInfo _lastProgressInfo;
  27. private bool _disposed;
  28. /// <summary>
  29. /// Initializes a new instance of the <see cref="SessionInfo"/> class.
  30. /// </summary>
  31. /// <param name="sessionManager">Instance of <see cref="ISessionManager"/> interface.</param>
  32. /// <param name="logger">Instance of <see cref="ILogger"/> interface.</param>
  33. public SessionInfo(ISessionManager sessionManager, ILogger logger)
  34. {
  35. _sessionManager = sessionManager;
  36. _logger = logger;
  37. AdditionalUsers = [];
  38. PlayState = new PlayerStateInfo();
  39. SessionControllers = [];
  40. NowPlayingQueue = [];
  41. NowPlayingQueueFullItems = [];
  42. }
  43. /// <summary>
  44. /// Gets or sets the play state.
  45. /// </summary>
  46. /// <value>The play state.</value>
  47. public PlayerStateInfo PlayState { get; set; }
  48. /// <summary>
  49. /// Gets or sets the additional users.
  50. /// </summary>
  51. /// <value>The additional users.</value>
  52. public IReadOnlyList<SessionUserInfo> AdditionalUsers { get; set; }
  53. /// <summary>
  54. /// Gets or sets the client capabilities.
  55. /// </summary>
  56. /// <value>The client capabilities.</value>
  57. public ClientCapabilities Capabilities { get; set; }
  58. /// <summary>
  59. /// Gets or sets the remote end point.
  60. /// </summary>
  61. /// <value>The remote end point.</value>
  62. public string RemoteEndPoint { get; set; }
  63. /// <summary>
  64. /// Gets the playable media types.
  65. /// </summary>
  66. /// <value>The playable media types.</value>
  67. public IReadOnlyList<MediaType> PlayableMediaTypes
  68. {
  69. get
  70. {
  71. if (Capabilities is null)
  72. {
  73. return [];
  74. }
  75. return Capabilities.PlayableMediaTypes;
  76. }
  77. }
  78. /// <summary>
  79. /// Gets or sets the id.
  80. /// </summary>
  81. /// <value>The id.</value>
  82. public string Id { get; set; }
  83. /// <summary>
  84. /// Gets or sets the user id.
  85. /// </summary>
  86. /// <value>The user id.</value>
  87. public Guid UserId { get; set; }
  88. /// <summary>
  89. /// Gets or sets the username.
  90. /// </summary>
  91. /// <value>The username.</value>
  92. public string UserName { get; set; }
  93. /// <summary>
  94. /// Gets or sets the type of the client.
  95. /// </summary>
  96. /// <value>The type of the client.</value>
  97. public string Client { get; set; }
  98. /// <summary>
  99. /// Gets or sets the last activity date.
  100. /// </summary>
  101. /// <value>The last activity date.</value>
  102. public DateTime LastActivityDate { get; set; }
  103. /// <summary>
  104. /// Gets or sets the last playback check in.
  105. /// </summary>
  106. /// <value>The last playback check in.</value>
  107. public DateTime LastPlaybackCheckIn { get; set; }
  108. /// <summary>
  109. /// Gets or sets the last paused date.
  110. /// </summary>
  111. /// <value>The last paused date.</value>
  112. public DateTime? LastPausedDate { get; set; }
  113. /// <summary>
  114. /// Gets or sets the name of the device.
  115. /// </summary>
  116. /// <value>The name of the device.</value>
  117. public string DeviceName { get; set; }
  118. /// <summary>
  119. /// Gets or sets the type of the device.
  120. /// </summary>
  121. /// <value>The type of the device.</value>
  122. public string DeviceType { get; set; }
  123. /// <summary>
  124. /// Gets or sets the now playing item.
  125. /// </summary>
  126. /// <value>The now playing item.</value>
  127. public BaseItemDto NowPlayingItem { get; set; }
  128. /// <summary>
  129. /// Gets or sets the now playing queue full items.
  130. /// </summary>
  131. /// <value>The now playing queue full items.</value>
  132. [JsonIgnore]
  133. public BaseItem FullNowPlayingItem { get; set; }
  134. /// <summary>
  135. /// Gets or sets the now viewing item.
  136. /// </summary>
  137. /// <value>The now viewing item.</value>
  138. public BaseItemDto NowViewingItem { get; set; }
  139. /// <summary>
  140. /// Gets or sets the device id.
  141. /// </summary>
  142. /// <value>The device id.</value>
  143. public string DeviceId { get; set; }
  144. /// <summary>
  145. /// Gets or sets the application version.
  146. /// </summary>
  147. /// <value>The application version.</value>
  148. public string ApplicationVersion { get; set; }
  149. /// <summary>
  150. /// Gets or sets the session controller.
  151. /// </summary>
  152. /// <value>The session controller.</value>
  153. [JsonIgnore]
  154. public IReadOnlyList<ISessionController> SessionControllers { get; set; }
  155. /// <summary>
  156. /// Gets or sets the transcoding info.
  157. /// </summary>
  158. /// <value>The transcoding info.</value>
  159. public TranscodingInfo TranscodingInfo { get; set; }
  160. /// <summary>
  161. /// Gets a value indicating whether this instance is active.
  162. /// </summary>
  163. /// <value><c>true</c> if this instance is active; otherwise, <c>false</c>.</value>
  164. public bool IsActive
  165. {
  166. get
  167. {
  168. var controllers = SessionControllers;
  169. foreach (var controller in controllers)
  170. {
  171. if (controller.IsSessionActive)
  172. {
  173. return true;
  174. }
  175. }
  176. if (controllers.Count > 0)
  177. {
  178. return false;
  179. }
  180. return true;
  181. }
  182. }
  183. /// <summary>
  184. /// Gets a value indicating whether the session supports media control.
  185. /// </summary>
  186. /// <value><c>true</c> if this session supports media control; otherwise, <c>false</c>.</value>
  187. public bool SupportsMediaControl
  188. {
  189. get
  190. {
  191. if (Capabilities is null || !Capabilities.SupportsMediaControl)
  192. {
  193. return false;
  194. }
  195. var controllers = SessionControllers;
  196. foreach (var controller in controllers)
  197. {
  198. if (controller.SupportsMediaControl)
  199. {
  200. return true;
  201. }
  202. }
  203. return false;
  204. }
  205. }
  206. /// <summary>
  207. /// Gets a value indicating whether the session supports remote control.
  208. /// </summary>
  209. /// <value><c>true</c> if this session supports remote control; otherwise, <c>false</c>.</value>
  210. public bool SupportsRemoteControl
  211. {
  212. get
  213. {
  214. if (Capabilities is null || !Capabilities.SupportsMediaControl)
  215. {
  216. return false;
  217. }
  218. var controllers = SessionControllers;
  219. foreach (var controller in controllers)
  220. {
  221. if (controller.SupportsMediaControl)
  222. {
  223. return true;
  224. }
  225. }
  226. return false;
  227. }
  228. }
  229. /// <summary>
  230. /// Gets or sets the now playing queue.
  231. /// </summary>
  232. /// <value>The now playing queue.</value>
  233. public IReadOnlyList<QueueItem> NowPlayingQueue { get; set; }
  234. /// <summary>
  235. /// Gets or sets the now playing queue full items.
  236. /// </summary>
  237. /// <value>The now playing queue full items.</value>
  238. public IReadOnlyList<BaseItemDto> NowPlayingQueueFullItems { get; set; }
  239. /// <summary>
  240. /// Gets or sets a value indicating whether the session has a custom device name.
  241. /// </summary>
  242. /// <value><c>true</c> if this session has a custom device name; otherwise, <c>false</c>.</value>
  243. public bool HasCustomDeviceName { get; set; }
  244. /// <summary>
  245. /// Gets or sets the playlist item id.
  246. /// </summary>
  247. /// <value>The splaylist item id.</value>
  248. public string PlaylistItemId { get; set; }
  249. /// <summary>
  250. /// Gets or sets the server id.
  251. /// </summary>
  252. /// <value>The server id.</value>
  253. public string ServerId { get; set; }
  254. /// <summary>
  255. /// Gets or sets the user primary image tag.
  256. /// </summary>
  257. /// <value>The user primary image tag.</value>
  258. public string UserPrimaryImageTag { get; set; }
  259. /// <summary>
  260. /// Gets the supported commands.
  261. /// </summary>
  262. /// <value>The supported commands.</value>
  263. public IReadOnlyList<GeneralCommandType> SupportedCommands
  264. => Capabilities is null ? [] : Capabilities.SupportedCommands;
  265. /// <summary>
  266. /// Ensures a controller of type exists.
  267. /// </summary>
  268. /// <typeparam name="T">Class to register.</typeparam>
  269. /// <param name="factory">The factory.</param>
  270. /// <returns>Tuple{ISessionController, bool}.</returns>
  271. public Tuple<ISessionController, bool> EnsureController<T>(Func<SessionInfo, ISessionController> factory)
  272. {
  273. var controllers = SessionControllers.ToList();
  274. foreach (var controller in controllers)
  275. {
  276. if (controller is T)
  277. {
  278. return new Tuple<ISessionController, bool>(controller, false);
  279. }
  280. }
  281. var newController = factory(this);
  282. _logger.LogDebug("Creating new {Factory}", newController.GetType().Name);
  283. controllers.Add(newController);
  284. SessionControllers = [.. controllers];
  285. return new Tuple<ISessionController, bool>(newController, true);
  286. }
  287. /// <summary>
  288. /// Adds a controller to the session.
  289. /// </summary>
  290. /// <param name="controller">The controller.</param>
  291. public void AddController(ISessionController controller)
  292. {
  293. SessionControllers = [.. SessionControllers, controller];
  294. }
  295. /// <summary>
  296. /// Gets a value indicating whether the session contains a user.
  297. /// </summary>
  298. /// <param name="userId">The user id to check.</param>
  299. /// <returns><c>true</c> if this session contains the user; otherwise, <c>false</c>.</returns>
  300. public bool ContainsUser(Guid userId)
  301. {
  302. if (UserId.Equals(userId))
  303. {
  304. return true;
  305. }
  306. foreach (var additionalUser in AdditionalUsers)
  307. {
  308. if (additionalUser.UserId.Equals(userId))
  309. {
  310. return true;
  311. }
  312. }
  313. return false;
  314. }
  315. /// <summary>
  316. /// Starts automatic progressing.
  317. /// </summary>
  318. /// <param name="progressInfo">The playback progress info.</param>
  319. /// <value>The supported commands.</value>
  320. public void StartAutomaticProgress(PlaybackProgressInfo progressInfo)
  321. {
  322. if (_disposed)
  323. {
  324. return;
  325. }
  326. lock (_progressLock)
  327. {
  328. _lastProgressInfo = progressInfo;
  329. if (_progressTimer is null)
  330. {
  331. _progressTimer = new Timer(OnProgressTimerCallback, null, 1000, 1000);
  332. }
  333. else
  334. {
  335. _progressTimer.Change(1000, 1000);
  336. }
  337. }
  338. }
  339. private async void OnProgressTimerCallback(object state)
  340. {
  341. if (_disposed)
  342. {
  343. return;
  344. }
  345. var progressInfo = _lastProgressInfo;
  346. if (progressInfo is null)
  347. {
  348. return;
  349. }
  350. if (progressInfo.IsPaused)
  351. {
  352. return;
  353. }
  354. var positionTicks = progressInfo.PositionTicks ?? 0;
  355. if (positionTicks < 0)
  356. {
  357. positionTicks = 0;
  358. }
  359. var newPositionTicks = positionTicks + ProgressIncrement;
  360. var item = progressInfo.Item;
  361. long? runtimeTicks = item?.RunTimeTicks;
  362. // Don't report beyond the runtime
  363. if (runtimeTicks.HasValue && newPositionTicks >= runtimeTicks.Value)
  364. {
  365. return;
  366. }
  367. progressInfo.PositionTicks = newPositionTicks;
  368. try
  369. {
  370. await _sessionManager.OnPlaybackProgress(progressInfo, true).ConfigureAwait(false);
  371. }
  372. catch (Exception ex)
  373. {
  374. _logger.LogError(ex, "Error reporting playback progress");
  375. }
  376. }
  377. /// <summary>
  378. /// Stops automatic progressing.
  379. /// </summary>
  380. public void StopAutomaticProgress()
  381. {
  382. lock (_progressLock)
  383. {
  384. if (_progressTimer is not null)
  385. {
  386. _progressTimer.Dispose();
  387. _progressTimer = null;
  388. }
  389. _lastProgressInfo = null;
  390. }
  391. }
  392. /// <summary>
  393. /// Disposes the instance async.
  394. /// </summary>
  395. /// <returns>ValueTask.</returns>
  396. public async ValueTask DisposeAsync()
  397. {
  398. _disposed = true;
  399. StopAutomaticProgress();
  400. var controllers = SessionControllers.ToList();
  401. SessionControllers = [];
  402. foreach (var controller in controllers)
  403. {
  404. if (controller is IAsyncDisposable disposableAsync)
  405. {
  406. _logger.LogDebug("Disposing session controller asynchronously {TypeName}", disposableAsync.GetType().Name);
  407. await disposableAsync.DisposeAsync().ConfigureAwait(false);
  408. }
  409. else if (controller is IDisposable disposable)
  410. {
  411. _logger.LogDebug("Disposing session controller synchronously {TypeName}", disposable.GetType().Name);
  412. disposable.Dispose();
  413. }
  414. }
  415. }
  416. }
  417. }