SessionManager.cs 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238
  1. using System.IO;
  2. using MediaBrowser.Common.Events;
  3. using MediaBrowser.Common.Extensions;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Drawing;
  6. using MediaBrowser.Controller.Dto;
  7. using MediaBrowser.Controller.Entities;
  8. using MediaBrowser.Controller.Entities.Audio;
  9. using MediaBrowser.Controller.Entities.TV;
  10. using MediaBrowser.Controller.Library;
  11. using MediaBrowser.Controller.Persistence;
  12. using MediaBrowser.Controller.Session;
  13. using MediaBrowser.Model.Entities;
  14. using MediaBrowser.Model.Library;
  15. using MediaBrowser.Model.Logging;
  16. using MediaBrowser.Model.Session;
  17. using System;
  18. using System.Collections.Concurrent;
  19. using System.Collections.Generic;
  20. using System.Linq;
  21. using System.Threading;
  22. using System.Threading.Tasks;
  23. namespace MediaBrowser.Server.Implementations.Session
  24. {
  25. /// <summary>
  26. /// Class SessionManager
  27. /// </summary>
  28. public class SessionManager : ISessionManager
  29. {
  30. /// <summary>
  31. /// The _user data repository
  32. /// </summary>
  33. private readonly IUserDataManager _userDataRepository;
  34. /// <summary>
  35. /// The _user repository
  36. /// </summary>
  37. private readonly IUserRepository _userRepository;
  38. /// <summary>
  39. /// The _logger
  40. /// </summary>
  41. private readonly ILogger _logger;
  42. private readonly ILibraryManager _libraryManager;
  43. private readonly IUserManager _userManager;
  44. private readonly IMusicManager _musicManager;
  45. private readonly IDtoService _dtoService;
  46. private readonly IImageProcessor _imageProcessor;
  47. /// <summary>
  48. /// Gets or sets the configuration manager.
  49. /// </summary>
  50. /// <value>The configuration manager.</value>
  51. private readonly IServerConfigurationManager _configurationManager;
  52. /// <summary>
  53. /// The _active connections
  54. /// </summary>
  55. private readonly ConcurrentDictionary<string, SessionInfo> _activeConnections =
  56. new ConcurrentDictionary<string, SessionInfo>(StringComparer.OrdinalIgnoreCase);
  57. /// <summary>
  58. /// Occurs when [playback start].
  59. /// </summary>
  60. public event EventHandler<PlaybackProgressEventArgs> PlaybackStart;
  61. /// <summary>
  62. /// Occurs when [playback progress].
  63. /// </summary>
  64. public event EventHandler<PlaybackProgressEventArgs> PlaybackProgress;
  65. /// <summary>
  66. /// Occurs when [playback stopped].
  67. /// </summary>
  68. public event EventHandler<PlaybackStopEventArgs> PlaybackStopped;
  69. public event EventHandler<SessionEventArgs> SessionStarted;
  70. public event EventHandler<SessionEventArgs> SessionEnded;
  71. private IEnumerable<ISessionControllerFactory> _sessionFactories = new List<ISessionControllerFactory>();
  72. private readonly SemaphoreSlim _sessionLock = new SemaphoreSlim(1, 1);
  73. /// <summary>
  74. /// Initializes a new instance of the <see cref="SessionManager" /> class.
  75. /// </summary>
  76. /// <param name="userDataRepository">The user data repository.</param>
  77. /// <param name="configurationManager">The configuration manager.</param>
  78. /// <param name="logger">The logger.</param>
  79. /// <param name="userRepository">The user repository.</param>
  80. /// <param name="libraryManager">The library manager.</param>
  81. public SessionManager(IUserDataManager userDataRepository, IServerConfigurationManager configurationManager, ILogger logger, IUserRepository userRepository, ILibraryManager libraryManager, IUserManager userManager, IMusicManager musicManager, IDtoService dtoService, IImageProcessor imageProcessor)
  82. {
  83. _userDataRepository = userDataRepository;
  84. _configurationManager = configurationManager;
  85. _logger = logger;
  86. _userRepository = userRepository;
  87. _libraryManager = libraryManager;
  88. _userManager = userManager;
  89. _musicManager = musicManager;
  90. _dtoService = dtoService;
  91. _imageProcessor = imageProcessor;
  92. }
  93. /// <summary>
  94. /// Adds the parts.
  95. /// </summary>
  96. /// <param name="sessionFactories">The session factories.</param>
  97. public void AddParts(IEnumerable<ISessionControllerFactory> sessionFactories)
  98. {
  99. _sessionFactories = sessionFactories.ToList();
  100. }
  101. /// <summary>
  102. /// Gets all connections.
  103. /// </summary>
  104. /// <value>All connections.</value>
  105. public IEnumerable<SessionInfo> Sessions
  106. {
  107. get { return _activeConnections.Values.OrderByDescending(c => c.LastActivityDate).ToList(); }
  108. }
  109. private void OnSessionStarted(SessionInfo info)
  110. {
  111. EventHelper.QueueEventIfNotNull(SessionStarted, this, new SessionEventArgs
  112. {
  113. SessionInfo = info
  114. }, _logger);
  115. }
  116. private async void OnSessionEnded(SessionInfo info)
  117. {
  118. try
  119. {
  120. await SendSessionEndedNotification(info, CancellationToken.None).ConfigureAwait(false);
  121. }
  122. catch (Exception ex)
  123. {
  124. _logger.ErrorException("Error in SendSessionEndedNotification", ex);
  125. }
  126. EventHelper.QueueEventIfNotNull(SessionEnded, this, new SessionEventArgs
  127. {
  128. SessionInfo = info
  129. }, _logger);
  130. var disposable = info.SessionController as IDisposable;
  131. if (disposable != null)
  132. {
  133. try
  134. {
  135. disposable.Dispose();
  136. }
  137. catch (Exception ex)
  138. {
  139. _logger.ErrorException("Error disposing session controller", ex);
  140. }
  141. }
  142. }
  143. /// <summary>
  144. /// Logs the user activity.
  145. /// </summary>
  146. /// <param name="clientType">Type of the client.</param>
  147. /// <param name="appVersion">The app version.</param>
  148. /// <param name="deviceId">The device id.</param>
  149. /// <param name="deviceName">Name of the device.</param>
  150. /// <param name="remoteEndPoint">The remote end point.</param>
  151. /// <param name="user">The user.</param>
  152. /// <returns>Task.</returns>
  153. /// <exception cref="System.ArgumentNullException">user</exception>
  154. /// <exception cref="System.UnauthorizedAccessException"></exception>
  155. public async Task<SessionInfo> LogSessionActivity(string clientType, string appVersion, string deviceId, string deviceName, string remoteEndPoint, User user)
  156. {
  157. if (string.IsNullOrEmpty(clientType))
  158. {
  159. throw new ArgumentNullException("clientType");
  160. }
  161. if (string.IsNullOrEmpty(appVersion))
  162. {
  163. throw new ArgumentNullException("appVersion");
  164. }
  165. if (string.IsNullOrEmpty(deviceId))
  166. {
  167. throw new ArgumentNullException("deviceId");
  168. }
  169. if (string.IsNullOrEmpty(deviceName))
  170. {
  171. throw new ArgumentNullException("deviceName");
  172. }
  173. if (user != null && user.Configuration.IsDisabled)
  174. {
  175. throw new UnauthorizedAccessException(string.Format("The {0} account is currently disabled. Please consult with your administrator.", user.Name));
  176. }
  177. var activityDate = DateTime.UtcNow;
  178. var userId = user == null ? (Guid?)null : user.Id;
  179. var username = user == null ? null : user.Name;
  180. var session = await GetSessionInfo(clientType, appVersion, deviceId, deviceName, remoteEndPoint, userId, username).ConfigureAwait(false);
  181. session.LastActivityDate = activityDate;
  182. if (user == null)
  183. {
  184. return session;
  185. }
  186. var lastActivityDate = user.LastActivityDate;
  187. user.LastActivityDate = activityDate;
  188. // Don't log in the db anymore frequently than 10 seconds
  189. if (lastActivityDate.HasValue && (activityDate - lastActivityDate.Value).TotalSeconds < 10)
  190. {
  191. return session;
  192. }
  193. // Save this directly. No need to fire off all the events for this.
  194. await _userRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  195. return session;
  196. }
  197. public async Task ReportSessionEnded(Guid sessionId)
  198. {
  199. await _sessionLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  200. try
  201. {
  202. var session = GetSession(sessionId);
  203. if (session == null)
  204. {
  205. throw new ArgumentException("Session not found");
  206. }
  207. var key = GetSessionKey(session.Client, session.ApplicationVersion, session.DeviceId);
  208. SessionInfo removed;
  209. if (_activeConnections.TryRemove(key, out removed))
  210. {
  211. OnSessionEnded(removed);
  212. }
  213. }
  214. finally
  215. {
  216. _sessionLock.Release();
  217. }
  218. }
  219. /// <summary>
  220. /// Updates the now playing item id.
  221. /// </summary>
  222. /// <param name="session">The session.</param>
  223. /// <param name="item">The item.</param>
  224. /// <param name="mediaSourceId">The media version identifier.</param>
  225. /// <param name="isPaused">if set to <c>true</c> [is paused].</param>
  226. /// <param name="currentPositionTicks">The current position ticks.</param>
  227. private void UpdateNowPlayingItem(SessionInfo session, BaseItem item, string mediaSourceId, bool isPaused, long? currentPositionTicks = null)
  228. {
  229. session.IsPaused = isPaused;
  230. session.NowPlayingPositionTicks = currentPositionTicks;
  231. session.NowPlayingItem = item;
  232. session.LastActivityDate = DateTime.UtcNow;
  233. session.NowPlayingMediaSourceId = mediaSourceId;
  234. if (string.IsNullOrWhiteSpace(mediaSourceId))
  235. {
  236. session.NowPlayingRunTimeTicks = item.RunTimeTicks;
  237. }
  238. else
  239. {
  240. var version = _libraryManager.GetItemById(new Guid(mediaSourceId));
  241. session.NowPlayingRunTimeTicks = version.RunTimeTicks;
  242. }
  243. }
  244. /// <summary>
  245. /// Removes the now playing item id.
  246. /// </summary>
  247. /// <param name="session">The session.</param>
  248. /// <param name="item">The item.</param>
  249. private void RemoveNowPlayingItem(SessionInfo session, BaseItem item)
  250. {
  251. if (item == null)
  252. {
  253. throw new ArgumentNullException("item");
  254. }
  255. if (session.NowPlayingItem != null && session.NowPlayingItem.Id == item.Id)
  256. {
  257. session.NowPlayingItem = null;
  258. session.NowPlayingPositionTicks = null;
  259. session.IsPaused = false;
  260. session.NowPlayingRunTimeTicks = null;
  261. session.NowPlayingMediaSourceId = null;
  262. }
  263. }
  264. private string GetSessionKey(string clientType, string appVersion, string deviceId)
  265. {
  266. return clientType + deviceId + appVersion;
  267. }
  268. /// <summary>
  269. /// Gets the connection.
  270. /// </summary>
  271. /// <param name="clientType">Type of the client.</param>
  272. /// <param name="appVersion">The app version.</param>
  273. /// <param name="deviceId">The device id.</param>
  274. /// <param name="deviceName">Name of the device.</param>
  275. /// <param name="remoteEndPoint">The remote end point.</param>
  276. /// <param name="userId">The user identifier.</param>
  277. /// <param name="username">The username.</param>
  278. /// <returns>SessionInfo.</returns>
  279. private async Task<SessionInfo> GetSessionInfo(string clientType, string appVersion, string deviceId, string deviceName, string remoteEndPoint, Guid? userId, string username)
  280. {
  281. var key = GetSessionKey(clientType, appVersion, deviceId);
  282. await _sessionLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  283. try
  284. {
  285. var connection = _activeConnections.GetOrAdd(key, keyName =>
  286. {
  287. var sessionInfo = new SessionInfo
  288. {
  289. Client = clientType,
  290. DeviceId = deviceId,
  291. ApplicationVersion = appVersion,
  292. Id = Guid.NewGuid()
  293. };
  294. OnSessionStarted(sessionInfo);
  295. return sessionInfo;
  296. });
  297. connection.DeviceName = deviceName;
  298. connection.UserId = userId;
  299. connection.UserName = username;
  300. connection.RemoteEndPoint = remoteEndPoint;
  301. if (!userId.HasValue)
  302. {
  303. connection.AdditionalUsers.Clear();
  304. }
  305. if (connection.SessionController == null)
  306. {
  307. connection.SessionController = _sessionFactories
  308. .Select(i => i.GetSessionController(connection))
  309. .FirstOrDefault(i => i != null);
  310. }
  311. return connection;
  312. }
  313. finally
  314. {
  315. _sessionLock.Release();
  316. }
  317. }
  318. private List<User> GetUsers(SessionInfo session)
  319. {
  320. var users = new List<User>();
  321. if (session.UserId.HasValue)
  322. {
  323. var user = _userManager.GetUserById(session.UserId.Value);
  324. if (user == null)
  325. {
  326. throw new InvalidOperationException("User not found");
  327. }
  328. users.Add(user);
  329. var additionalUsers = session.AdditionalUsers
  330. .Select(i => _userManager.GetUserById(new Guid(i.UserId)))
  331. .Where(i => i != null);
  332. users.AddRange(additionalUsers);
  333. }
  334. return users;
  335. }
  336. /// <summary>
  337. /// Used to report that playback has started for an item
  338. /// </summary>
  339. /// <param name="info">The info.</param>
  340. /// <returns>Task.</returns>
  341. /// <exception cref="System.ArgumentNullException">info</exception>
  342. public async Task OnPlaybackStart(PlaybackInfo info)
  343. {
  344. if (info == null)
  345. {
  346. throw new ArgumentNullException("info");
  347. }
  348. if (info.SessionId == Guid.Empty)
  349. {
  350. throw new ArgumentNullException("info");
  351. }
  352. var session = Sessions.First(i => i.Id.Equals(info.SessionId));
  353. var item = info.Item;
  354. var mediaSourceId = GetMediaSourceId(item, info.MediaSourceId);
  355. UpdateNowPlayingItem(session, item, mediaSourceId, false);
  356. session.CanSeek = info.CanSeek;
  357. session.QueueableMediaTypes = info.QueueableMediaTypes;
  358. session.NowPlayingAudioStreamIndex = info.AudioStreamIndex;
  359. session.NowPlayingSubtitleStreamIndex = info.SubtitleStreamIndex;
  360. var key = item.GetUserDataKey();
  361. var users = GetUsers(session);
  362. foreach (var user in users)
  363. {
  364. await OnPlaybackStart(user.Id, key, item).ConfigureAwait(false);
  365. }
  366. // Nothing to save here
  367. // Fire events to inform plugins
  368. EventHelper.QueueEventIfNotNull(PlaybackStart, this, new PlaybackProgressEventArgs
  369. {
  370. Item = item,
  371. Users = users,
  372. MediaSourceId = info.MediaSourceId
  373. }, _logger);
  374. }
  375. /// <summary>
  376. /// Called when [playback start].
  377. /// </summary>
  378. /// <param name="userId">The user identifier.</param>
  379. /// <param name="userDataKey">The user data key.</param>
  380. /// <param name="item">The item.</param>
  381. /// <returns>Task.</returns>
  382. private async Task OnPlaybackStart(Guid userId, string userDataKey, IHasUserData item)
  383. {
  384. var data = _userDataRepository.GetUserData(userId, userDataKey);
  385. data.PlayCount++;
  386. data.LastPlayedDate = DateTime.UtcNow;
  387. if (!(item is Video))
  388. {
  389. data.Played = true;
  390. }
  391. await _userDataRepository.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackStart, CancellationToken.None).ConfigureAwait(false);
  392. }
  393. /// <summary>
  394. /// Used to report playback progress for an item
  395. /// </summary>
  396. /// <param name="info">The info.</param>
  397. /// <returns>Task.</returns>
  398. /// <exception cref="System.ArgumentNullException"></exception>
  399. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  400. public async Task OnPlaybackProgress(Controller.Session.PlaybackProgressInfo info)
  401. {
  402. if (info == null)
  403. {
  404. throw new ArgumentNullException("info");
  405. }
  406. if (info.PositionTicks.HasValue && info.PositionTicks.Value < 0)
  407. {
  408. throw new ArgumentOutOfRangeException("positionTicks");
  409. }
  410. var session = Sessions.First(i => i.Id.Equals(info.SessionId));
  411. var mediaSourceId = GetMediaSourceId(info.Item, info.MediaSourceId);
  412. UpdateNowPlayingItem(session, info.Item, mediaSourceId, info.IsPaused, info.PositionTicks);
  413. session.IsMuted = info.IsMuted;
  414. session.VolumeLevel = info.VolumeLevel;
  415. session.NowPlayingAudioStreamIndex = info.AudioStreamIndex;
  416. session.NowPlayingSubtitleStreamIndex = info.SubtitleStreamIndex;
  417. var key = info.Item.GetUserDataKey();
  418. var users = GetUsers(session);
  419. foreach (var user in users)
  420. {
  421. await OnPlaybackProgress(user.Id, key, info.Item, info.PositionTicks).ConfigureAwait(false);
  422. }
  423. EventHelper.QueueEventIfNotNull(PlaybackProgress, this, new PlaybackProgressEventArgs
  424. {
  425. Item = info.Item,
  426. Users = users,
  427. PlaybackPositionTicks = info.PositionTicks,
  428. MediaSourceId = mediaSourceId
  429. }, _logger);
  430. }
  431. private async Task OnPlaybackProgress(Guid userId, string userDataKey, BaseItem item, long? positionTicks)
  432. {
  433. var data = _userDataRepository.GetUserData(userId, userDataKey);
  434. if (positionTicks.HasValue)
  435. {
  436. UpdatePlayState(item, data, positionTicks.Value);
  437. await _userDataRepository.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackProgress, CancellationToken.None).ConfigureAwait(false);
  438. }
  439. }
  440. /// <summary>
  441. /// Used to report that playback has ended for an item
  442. /// </summary>
  443. /// <param name="info">The info.</param>
  444. /// <returns>Task.</returns>
  445. /// <exception cref="System.ArgumentNullException">info</exception>
  446. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  447. public async Task OnPlaybackStopped(Controller.Session.PlaybackStopInfo info)
  448. {
  449. if (info == null)
  450. {
  451. throw new ArgumentNullException("info");
  452. }
  453. if (info.Item == null)
  454. {
  455. throw new ArgumentException("PlaybackStopInfo.Item cannot be null");
  456. }
  457. if (info.SessionId == Guid.Empty)
  458. {
  459. throw new ArgumentException("PlaybackStopInfo.SessionId cannot be Guid.Empty");
  460. }
  461. if (info.PositionTicks.HasValue && info.PositionTicks.Value < 0)
  462. {
  463. throw new ArgumentOutOfRangeException("positionTicks");
  464. }
  465. var session = Sessions.First(i => i.Id.Equals(info.SessionId));
  466. RemoveNowPlayingItem(session, info.Item);
  467. var key = info.Item.GetUserDataKey();
  468. var users = GetUsers(session);
  469. var playedToCompletion = false;
  470. foreach (var user in users)
  471. {
  472. playedToCompletion = await OnPlaybackStopped(user.Id, key, info.Item, info.PositionTicks).ConfigureAwait(false);
  473. }
  474. var mediaSourceId = GetMediaSourceId(info.Item, info.MediaSourceId);
  475. EventHelper.QueueEventIfNotNull(PlaybackStopped, this, new PlaybackStopEventArgs
  476. {
  477. Item = info.Item,
  478. Users = users,
  479. PlaybackPositionTicks = info.PositionTicks,
  480. PlayedToCompletion = playedToCompletion,
  481. MediaSourceId = mediaSourceId
  482. }, _logger);
  483. }
  484. private string GetMediaSourceId(BaseItem item, string reportedMediaSourceId)
  485. {
  486. if (string.IsNullOrWhiteSpace(reportedMediaSourceId))
  487. {
  488. if (item is Video || item is Audio)
  489. {
  490. reportedMediaSourceId = item.Id.ToString("N");
  491. }
  492. }
  493. return reportedMediaSourceId;
  494. }
  495. private async Task<bool> OnPlaybackStopped(Guid userId, string userDataKey, BaseItem item, long? positionTicks)
  496. {
  497. var data = _userDataRepository.GetUserData(userId, userDataKey);
  498. bool playedToCompletion;
  499. if (positionTicks.HasValue)
  500. {
  501. playedToCompletion = UpdatePlayState(item, data, positionTicks.Value);
  502. }
  503. else
  504. {
  505. // If the client isn't able to report this, then we'll just have to make an assumption
  506. data.PlayCount++;
  507. data.Played = true;
  508. data.PlaybackPositionTicks = 0;
  509. playedToCompletion = true;
  510. }
  511. await _userDataRepository.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackFinished, CancellationToken.None).ConfigureAwait(false);
  512. return playedToCompletion;
  513. }
  514. /// <summary>
  515. /// Updates playstate position for an item but does not save
  516. /// </summary>
  517. /// <param name="item">The item</param>
  518. /// <param name="data">User data for the item</param>
  519. /// <param name="positionTicks">The current playback position</param>
  520. private bool UpdatePlayState(BaseItem item, UserItemData data, long positionTicks)
  521. {
  522. var playedToCompletion = false;
  523. var hasRuntime = item.RunTimeTicks.HasValue && item.RunTimeTicks > 0;
  524. // If a position has been reported, and if we know the duration
  525. if (positionTicks > 0 && hasRuntime)
  526. {
  527. var pctIn = Decimal.Divide(positionTicks, item.RunTimeTicks.Value) * 100;
  528. // Don't track in very beginning
  529. if (pctIn < _configurationManager.Configuration.MinResumePct)
  530. {
  531. positionTicks = 0;
  532. }
  533. // If we're at the end, assume completed
  534. else if (pctIn > _configurationManager.Configuration.MaxResumePct || positionTicks >= item.RunTimeTicks.Value)
  535. {
  536. positionTicks = 0;
  537. data.Played = playedToCompletion = true;
  538. }
  539. else
  540. {
  541. // Enforce MinResumeDuration
  542. var durationSeconds = TimeSpan.FromTicks(item.RunTimeTicks.Value).TotalSeconds;
  543. if (durationSeconds < _configurationManager.Configuration.MinResumeDurationSeconds)
  544. {
  545. positionTicks = 0;
  546. data.Played = playedToCompletion = true;
  547. }
  548. }
  549. }
  550. else if (!hasRuntime)
  551. {
  552. // If we don't know the runtime we'll just have to assume it was fully played
  553. data.Played = playedToCompletion = true;
  554. positionTicks = 0;
  555. }
  556. if (item is Audio)
  557. {
  558. positionTicks = 0;
  559. }
  560. data.PlaybackPositionTicks = positionTicks;
  561. return playedToCompletion;
  562. }
  563. /// <summary>
  564. /// Gets the session.
  565. /// </summary>
  566. /// <param name="sessionId">The session identifier.</param>
  567. /// <returns>SessionInfo.</returns>
  568. /// <exception cref="ResourceNotFoundException"></exception>
  569. private SessionInfo GetSession(Guid sessionId)
  570. {
  571. var session = Sessions.First(i => i.Id.Equals(sessionId));
  572. if (session == null)
  573. {
  574. throw new ResourceNotFoundException(string.Format("Session {0} not found.", sessionId));
  575. }
  576. return session;
  577. }
  578. /// <summary>
  579. /// Gets the session for remote control.
  580. /// </summary>
  581. /// <param name="sessionId">The session id.</param>
  582. /// <returns>SessionInfo.</returns>
  583. /// <exception cref="ResourceNotFoundException"></exception>
  584. private SessionInfo GetSessionForRemoteControl(Guid sessionId)
  585. {
  586. var session = GetSession(sessionId);
  587. if (!session.SupportsRemoteControl)
  588. {
  589. throw new ArgumentException(string.Format("Session {0} does not support remote control.", session.Id));
  590. }
  591. return session;
  592. }
  593. public Task SendMessageCommand(Guid controllingSessionId, Guid sessionId, MessageCommand command, CancellationToken cancellationToken)
  594. {
  595. var session = GetSessionForRemoteControl(sessionId);
  596. var controllingSession = GetSession(controllingSessionId);
  597. AssertCanControl(session, controllingSession);
  598. return session.SessionController.SendMessageCommand(command, cancellationToken);
  599. }
  600. public Task SendGeneralCommand(Guid controllingSessionId, Guid sessionId, GeneralCommand command, CancellationToken cancellationToken)
  601. {
  602. var session = GetSessionForRemoteControl(sessionId);
  603. var controllingSession = GetSession(controllingSessionId);
  604. AssertCanControl(session, controllingSession);
  605. return session.SessionController.SendGeneralCommand(command, cancellationToken);
  606. }
  607. public Task SendPlayCommand(Guid controllingSessionId, Guid sessionId, PlayRequest command, CancellationToken cancellationToken)
  608. {
  609. var session = GetSessionForRemoteControl(sessionId);
  610. var user = session.UserId.HasValue ? _userManager.GetUserById(session.UserId.Value) : null;
  611. List<BaseItem> items;
  612. if (command.PlayCommand == PlayCommand.PlayInstantMix)
  613. {
  614. items = command.ItemIds.SelectMany(i => TranslateItemForInstantMix(i, user))
  615. .Where(i => i.LocationType != LocationType.Virtual)
  616. .ToList();
  617. command.PlayCommand = PlayCommand.PlayNow;
  618. }
  619. else
  620. {
  621. items = command.ItemIds.SelectMany(i => TranslateItemForPlayback(i, user))
  622. .Where(i => i.LocationType != LocationType.Virtual)
  623. .ToList();
  624. }
  625. if (command.PlayCommand == PlayCommand.PlayShuffle)
  626. {
  627. items = items.OrderBy(i => Guid.NewGuid()).ToList();
  628. command.PlayCommand = PlayCommand.PlayNow;
  629. }
  630. command.ItemIds = items.Select(i => i.Id.ToString("N")).ToArray();
  631. if (user != null)
  632. {
  633. if (items.Any(i => i.GetPlayAccess(user) != PlayAccess.Full))
  634. {
  635. throw new ArgumentException(string.Format("{0} is not allowed to play media.", user.Name));
  636. }
  637. }
  638. if (command.PlayCommand != PlayCommand.PlayNow)
  639. {
  640. if (items.Any(i => !session.QueueableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  641. {
  642. throw new ArgumentException(string.Format("{0} is unable to queue the requested media type.", session.DeviceName ?? session.Id.ToString()));
  643. }
  644. }
  645. else
  646. {
  647. if (items.Any(i => !session.PlayableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  648. {
  649. throw new ArgumentException(string.Format("{0} is unable to play the requested media type.", session.DeviceName ?? session.Id.ToString()));
  650. }
  651. }
  652. var controllingSession = GetSession(controllingSessionId);
  653. AssertCanControl(session, controllingSession);
  654. if (controllingSession.UserId.HasValue)
  655. {
  656. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  657. }
  658. return session.SessionController.SendPlayCommand(command, cancellationToken);
  659. }
  660. private IEnumerable<BaseItem> TranslateItemForPlayback(string id, User user)
  661. {
  662. var item = _libraryManager.GetItemById(new Guid(id));
  663. if (item.IsFolder)
  664. {
  665. var folder = (Folder)item;
  666. var items = user == null ? folder.RecursiveChildren :
  667. folder.GetRecursiveChildren(user);
  668. items = items.Where(i => !i.IsFolder);
  669. items = items.OrderBy(i => i.SortName);
  670. return items;
  671. }
  672. return new[] { item };
  673. }
  674. private IEnumerable<BaseItem> TranslateItemForInstantMix(string id, User user)
  675. {
  676. var item = _libraryManager.GetItemById(new Guid(id));
  677. var audio = item as Audio;
  678. if (audio != null)
  679. {
  680. return _musicManager.GetInstantMixFromSong(audio, user);
  681. }
  682. var artist = item as MusicArtist;
  683. if (artist != null)
  684. {
  685. return _musicManager.GetInstantMixFromArtist(artist.Name, user);
  686. }
  687. var album = item as MusicAlbum;
  688. if (album != null)
  689. {
  690. return _musicManager.GetInstantMixFromAlbum(album, user);
  691. }
  692. var genre = item as MusicGenre;
  693. if (genre != null)
  694. {
  695. return _musicManager.GetInstantMixFromGenres(new[] { genre.Name }, user);
  696. }
  697. return new BaseItem[] { };
  698. }
  699. public Task SendBrowseCommand(Guid controllingSessionId, Guid sessionId, BrowseRequest command, CancellationToken cancellationToken)
  700. {
  701. var session = GetSessionForRemoteControl(sessionId);
  702. var controllingSession = GetSession(controllingSessionId);
  703. AssertCanControl(session, controllingSession);
  704. return session.SessionController.SendBrowseCommand(command, cancellationToken);
  705. }
  706. public Task SendPlaystateCommand(Guid controllingSessionId, Guid sessionId, PlaystateRequest command, CancellationToken cancellationToken)
  707. {
  708. var session = GetSessionForRemoteControl(sessionId);
  709. if (command.Command == PlaystateCommand.Seek && !session.CanSeek)
  710. {
  711. throw new ArgumentException(string.Format("Session {0} is unable to seek.", session.Id));
  712. }
  713. var controllingSession = GetSession(controllingSessionId);
  714. AssertCanControl(session, controllingSession);
  715. if (controllingSession.UserId.HasValue)
  716. {
  717. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  718. }
  719. return session.SessionController.SendPlaystateCommand(command, cancellationToken);
  720. }
  721. private void AssertCanControl(SessionInfo session, SessionInfo controllingSession)
  722. {
  723. if (session == null)
  724. {
  725. throw new ArgumentNullException("session");
  726. }
  727. if (controllingSession == null)
  728. {
  729. throw new ArgumentNullException("controllingSession");
  730. }
  731. }
  732. /// <summary>
  733. /// Sends the restart required message.
  734. /// </summary>
  735. /// <param name="cancellationToken">The cancellation token.</param>
  736. /// <returns>Task.</returns>
  737. public Task SendRestartRequiredNotification(CancellationToken cancellationToken)
  738. {
  739. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  740. var tasks = sessions.Select(session => Task.Run(async () =>
  741. {
  742. try
  743. {
  744. await session.SessionController.SendRestartRequiredNotification(cancellationToken).ConfigureAwait(false);
  745. }
  746. catch (Exception ex)
  747. {
  748. _logger.ErrorException("Error in SendRestartRequiredNotification.", ex);
  749. }
  750. }, cancellationToken));
  751. return Task.WhenAll(tasks);
  752. }
  753. /// <summary>
  754. /// Sends the server shutdown notification.
  755. /// </summary>
  756. /// <param name="cancellationToken">The cancellation token.</param>
  757. /// <returns>Task.</returns>
  758. public Task SendServerShutdownNotification(CancellationToken cancellationToken)
  759. {
  760. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  761. var tasks = sessions.Select(session => Task.Run(async () =>
  762. {
  763. try
  764. {
  765. await session.SessionController.SendServerShutdownNotification(cancellationToken).ConfigureAwait(false);
  766. }
  767. catch (Exception ex)
  768. {
  769. _logger.ErrorException("Error in SendServerShutdownNotification.", ex);
  770. }
  771. }, cancellationToken));
  772. return Task.WhenAll(tasks);
  773. }
  774. /// <summary>
  775. /// Sends the server restart notification.
  776. /// </summary>
  777. /// <param name="cancellationToken">The cancellation token.</param>
  778. /// <returns>Task.</returns>
  779. public Task SendServerRestartNotification(CancellationToken cancellationToken)
  780. {
  781. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  782. var tasks = sessions.Select(session => Task.Run(async () =>
  783. {
  784. try
  785. {
  786. await session.SessionController.SendServerRestartNotification(cancellationToken).ConfigureAwait(false);
  787. }
  788. catch (Exception ex)
  789. {
  790. _logger.ErrorException("Error in SendServerRestartNotification.", ex);
  791. }
  792. }, cancellationToken));
  793. return Task.WhenAll(tasks);
  794. }
  795. public Task SendSessionEndedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  796. {
  797. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  798. var dto = GetSessionInfoDto(sessionInfo);
  799. var tasks = sessions.Select(session => Task.Run(async () =>
  800. {
  801. try
  802. {
  803. await session.SessionController.SendSessionEndedNotification(dto, cancellationToken).ConfigureAwait(false);
  804. }
  805. catch (Exception ex)
  806. {
  807. _logger.ErrorException("Error in SendSessionEndedNotification.", ex);
  808. }
  809. }, cancellationToken));
  810. return Task.WhenAll(tasks);
  811. }
  812. /// <summary>
  813. /// Adds the additional user.
  814. /// </summary>
  815. /// <param name="sessionId">The session identifier.</param>
  816. /// <param name="userId">The user identifier.</param>
  817. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  818. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  819. public void AddAdditionalUser(Guid sessionId, Guid userId)
  820. {
  821. var session = GetSession(sessionId);
  822. if (!session.UserId.HasValue)
  823. {
  824. throw new UnauthorizedAccessException("Cannot modify additional users without authenticating first.");
  825. }
  826. if (session.UserId.Value == userId)
  827. {
  828. throw new ArgumentException("The requested user is already the primary user of the session.");
  829. }
  830. if (session.AdditionalUsers.All(i => new Guid(i.UserId) != userId))
  831. {
  832. var user = _userManager.GetUserById(userId);
  833. session.AdditionalUsers.Add(new SessionUserInfo
  834. {
  835. UserId = userId.ToString("N"),
  836. UserName = user.Name
  837. });
  838. }
  839. }
  840. /// <summary>
  841. /// Removes the additional user.
  842. /// </summary>
  843. /// <param name="sessionId">The session identifier.</param>
  844. /// <param name="userId">The user identifier.</param>
  845. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  846. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  847. public void RemoveAdditionalUser(Guid sessionId, Guid userId)
  848. {
  849. var session = GetSession(sessionId);
  850. if (!session.UserId.HasValue)
  851. {
  852. throw new UnauthorizedAccessException("Cannot modify additional users without authenticating first.");
  853. }
  854. if (session.UserId.Value == userId)
  855. {
  856. throw new ArgumentException("The requested user is already the primary user of the session.");
  857. }
  858. var user = session.AdditionalUsers.FirstOrDefault(i => new Guid(i.UserId) == userId);
  859. if (user != null)
  860. {
  861. session.AdditionalUsers.Remove(user);
  862. }
  863. }
  864. /// <summary>
  865. /// Authenticates the new session.
  866. /// </summary>
  867. /// <param name="user">The user.</param>
  868. /// <param name="password">The password.</param>
  869. /// <param name="clientType">Type of the client.</param>
  870. /// <param name="appVersion">The application version.</param>
  871. /// <param name="deviceId">The device identifier.</param>
  872. /// <param name="deviceName">Name of the device.</param>
  873. /// <param name="remoteEndPoint">The remote end point.</param>
  874. /// <returns>Task{SessionInfo}.</returns>
  875. /// <exception cref="UnauthorizedAccessException"></exception>
  876. public async Task<SessionInfo> AuthenticateNewSession(User user, string password, string clientType, string appVersion, string deviceId, string deviceName, string remoteEndPoint)
  877. {
  878. var result = await _userManager.AuthenticateUser(user, password).ConfigureAwait(false);
  879. if (!result)
  880. {
  881. throw new UnauthorizedAccessException("Invalid user or password entered.");
  882. }
  883. return await LogSessionActivity(clientType, appVersion, deviceId, deviceName, remoteEndPoint, user).ConfigureAwait(false);
  884. }
  885. /// <summary>
  886. /// Reports the capabilities.
  887. /// </summary>
  888. /// <param name="sessionId">The session identifier.</param>
  889. /// <param name="capabilities">The capabilities.</param>
  890. public void ReportCapabilities(Guid sessionId, SessionCapabilities capabilities)
  891. {
  892. var session = GetSession(sessionId);
  893. session.PlayableMediaTypes = capabilities.PlayableMediaTypes;
  894. session.SupportedCommands = capabilities.SupportedCommands;
  895. }
  896. public SessionInfoDto GetSessionInfoDto(SessionInfo session)
  897. {
  898. var dto = new SessionInfoDto
  899. {
  900. Client = session.Client,
  901. DeviceId = session.DeviceId,
  902. DeviceName = session.DeviceName,
  903. Id = session.Id.ToString("N"),
  904. LastActivityDate = session.LastActivityDate,
  905. NowPlayingPositionTicks = session.NowPlayingPositionTicks,
  906. SupportsRemoteControl = session.SupportsRemoteControl,
  907. IsPaused = session.IsPaused,
  908. IsMuted = session.IsMuted,
  909. NowViewingContext = session.NowViewingContext,
  910. NowViewingItemId = session.NowViewingItemId,
  911. NowViewingItemName = session.NowViewingItemName,
  912. NowViewingItemType = session.NowViewingItemType,
  913. ApplicationVersion = session.ApplicationVersion,
  914. CanSeek = session.CanSeek,
  915. QueueableMediaTypes = session.QueueableMediaTypes,
  916. PlayableMediaTypes = session.PlayableMediaTypes,
  917. RemoteEndPoint = session.RemoteEndPoint,
  918. AdditionalUsers = session.AdditionalUsers,
  919. SupportedCommands = session.SupportedCommands,
  920. NowPlayingAudioStreamIndex = session.NowPlayingAudioStreamIndex,
  921. NowPlayingSubtitleStreamIndex = session.NowPlayingSubtitleStreamIndex,
  922. UserName = session.UserName,
  923. VolumeLevel = session.VolumeLevel
  924. };
  925. if (session.NowPlayingItem != null)
  926. {
  927. dto.NowPlayingItem = GetNowPlayingInfo(session.NowPlayingItem, session.NowPlayingMediaSourceId, session.NowPlayingRunTimeTicks);
  928. }
  929. if (session.UserId.HasValue)
  930. {
  931. dto.UserId = session.UserId.Value.ToString("N");
  932. }
  933. return dto;
  934. }
  935. /// <summary>
  936. /// Converts a BaseItem to a BaseItemInfo
  937. /// </summary>
  938. /// <param name="item">The item.</param>
  939. /// <param name="mediaSourceId">The media version identifier.</param>
  940. /// <param name="nowPlayingRuntimeTicks">The now playing runtime ticks.</param>
  941. /// <returns>BaseItemInfo.</returns>
  942. /// <exception cref="System.ArgumentNullException">item</exception>
  943. private BaseItemInfo GetNowPlayingInfo(BaseItem item, string mediaSourceId, long? nowPlayingRuntimeTicks)
  944. {
  945. if (item == null)
  946. {
  947. throw new ArgumentNullException("item");
  948. }
  949. var info = new BaseItemInfo
  950. {
  951. Id = GetDtoId(item),
  952. Name = item.Name,
  953. MediaType = item.MediaType,
  954. Type = item.GetClientTypeName(),
  955. RunTimeTicks = nowPlayingRuntimeTicks,
  956. MediaSourceId = mediaSourceId
  957. };
  958. info.PrimaryImageTag = GetImageCacheTag(item, ImageType.Primary);
  959. var backropItem = item.HasImage(ImageType.Backdrop) ? item : null;
  960. var thumbItem = item.HasImage(ImageType.Thumb) ? item : null;
  961. if (thumbItem == null)
  962. {
  963. var episode = item as Episode;
  964. if (episode != null)
  965. {
  966. var series = episode.Series;
  967. if (series != null && series.HasImage(ImageType.Thumb))
  968. {
  969. thumbItem = series;
  970. }
  971. }
  972. }
  973. if (backropItem == null)
  974. {
  975. var episode = item as Episode;
  976. if (episode != null)
  977. {
  978. var series = episode.Series;
  979. if (series != null && series.HasImage(ImageType.Backdrop))
  980. {
  981. backropItem = series;
  982. }
  983. }
  984. }
  985. if (thumbItem == null)
  986. {
  987. thumbItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Thumb));
  988. }
  989. if (thumbItem != null)
  990. {
  991. info.ThumbImageTag = GetImageCacheTag(thumbItem, ImageType.Thumb);
  992. info.ThumbItemId = GetDtoId(thumbItem);
  993. }
  994. if (thumbItem != null)
  995. {
  996. info.BackdropImageTag = GetImageCacheTag(backropItem, ImageType.Backdrop);
  997. info.BackdropItemId = GetDtoId(backropItem);
  998. }
  999. return info;
  1000. }
  1001. private Guid? GetImageCacheTag(BaseItem item, ImageType type)
  1002. {
  1003. try
  1004. {
  1005. return _imageProcessor.GetImageCacheTag(item, type);
  1006. }
  1007. catch (Exception ex)
  1008. {
  1009. _logger.ErrorException("Error getting {0} image info", ex, type);
  1010. return null;
  1011. }
  1012. }
  1013. private string GetDtoId(BaseItem item)
  1014. {
  1015. return _dtoService.GetDtoId(item);
  1016. }
  1017. }
  1018. }