GroupController.cs 25 KB

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