GroupController.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using Jellyfin.Data.Entities;
  8. using Jellyfin.Data.Enums;
  9. using MediaBrowser.Controller.Entities;
  10. using MediaBrowser.Controller.Library;
  11. using MediaBrowser.Controller.Session;
  12. using MediaBrowser.Controller.SyncPlay;
  13. using MediaBrowser.Model.SyncPlay;
  14. using Microsoft.Extensions.Logging;
  15. namespace Emby.Server.Implementations.SyncPlay
  16. {
  17. /// <summary>
  18. /// Class SyncPlayGroupController.
  19. /// </summary>
  20. /// <remarks>
  21. /// Class is not thread-safe, external locking is required when accessing methods.
  22. /// </remarks>
  23. public class SyncPlayGroupController : ISyncPlayGroupController, ISyncPlayStateContext
  24. {
  25. /// <summary>
  26. /// Gets the default ping value used for sessions.
  27. /// </summary>
  28. public long DefaultPing { get; } = 500;
  29. /// <summary>
  30. /// The logger.
  31. /// </summary>
  32. private readonly ILogger _logger;
  33. /// <summary>
  34. /// The user manager.
  35. /// </summary>
  36. private readonly IUserManager _userManager;
  37. /// <summary>
  38. /// The session manager.
  39. /// </summary>
  40. private readonly ISessionManager _sessionManager;
  41. /// <summary>
  42. /// The library manager.
  43. /// </summary>
  44. private readonly ILibraryManager _libraryManager;
  45. /// <summary>
  46. /// The SyncPlay manager.
  47. /// </summary>
  48. private readonly ISyncPlayManager _syncPlayManager;
  49. /// <summary>
  50. /// Internal group state.
  51. /// </summary>
  52. /// <value>The group's state.</value>
  53. private ISyncPlayState State;
  54. /// <summary>
  55. /// Gets the group identifier.
  56. /// </summary>
  57. /// <value>The group identifier.</value>
  58. public Guid GroupId { get; } = Guid.NewGuid();
  59. /// <summary>
  60. /// Gets the group name.
  61. /// </summary>
  62. /// <value>The group name.</value>
  63. public string GroupName { get; private set; }
  64. /// <summary>
  65. /// Gets the group identifier.
  66. /// </summary>
  67. /// <value>The group identifier.</value>
  68. public PlayQueueManager PlayQueue { get; } = new PlayQueueManager();
  69. /// <summary>
  70. /// Gets or sets the runtime ticks of current playing item.
  71. /// </summary>
  72. /// <value>The runtime ticks of current playing item.</value>
  73. public long RunTimeTicks { get; private set; }
  74. /// <summary>
  75. /// Gets or sets the position ticks.
  76. /// </summary>
  77. /// <value>The position ticks.</value>
  78. public long PositionTicks { get; set; }
  79. /// <summary>
  80. /// Gets or sets the last activity.
  81. /// </summary>
  82. /// <value>The last activity.</value>
  83. public DateTime LastActivity { get; set; }
  84. /// <summary>
  85. /// Gets the participants.
  86. /// </summary>
  87. /// <value>The participants, or members of the group.</value>
  88. public Dictionary<string, GroupMember> Participants { get; } =
  89. new Dictionary<string, GroupMember>(StringComparer.OrdinalIgnoreCase);
  90. /// <summary>
  91. /// Initializes a new instance of the <see cref="SyncPlayGroupController" /> class.
  92. /// </summary>
  93. /// <param name="logger">The logger.</param>
  94. /// <param name="userManager">The user manager.</param>
  95. /// <param name="sessionManager">The session manager.</param>
  96. /// <param name="libraryManager">The library manager.</param>
  97. /// <param name="syncPlayManager">The SyncPlay manager.</param>
  98. public SyncPlayGroupController(
  99. ILogger logger,
  100. IUserManager userManager,
  101. ISessionManager sessionManager,
  102. ILibraryManager libraryManager,
  103. ISyncPlayManager syncPlayManager)
  104. {
  105. _logger = logger;
  106. _userManager = userManager;
  107. _sessionManager = sessionManager;
  108. _libraryManager = libraryManager;
  109. _syncPlayManager = syncPlayManager;
  110. State = new IdleGroupState(_logger);
  111. }
  112. /// <summary>
  113. /// Adds the session to the group.
  114. /// </summary>
  115. /// <param name="session">The session.</param>
  116. private void AddSession(SessionInfo session)
  117. {
  118. Participants.TryAdd(
  119. session.Id,
  120. new GroupMember
  121. {
  122. Session = session,
  123. Ping = DefaultPing,
  124. IsBuffering = false
  125. });
  126. }
  127. /// <summary>
  128. /// Removes the session from the group.
  129. /// </summary>
  130. /// <param name="session">The session.</param>
  131. private void RemoveSession(SessionInfo session)
  132. {
  133. Participants.Remove(session.Id);
  134. }
  135. /// <summary>
  136. /// Filters sessions of this group.
  137. /// </summary>
  138. /// <param name="from">The current session.</param>
  139. /// <param name="type">The filtering type.</param>
  140. /// <returns>The array of sessions matching the filter.</returns>
  141. private SessionInfo[] FilterSessions(SessionInfo from, SyncPlayBroadcastType type)
  142. {
  143. switch (type)
  144. {
  145. case SyncPlayBroadcastType.CurrentSession:
  146. return new SessionInfo[] { from };
  147. case SyncPlayBroadcastType.AllGroup:
  148. return Participants
  149. .Values
  150. .Select(session => session.Session)
  151. .ToArray();
  152. case SyncPlayBroadcastType.AllExceptCurrentSession:
  153. return Participants
  154. .Values
  155. .Select(session => session.Session)
  156. .Where(session => !session.Id.Equals(from.Id))
  157. .ToArray();
  158. case SyncPlayBroadcastType.AllReady:
  159. return Participants
  160. .Values
  161. .Where(session => !session.IsBuffering)
  162. .Select(session => session.Session)
  163. .ToArray();
  164. default:
  165. return Array.Empty<SessionInfo>();
  166. }
  167. }
  168. private bool HasAccessToItem(User user, BaseItem item)
  169. {
  170. var collections = _libraryManager.GetCollectionFolders(item)
  171. .Select(folder => folder.Id.ToString("N", CultureInfo.InvariantCulture));
  172. return collections.Intersect(user.GetPreference(PreferenceKind.EnabledFolders)).Any();
  173. }
  174. private bool HasAccessToQueue(User user, Guid[] queue)
  175. {
  176. if (queue == null || queue.Length == 0)
  177. {
  178. return true;
  179. }
  180. var items = queue.ToList()
  181. .Select(item => _libraryManager.GetItemById(item));
  182. // Find the highest rating value, which becomes the required minimum for the user.
  183. var MinParentalRatingAccessRequired = items
  184. .Select(item => item.InheritedParentalRatingValue)
  185. .Min();
  186. // Check ParentalRating access, user must have the minimum required access level.
  187. var hasParentalRatingAccess = !user.MaxParentalAgeRating.HasValue
  188. || MinParentalRatingAccessRequired <= user.MaxParentalAgeRating;
  189. // Check that user has access to all required folders.
  190. if (!user.HasPermission(PermissionKind.EnableAllFolders) && hasParentalRatingAccess)
  191. {
  192. // Get list of items that are not accessible.
  193. var blockedItems = items.Where(item => !HasAccessToItem(user, item));
  194. // We need the user to be able to access all items.
  195. return !blockedItems.Any();
  196. }
  197. return hasParentalRatingAccess;
  198. }
  199. private bool AllUsersHaveAccessToQueue(Guid[] queue)
  200. {
  201. if (queue == null || queue.Length == 0)
  202. {
  203. return true;
  204. }
  205. // Get list of users.
  206. var users = Participants
  207. .Values
  208. .Select(participant => _userManager.GetUserById(participant.Session.UserId));
  209. // Find problematic users.
  210. var usersWithNoAccess = users.Where(user => !HasAccessToQueue(user, queue));
  211. // All users must be able to access the queue.
  212. return !usersWithNoAccess.Any();
  213. }
  214. /// <inheritdoc />
  215. public bool IsGroupEmpty() => Participants.Count == 0;
  216. /// <inheritdoc />
  217. public void CreateGroup(SessionInfo session, NewGroupRequest request, CancellationToken cancellationToken)
  218. {
  219. GroupName = request.GroupName;
  220. AddSession(session);
  221. _syncPlayManager.AddSessionToGroup(session, this);
  222. var sessionIsPlayingAnItem = session.FullNowPlayingItem != null;
  223. RestartCurrentItem();
  224. if (sessionIsPlayingAnItem)
  225. {
  226. var playlist = session.NowPlayingQueue.Select(item => item.Id).ToArray();
  227. PlayQueue.Reset();
  228. PlayQueue.SetPlaylist(playlist);
  229. PlayQueue.SetPlayingItemById(session.FullNowPlayingItem.Id);
  230. RunTimeTicks = session.FullNowPlayingItem.RunTimeTicks ?? 0;
  231. PositionTicks = session.PlayState.PositionTicks ?? 0;
  232. // Mantain playstate.
  233. var waitingState = new WaitingGroupState(_logger);
  234. waitingState.ResumePlaying = !session.PlayState.IsPaused;
  235. SetState(waitingState);
  236. }
  237. var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupJoined, GetInfo());
  238. SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, updateSession, cancellationToken);
  239. State.SessionJoined(this, State.GetGroupState(), session, cancellationToken);
  240. _logger.LogInformation("InitGroup: {0} created group {1}.", session.Id.ToString(), GroupId.ToString());
  241. }
  242. /// <inheritdoc />
  243. public void SessionJoin(SessionInfo session, JoinGroupRequest request, CancellationToken cancellationToken)
  244. {
  245. AddSession(session);
  246. _syncPlayManager.AddSessionToGroup(session, this);
  247. var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupJoined, GetInfo());
  248. SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, updateSession, cancellationToken);
  249. var updateOthers = NewSyncPlayGroupUpdate(GroupUpdateType.UserJoined, session.UserName);
  250. SendGroupUpdate(session, SyncPlayBroadcastType.AllExceptCurrentSession, updateOthers, cancellationToken);
  251. State.SessionJoined(this, State.GetGroupState(), session, cancellationToken);
  252. _logger.LogInformation("SessionJoin: {0} joined group {1}.", session.Id.ToString(), GroupId.ToString());
  253. }
  254. /// <inheritdoc />
  255. public void SessionRestore(SessionInfo session, JoinGroupRequest request, CancellationToken cancellationToken)
  256. {
  257. var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupJoined, GetInfo());
  258. SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, updateSession, cancellationToken);
  259. var updateOthers = NewSyncPlayGroupUpdate(GroupUpdateType.UserJoined, session.UserName);
  260. SendGroupUpdate(session, SyncPlayBroadcastType.AllExceptCurrentSession, updateOthers, cancellationToken);
  261. State.SessionJoined(this, State.GetGroupState(), session, cancellationToken);
  262. _logger.LogInformation("SessionRestore: {0} re-joined group {1}.", session.Id.ToString(), GroupId.ToString());
  263. }
  264. /// <inheritdoc />
  265. public void SessionLeave(SessionInfo session, CancellationToken cancellationToken)
  266. {
  267. State.SessionLeaving(this, State.GetGroupState(), session, cancellationToken);
  268. RemoveSession(session);
  269. _syncPlayManager.RemoveSessionFromGroup(session, this);
  270. var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupLeft, GroupId.ToString());
  271. SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, updateSession, cancellationToken);
  272. var updateOthers = NewSyncPlayGroupUpdate(GroupUpdateType.UserLeft, session.UserName);
  273. SendGroupUpdate(session, SyncPlayBroadcastType.AllExceptCurrentSession, updateOthers, cancellationToken);
  274. _logger.LogInformation("SessionLeave: {0} left group {1}.", session.Id.ToString(), GroupId.ToString());
  275. }
  276. /// <inheritdoc />
  277. public void HandleRequest(SessionInfo session, IPlaybackGroupRequest request, CancellationToken cancellationToken)
  278. {
  279. // The server's job is to maintain a consistent state for clients to reference
  280. // and notify clients of state changes. The actual syncing of media playback
  281. // happens client side. Clients are aware of the server's time and use it to sync.
  282. _logger.LogInformation("HandleRequest: {0} requested {1}, group {2} in {3} state.",
  283. session.Id.ToString(), request.GetRequestType(), GroupId.ToString(), State.GetGroupState());
  284. request.Apply(this, State, session, cancellationToken);
  285. }
  286. /// <inheritdoc />
  287. public GroupInfoDto GetInfo()
  288. {
  289. return new GroupInfoDto()
  290. {
  291. GroupId = GroupId.ToString(),
  292. GroupName = GroupName,
  293. State = State.GetGroupState(),
  294. Participants = Participants.Values.Select(session => session.Session.UserName).Distinct().ToList(),
  295. LastUpdatedAt = DateToUTCString(DateTime.UtcNow)
  296. };
  297. }
  298. /// <inheritdoc />
  299. public bool HasAccessToPlayQueue(User user)
  300. {
  301. var items = PlayQueue.GetPlaylist().Select(item => item.ItemId).ToArray();
  302. return HasAccessToQueue(user, items);
  303. }
  304. /// <inheritdoc />
  305. public void SetIgnoreGroupWait(SessionInfo session, bool ignoreGroupWait)
  306. {
  307. if (!Participants.ContainsKey(session.Id))
  308. {
  309. return;
  310. }
  311. Participants[session.Id].IgnoreGroupWait = ignoreGroupWait;
  312. }
  313. /// <inheritdoc />
  314. public void SetState(ISyncPlayState state)
  315. {
  316. _logger.LogInformation("SetState: {0} switching from {1} to {2}.", GroupId.ToString(), State.GetGroupState(), state.GetGroupState());
  317. this.State = state;
  318. }
  319. /// <inheritdoc />
  320. public Task SendGroupUpdate<T>(SessionInfo from, SyncPlayBroadcastType type, GroupUpdate<T> message, CancellationToken cancellationToken)
  321. {
  322. IEnumerable<Task> GetTasks()
  323. {
  324. foreach (var session in FilterSessions(from, type))
  325. {
  326. yield return _sessionManager.SendSyncPlayGroupUpdate(session, message, cancellationToken);
  327. }
  328. }
  329. return Task.WhenAll(GetTasks());
  330. }
  331. /// <inheritdoc />
  332. public Task SendCommand(SessionInfo from, SyncPlayBroadcastType type, SendCommand message, CancellationToken cancellationToken)
  333. {
  334. IEnumerable<Task> GetTasks()
  335. {
  336. foreach (var session in FilterSessions(from, type))
  337. {
  338. yield return _sessionManager.SendSyncPlayCommand(session, message, cancellationToken);
  339. }
  340. }
  341. return Task.WhenAll(GetTasks());
  342. }
  343. /// <inheritdoc />
  344. public SendCommand NewSyncPlayCommand(SendCommandType type)
  345. {
  346. return new SendCommand()
  347. {
  348. GroupId = GroupId.ToString(),
  349. PlaylistItemId = PlayQueue.GetPlayingItemPlaylistId(),
  350. PositionTicks = PositionTicks,
  351. Command = type,
  352. When = DateToUTCString(LastActivity),
  353. EmittedAt = DateToUTCString(DateTime.UtcNow)
  354. };
  355. }
  356. /// <inheritdoc />
  357. public GroupUpdate<T> NewSyncPlayGroupUpdate<T>(GroupUpdateType type, T data)
  358. {
  359. return new GroupUpdate<T>()
  360. {
  361. GroupId = GroupId.ToString(),
  362. Type = type,
  363. Data = data
  364. };
  365. }
  366. /// <inheritdoc />
  367. public string DateToUTCString(DateTime dateTime)
  368. {
  369. return dateTime.ToUniversalTime().ToString("o");
  370. }
  371. /// <inheritdoc />
  372. public long SanitizePositionTicks(long? positionTicks)
  373. {
  374. var ticks = positionTicks ?? 0;
  375. ticks = Math.Max(ticks, 0);
  376. ticks = Math.Min(ticks, RunTimeTicks);
  377. return ticks;
  378. }
  379. /// <inheritdoc />
  380. public void UpdatePing(SessionInfo session, long ping)
  381. {
  382. if (Participants.TryGetValue(session.Id, out GroupMember value))
  383. {
  384. value.Ping = ping;
  385. }
  386. }
  387. /// <inheritdoc />
  388. public long GetHighestPing()
  389. {
  390. long max = long.MinValue;
  391. foreach (var session in Participants.Values)
  392. {
  393. max = Math.Max(max, session.Ping);
  394. }
  395. return max;
  396. }
  397. /// <inheritdoc />
  398. public void SetBuffering(SessionInfo session, bool isBuffering)
  399. {
  400. if (Participants.TryGetValue(session.Id, out GroupMember value))
  401. {
  402. value.IsBuffering = isBuffering;
  403. }
  404. }
  405. /// <inheritdoc />
  406. public void SetAllBuffering(bool isBuffering)
  407. {
  408. foreach (var session in Participants.Values)
  409. {
  410. session.IsBuffering = isBuffering;
  411. }
  412. }
  413. /// <inheritdoc />
  414. public bool IsBuffering()
  415. {
  416. foreach (var session in Participants.Values)
  417. {
  418. if (session.IsBuffering && !session.IgnoreGroupWait)
  419. {
  420. return true;
  421. }
  422. }
  423. return false;
  424. }
  425. /// <inheritdoc />
  426. public bool SetPlayQueue(Guid[] playQueue, int playingItemPosition, long startPositionTicks)
  427. {
  428. // Ignore on empty queue or invalid item position.
  429. if (playQueue.Length < 1 || playingItemPosition >= playQueue.Length || playingItemPosition < 0)
  430. {
  431. return false;
  432. }
  433. // Check if participants can access the new playing queue.
  434. if (!AllUsersHaveAccessToQueue(playQueue))
  435. {
  436. return false;
  437. }
  438. PlayQueue.Reset();
  439. PlayQueue.SetPlaylist(playQueue);
  440. PlayQueue.SetPlayingItemByIndex(playingItemPosition);
  441. var item = _libraryManager.GetItemById(PlayQueue.GetPlayingItemId());
  442. RunTimeTicks = item.RunTimeTicks ?? 0;
  443. PositionTicks = startPositionTicks;
  444. LastActivity = DateTime.UtcNow;
  445. return true;
  446. }
  447. /// <inheritdoc />
  448. public bool SetPlayingItem(string playlistItemId)
  449. {
  450. var itemFound = PlayQueue.SetPlayingItemByPlaylistId(playlistItemId);
  451. if (itemFound)
  452. {
  453. var item = _libraryManager.GetItemById(PlayQueue.GetPlayingItemId());
  454. RunTimeTicks = item.RunTimeTicks ?? 0;
  455. }
  456. else
  457. {
  458. RunTimeTicks = 0;
  459. }
  460. RestartCurrentItem();
  461. return itemFound;
  462. }
  463. /// <inheritdoc />
  464. public bool RemoveFromPlayQueue(string[] playlistItemIds)
  465. {
  466. var playingItemRemoved = PlayQueue.RemoveFromPlaylist(playlistItemIds);
  467. if (playingItemRemoved)
  468. {
  469. var itemId = PlayQueue.GetPlayingItemId();
  470. if (!itemId.Equals(Guid.Empty))
  471. {
  472. var item = _libraryManager.GetItemById(itemId);
  473. RunTimeTicks = item.RunTimeTicks ?? 0;
  474. }
  475. else
  476. {
  477. RunTimeTicks = 0;
  478. }
  479. RestartCurrentItem();
  480. }
  481. return playingItemRemoved;
  482. }
  483. /// <inheritdoc />
  484. public bool MoveItemInPlayQueue(string playlistItemId, int newIndex)
  485. {
  486. return PlayQueue.MovePlaylistItem(playlistItemId, newIndex);
  487. }
  488. /// <inheritdoc />
  489. public bool AddToPlayQueue(Guid[] newItems, string mode)
  490. {
  491. // Ignore on empty list.
  492. if (newItems.Length < 1)
  493. {
  494. return false;
  495. }
  496. // Check if participants can access the new playing queue.
  497. if (!AllUsersHaveAccessToQueue(newItems))
  498. {
  499. return false;
  500. }
  501. if (mode.Equals("next"))
  502. {
  503. PlayQueue.QueueNext(newItems);
  504. }
  505. else
  506. {
  507. PlayQueue.Queue(newItems);
  508. }
  509. return true;
  510. }
  511. /// <inheritdoc />
  512. public void RestartCurrentItem()
  513. {
  514. PositionTicks = 0;
  515. LastActivity = DateTime.UtcNow;
  516. }
  517. /// <inheritdoc />
  518. public bool NextItemInQueue()
  519. {
  520. var update = PlayQueue.Next();
  521. if (update)
  522. {
  523. var item = _libraryManager.GetItemById(PlayQueue.GetPlayingItemId());
  524. RunTimeTicks = item.RunTimeTicks ?? 0;
  525. RestartCurrentItem();
  526. return true;
  527. }
  528. else
  529. {
  530. return false;
  531. }
  532. }
  533. /// <inheritdoc />
  534. public bool PreviousItemInQueue()
  535. {
  536. var update = PlayQueue.Previous();
  537. if (update)
  538. {
  539. var item = _libraryManager.GetItemById(PlayQueue.GetPlayingItemId());
  540. RunTimeTicks = item.RunTimeTicks ?? 0;
  541. RestartCurrentItem();
  542. return true;
  543. }
  544. else
  545. {
  546. return false;
  547. }
  548. }
  549. /// <inheritdoc />
  550. public void SetRepeatMode(string mode) {
  551. switch (mode)
  552. {
  553. case "RepeatOne":
  554. PlayQueue.SetRepeatMode(GroupRepeatMode.RepeatOne);
  555. break;
  556. case "RepeatAll":
  557. PlayQueue.SetRepeatMode(GroupRepeatMode.RepeatAll);
  558. break;
  559. default:
  560. // On unknown values, default to repeat none.
  561. PlayQueue.SetRepeatMode(GroupRepeatMode.RepeatNone);
  562. break;
  563. }
  564. }
  565. /// <inheritdoc />
  566. public void SetShuffleMode(string mode) {
  567. switch (mode)
  568. {
  569. case "Shuffle":
  570. PlayQueue.SetShuffleMode(GroupShuffleMode.Shuffle);
  571. break;
  572. default:
  573. // On unknown values, default to sorted playlist.
  574. PlayQueue.SetShuffleMode(GroupShuffleMode.Sorted);
  575. break;
  576. }
  577. }
  578. /// <inheritdoc />
  579. public PlayQueueUpdate GetPlayQueueUpdate(PlayQueueUpdateReason reason)
  580. {
  581. var startPositionTicks = PositionTicks;
  582. if (State.GetGroupState().Equals(GroupState.Playing))
  583. {
  584. var currentTime = DateTime.UtcNow;
  585. var elapsedTime = currentTime - LastActivity;
  586. // Elapsed time is negative if event happens
  587. // during the delay added to account for latency.
  588. // In this phase clients haven't started the playback yet.
  589. // In other words, LastActivity is in the future,
  590. // when playback unpause is supposed to happen.
  591. // Adjust ticks only if playback actually started.
  592. startPositionTicks += Math.Max(elapsedTime.Ticks, 0);
  593. }
  594. return new PlayQueueUpdate()
  595. {
  596. Reason = reason,
  597. LastUpdate = DateToUTCString(PlayQueue.LastChange),
  598. Playlist = PlayQueue.GetPlaylist(),
  599. PlayingItemIndex = PlayQueue.PlayingItemIndex,
  600. StartPositionTicks = startPositionTicks,
  601. ShuffleMode = PlayQueue.ShuffleMode,
  602. RepeatMode = PlayQueue.RepeatMode
  603. };
  604. }
  605. }
  606. }