SessionManager.cs 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549
  1. using MediaBrowser.Common.Events;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Controller;
  5. using MediaBrowser.Controller.Configuration;
  6. using MediaBrowser.Controller.Drawing;
  7. using MediaBrowser.Controller.Dto;
  8. using MediaBrowser.Controller.Entities;
  9. using MediaBrowser.Controller.Entities.Audio;
  10. using MediaBrowser.Controller.Entities.TV;
  11. using MediaBrowser.Controller.Library;
  12. using MediaBrowser.Controller.LiveTv;
  13. using MediaBrowser.Controller.Persistence;
  14. using MediaBrowser.Controller.Session;
  15. using MediaBrowser.Model.Entities;
  16. using MediaBrowser.Model.Library;
  17. using MediaBrowser.Model.Logging;
  18. using MediaBrowser.Model.Serialization;
  19. using MediaBrowser.Model.Session;
  20. using System;
  21. using System.Collections.Concurrent;
  22. using System.Collections.Generic;
  23. using System.Globalization;
  24. using System.IO;
  25. using System.Linq;
  26. using System.Threading;
  27. using System.Threading.Tasks;
  28. using MediaBrowser.Model.Users;
  29. namespace MediaBrowser.Server.Implementations.Session
  30. {
  31. /// <summary>
  32. /// Class SessionManager
  33. /// </summary>
  34. public class SessionManager : ISessionManager
  35. {
  36. /// <summary>
  37. /// The _user data repository
  38. /// </summary>
  39. private readonly IUserDataManager _userDataRepository;
  40. /// <summary>
  41. /// The _user repository
  42. /// </summary>
  43. private readonly IUserRepository _userRepository;
  44. /// <summary>
  45. /// The _logger
  46. /// </summary>
  47. private readonly ILogger _logger;
  48. private readonly ILibraryManager _libraryManager;
  49. private readonly IUserManager _userManager;
  50. private readonly IMusicManager _musicManager;
  51. private readonly IDtoService _dtoService;
  52. private readonly IImageProcessor _imageProcessor;
  53. private readonly IItemRepository _itemRepo;
  54. private readonly IHttpClient _httpClient;
  55. private readonly IJsonSerializer _jsonSerializer;
  56. private readonly IServerApplicationHost _appHost;
  57. /// <summary>
  58. /// Gets or sets the configuration manager.
  59. /// </summary>
  60. /// <value>The configuration manager.</value>
  61. private readonly IServerConfigurationManager _configurationManager;
  62. /// <summary>
  63. /// The _active connections
  64. /// </summary>
  65. private readonly ConcurrentDictionary<string, SessionInfo> _activeConnections =
  66. new ConcurrentDictionary<string, SessionInfo>(StringComparer.OrdinalIgnoreCase);
  67. /// <summary>
  68. /// Occurs when [playback start].
  69. /// </summary>
  70. public event EventHandler<PlaybackProgressEventArgs> PlaybackStart;
  71. /// <summary>
  72. /// Occurs when [playback progress].
  73. /// </summary>
  74. public event EventHandler<PlaybackProgressEventArgs> PlaybackProgress;
  75. /// <summary>
  76. /// Occurs when [playback stopped].
  77. /// </summary>
  78. public event EventHandler<PlaybackStopEventArgs> PlaybackStopped;
  79. public event EventHandler<SessionEventArgs> SessionStarted;
  80. public event EventHandler<SessionEventArgs> CapabilitiesChanged;
  81. public event EventHandler<SessionEventArgs> SessionEnded;
  82. public event EventHandler<SessionEventArgs> SessionActivity;
  83. private IEnumerable<ISessionControllerFactory> _sessionFactories = new List<ISessionControllerFactory>();
  84. private readonly SemaphoreSlim _sessionLock = new SemaphoreSlim(1, 1);
  85. /// <summary>
  86. /// Initializes a new instance of the <see cref="SessionManager" /> class.
  87. /// </summary>
  88. /// <param name="userDataRepository">The user data repository.</param>
  89. /// <param name="configurationManager">The configuration manager.</param>
  90. /// <param name="logger">The logger.</param>
  91. /// <param name="userRepository">The user repository.</param>
  92. /// <param name="libraryManager">The library manager.</param>
  93. public SessionManager(IUserDataManager userDataRepository, IServerConfigurationManager configurationManager, ILogger logger, IUserRepository userRepository, ILibraryManager libraryManager, IUserManager userManager, IMusicManager musicManager, IDtoService dtoService, IImageProcessor imageProcessor, IItemRepository itemRepo, IJsonSerializer jsonSerializer, IServerApplicationHost appHost, IHttpClient httpClient)
  94. {
  95. _userDataRepository = userDataRepository;
  96. _configurationManager = configurationManager;
  97. _logger = logger;
  98. _userRepository = userRepository;
  99. _libraryManager = libraryManager;
  100. _userManager = userManager;
  101. _musicManager = musicManager;
  102. _dtoService = dtoService;
  103. _imageProcessor = imageProcessor;
  104. _itemRepo = itemRepo;
  105. _jsonSerializer = jsonSerializer;
  106. _appHost = appHost;
  107. _httpClient = httpClient;
  108. }
  109. /// <summary>
  110. /// Adds the parts.
  111. /// </summary>
  112. /// <param name="sessionFactories">The session factories.</param>
  113. public void AddParts(IEnumerable<ISessionControllerFactory> sessionFactories)
  114. {
  115. _sessionFactories = sessionFactories.ToList();
  116. }
  117. /// <summary>
  118. /// Gets all connections.
  119. /// </summary>
  120. /// <value>All connections.</value>
  121. public IEnumerable<SessionInfo> Sessions
  122. {
  123. get { return _activeConnections.Values.OrderByDescending(c => c.LastActivityDate).ToList(); }
  124. }
  125. private void OnSessionStarted(SessionInfo info)
  126. {
  127. EventHelper.QueueEventIfNotNull(SessionStarted, this, new SessionEventArgs
  128. {
  129. SessionInfo = info
  130. }, _logger);
  131. if (!string.IsNullOrWhiteSpace(info.DeviceId))
  132. {
  133. var capabilities = GetSavedCapabilities(info.DeviceId);
  134. if (capabilities != null)
  135. {
  136. ReportCapabilities(info, capabilities, false);
  137. }
  138. }
  139. }
  140. private async void OnSessionEnded(SessionInfo info)
  141. {
  142. try
  143. {
  144. await SendSessionEndedNotification(info, CancellationToken.None).ConfigureAwait(false);
  145. }
  146. catch (Exception ex)
  147. {
  148. _logger.ErrorException("Error in SendSessionEndedNotification", ex);
  149. }
  150. EventHelper.QueueEventIfNotNull(SessionEnded, this, new SessionEventArgs
  151. {
  152. SessionInfo = info
  153. }, _logger);
  154. var disposable = info.SessionController as IDisposable;
  155. if (disposable != null)
  156. {
  157. _logger.Debug("Disposing session controller {0}", disposable.GetType().Name);
  158. try
  159. {
  160. disposable.Dispose();
  161. }
  162. catch (Exception ex)
  163. {
  164. _logger.ErrorException("Error disposing session controller", ex);
  165. }
  166. }
  167. }
  168. /// <summary>
  169. /// Logs the user activity.
  170. /// </summary>
  171. /// <param name="clientType">Type of the client.</param>
  172. /// <param name="appVersion">The app version.</param>
  173. /// <param name="deviceId">The device id.</param>
  174. /// <param name="deviceName">Name of the device.</param>
  175. /// <param name="remoteEndPoint">The remote end point.</param>
  176. /// <param name="user">The user.</param>
  177. /// <returns>Task.</returns>
  178. /// <exception cref="System.ArgumentNullException">user</exception>
  179. /// <exception cref="System.UnauthorizedAccessException"></exception>
  180. public async Task<SessionInfo> LogSessionActivity(string clientType, string appVersion, string deviceId, string deviceName, string remoteEndPoint, User user)
  181. {
  182. if (string.IsNullOrEmpty(clientType))
  183. {
  184. throw new ArgumentNullException("clientType");
  185. }
  186. if (string.IsNullOrEmpty(appVersion))
  187. {
  188. throw new ArgumentNullException("appVersion");
  189. }
  190. if (string.IsNullOrEmpty(deviceId))
  191. {
  192. throw new ArgumentNullException("deviceId");
  193. }
  194. if (string.IsNullOrEmpty(deviceName))
  195. {
  196. throw new ArgumentNullException("deviceName");
  197. }
  198. if (user != null && user.Configuration.IsDisabled)
  199. {
  200. throw new UnauthorizedAccessException(string.Format("The {0} account is currently disabled. Please consult with your administrator.", user.Name));
  201. }
  202. var activityDate = DateTime.UtcNow;
  203. var userId = user == null ? (Guid?)null : user.Id;
  204. var username = user == null ? null : user.Name;
  205. var session = await GetSessionInfo(clientType, appVersion, deviceId, deviceName, remoteEndPoint, userId, username).ConfigureAwait(false);
  206. session.LastActivityDate = activityDate;
  207. if (user == null)
  208. {
  209. return session;
  210. }
  211. var lastActivityDate = user.LastActivityDate;
  212. user.LastActivityDate = activityDate;
  213. // Don't log in the db anymore frequently than 10 seconds
  214. if (lastActivityDate.HasValue && (activityDate - lastActivityDate.Value).TotalSeconds < 10)
  215. {
  216. return session;
  217. }
  218. // Save this directly. No need to fire off all the events for this.
  219. await _userRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  220. EventHelper.FireEventIfNotNull(SessionActivity, this, new SessionEventArgs
  221. {
  222. SessionInfo = session
  223. }, _logger);
  224. return session;
  225. }
  226. public async void ReportSessionEnded(string sessionId)
  227. {
  228. await _sessionLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  229. try
  230. {
  231. var session = GetSession(sessionId, false);
  232. if (session != null)
  233. {
  234. var key = GetSessionKey(session.Client, session.ApplicationVersion, session.DeviceId);
  235. SessionInfo removed;
  236. if (_activeConnections.TryRemove(key, out removed))
  237. {
  238. OnSessionEnded(removed);
  239. }
  240. }
  241. }
  242. finally
  243. {
  244. _sessionLock.Release();
  245. }
  246. }
  247. /// <summary>
  248. /// Updates the now playing item id.
  249. /// </summary>
  250. /// <param name="session">The session.</param>
  251. /// <param name="info">The information.</param>
  252. /// <param name="libraryItem">The library item.</param>
  253. private void UpdateNowPlayingItem(SessionInfo session, PlaybackProgressInfo info, BaseItem libraryItem)
  254. {
  255. var runtimeTicks = libraryItem == null ? null : libraryItem.RunTimeTicks;
  256. if (string.IsNullOrWhiteSpace(info.MediaSourceId))
  257. {
  258. info.MediaSourceId = info.ItemId;
  259. }
  260. if (!string.Equals(info.ItemId, info.MediaSourceId) &&
  261. !string.IsNullOrWhiteSpace(info.MediaSourceId))
  262. {
  263. runtimeTicks = _libraryManager.GetItemById(new Guid(info.MediaSourceId)).RunTimeTicks;
  264. }
  265. if (!string.IsNullOrWhiteSpace(info.ItemId) && libraryItem != null)
  266. {
  267. var current = session.NowPlayingItem;
  268. if (current == null || !string.Equals(current.Id, info.ItemId, StringComparison.OrdinalIgnoreCase))
  269. {
  270. info.Item = GetItemInfo(libraryItem, libraryItem, info.MediaSourceId);
  271. }
  272. else
  273. {
  274. info.Item = current;
  275. }
  276. info.Item.RunTimeTicks = runtimeTicks;
  277. }
  278. session.NowPlayingItem = info.Item;
  279. session.LastActivityDate = DateTime.UtcNow;
  280. session.PlayState.IsPaused = info.IsPaused;
  281. session.PlayState.PositionTicks = info.PositionTicks;
  282. session.PlayState.MediaSourceId = info.MediaSourceId;
  283. session.PlayState.CanSeek = info.CanSeek;
  284. session.PlayState.IsMuted = info.IsMuted;
  285. session.PlayState.VolumeLevel = info.VolumeLevel;
  286. session.PlayState.AudioStreamIndex = info.AudioStreamIndex;
  287. session.PlayState.SubtitleStreamIndex = info.SubtitleStreamIndex;
  288. session.PlayState.PlayMethod = info.PlayMethod;
  289. }
  290. /// <summary>
  291. /// Removes the now playing item id.
  292. /// </summary>
  293. /// <param name="session">The session.</param>
  294. /// <exception cref="System.ArgumentNullException">item</exception>
  295. private void RemoveNowPlayingItem(SessionInfo session)
  296. {
  297. session.NowPlayingItem = null;
  298. session.PlayState = new PlayerStateInfo();
  299. if (!string.IsNullOrEmpty(session.DeviceId))
  300. {
  301. ClearTranscodingInfo(session.DeviceId);
  302. }
  303. }
  304. private string GetSessionKey(string clientType, string appVersion, string deviceId)
  305. {
  306. return clientType + deviceId;
  307. }
  308. /// <summary>
  309. /// Gets the connection.
  310. /// </summary>
  311. /// <param name="clientType">Type of the client.</param>
  312. /// <param name="appVersion">The app version.</param>
  313. /// <param name="deviceId">The device id.</param>
  314. /// <param name="deviceName">Name of the device.</param>
  315. /// <param name="remoteEndPoint">The remote end point.</param>
  316. /// <param name="userId">The user identifier.</param>
  317. /// <param name="username">The username.</param>
  318. /// <returns>SessionInfo.</returns>
  319. private async Task<SessionInfo> GetSessionInfo(string clientType, string appVersion, string deviceId, string deviceName, string remoteEndPoint, Guid? userId, string username)
  320. {
  321. var key = GetSessionKey(clientType, appVersion, deviceId);
  322. await _sessionLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  323. try
  324. {
  325. var connection = _activeConnections.GetOrAdd(key, keyName =>
  326. {
  327. var sessionInfo = new SessionInfo
  328. {
  329. Client = clientType,
  330. DeviceId = deviceId,
  331. ApplicationVersion = appVersion,
  332. Id = Guid.NewGuid().ToString("N")
  333. };
  334. OnSessionStarted(sessionInfo);
  335. return sessionInfo;
  336. });
  337. connection.DeviceName = deviceName;
  338. connection.UserId = userId;
  339. connection.UserName = username;
  340. connection.RemoteEndPoint = remoteEndPoint;
  341. if (!userId.HasValue)
  342. {
  343. connection.AdditionalUsers.Clear();
  344. }
  345. if (connection.SessionController == null)
  346. {
  347. connection.SessionController = _sessionFactories
  348. .Select(i => i.GetSessionController(connection))
  349. .FirstOrDefault(i => i != null);
  350. }
  351. return connection;
  352. }
  353. finally
  354. {
  355. _sessionLock.Release();
  356. }
  357. }
  358. private List<User> GetUsers(SessionInfo session)
  359. {
  360. var users = new List<User>();
  361. if (session.UserId.HasValue)
  362. {
  363. var user = _userManager.GetUserById(session.UserId.Value);
  364. if (user == null)
  365. {
  366. throw new InvalidOperationException("User not found");
  367. }
  368. users.Add(user);
  369. var additionalUsers = session.AdditionalUsers
  370. .Select(i => _userManager.GetUserById(new Guid(i.UserId)))
  371. .Where(i => i != null);
  372. users.AddRange(additionalUsers);
  373. }
  374. return users;
  375. }
  376. /// <summary>
  377. /// Used to report that playback has started for an item
  378. /// </summary>
  379. /// <param name="info">The info.</param>
  380. /// <returns>Task.</returns>
  381. /// <exception cref="System.ArgumentNullException">info</exception>
  382. public async Task OnPlaybackStart(PlaybackStartInfo info)
  383. {
  384. if (info == null)
  385. {
  386. throw new ArgumentNullException("info");
  387. }
  388. var session = GetSession(info.SessionId);
  389. var libraryItem = string.IsNullOrWhiteSpace(info.ItemId)
  390. ? null
  391. : _libraryManager.GetItemById(new Guid(info.ItemId));
  392. UpdateNowPlayingItem(session, info, libraryItem);
  393. if (!string.IsNullOrEmpty(session.DeviceId) && info.PlayMethod != PlayMethod.Transcode)
  394. {
  395. ClearTranscodingInfo(session.DeviceId);
  396. }
  397. session.QueueableMediaTypes = info.QueueableMediaTypes;
  398. var users = GetUsers(session);
  399. if (libraryItem != null)
  400. {
  401. var key = libraryItem.GetUserDataKey();
  402. foreach (var user in users)
  403. {
  404. await OnPlaybackStart(user.Id, key, libraryItem).ConfigureAwait(false);
  405. }
  406. }
  407. // Nothing to save here
  408. // Fire events to inform plugins
  409. EventHelper.QueueEventIfNotNull(PlaybackStart, this, new PlaybackProgressEventArgs
  410. {
  411. Item = libraryItem,
  412. Users = users,
  413. MediaSourceId = info.MediaSourceId,
  414. MediaInfo = info.Item,
  415. DeviceName = session.DeviceName,
  416. ClientName = session.Client,
  417. DeviceId = session.DeviceId
  418. }, _logger);
  419. await SendPlaybackStartNotification(session, CancellationToken.None).ConfigureAwait(false);
  420. }
  421. /// <summary>
  422. /// Called when [playback start].
  423. /// </summary>
  424. /// <param name="userId">The user identifier.</param>
  425. /// <param name="userDataKey">The user data key.</param>
  426. /// <param name="item">The item.</param>
  427. /// <returns>Task.</returns>
  428. private async Task OnPlaybackStart(Guid userId, string userDataKey, IHasUserData item)
  429. {
  430. var data = _userDataRepository.GetUserData(userId, userDataKey);
  431. data.PlayCount++;
  432. data.LastPlayedDate = DateTime.UtcNow;
  433. if (!(item is Video))
  434. {
  435. data.Played = true;
  436. }
  437. await _userDataRepository.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackStart, CancellationToken.None).ConfigureAwait(false);
  438. }
  439. /// <summary>
  440. /// Used to report playback progress for an item
  441. /// </summary>
  442. /// <param name="info">The info.</param>
  443. /// <returns>Task.</returns>
  444. /// <exception cref="System.ArgumentNullException"></exception>
  445. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  446. public async Task OnPlaybackProgress(PlaybackProgressInfo info)
  447. {
  448. if (info == null)
  449. {
  450. throw new ArgumentNullException("info");
  451. }
  452. var session = GetSession(info.SessionId);
  453. var libraryItem = string.IsNullOrWhiteSpace(info.ItemId)
  454. ? null
  455. : _libraryManager.GetItemById(new Guid(info.ItemId));
  456. UpdateNowPlayingItem(session, info, libraryItem);
  457. var users = GetUsers(session);
  458. if (libraryItem != null)
  459. {
  460. var key = libraryItem.GetUserDataKey();
  461. foreach (var user in users)
  462. {
  463. await OnPlaybackProgress(user.Id, key, libraryItem, info.PositionTicks).ConfigureAwait(false);
  464. }
  465. }
  466. EventHelper.FireEventIfNotNull(PlaybackProgress, this, new PlaybackProgressEventArgs
  467. {
  468. Item = libraryItem,
  469. Users = users,
  470. PlaybackPositionTicks = session.PlayState.PositionTicks,
  471. MediaSourceId = session.PlayState.MediaSourceId,
  472. MediaInfo = info.Item,
  473. DeviceName = session.DeviceName,
  474. ClientName = session.Client,
  475. DeviceId = session.DeviceId
  476. }, _logger);
  477. }
  478. private async Task OnPlaybackProgress(Guid userId, string userDataKey, BaseItem item, long? positionTicks)
  479. {
  480. var data = _userDataRepository.GetUserData(userId, userDataKey);
  481. if (positionTicks.HasValue)
  482. {
  483. UpdatePlayState(item, data, positionTicks.Value);
  484. await _userDataRepository.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackProgress, CancellationToken.None).ConfigureAwait(false);
  485. }
  486. }
  487. /// <summary>
  488. /// Used to report that playback has ended for an item
  489. /// </summary>
  490. /// <param name="info">The info.</param>
  491. /// <returns>Task.</returns>
  492. /// <exception cref="System.ArgumentNullException">info</exception>
  493. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  494. public async Task OnPlaybackStopped(PlaybackStopInfo info)
  495. {
  496. if (info == null)
  497. {
  498. throw new ArgumentNullException("info");
  499. }
  500. if (info.PositionTicks.HasValue && info.PositionTicks.Value < 0)
  501. {
  502. throw new ArgumentOutOfRangeException("positionTicks");
  503. }
  504. var session = GetSession(info.SessionId);
  505. var libraryItem = string.IsNullOrWhiteSpace(info.ItemId)
  506. ? null
  507. : _libraryManager.GetItemById(new Guid(info.ItemId));
  508. // Normalize
  509. if (string.IsNullOrWhiteSpace(info.MediaSourceId))
  510. {
  511. info.MediaSourceId = info.ItemId;
  512. }
  513. RemoveNowPlayingItem(session);
  514. var users = GetUsers(session);
  515. var playedToCompletion = false;
  516. if (libraryItem != null)
  517. {
  518. var key = libraryItem.GetUserDataKey();
  519. foreach (var user in users)
  520. {
  521. playedToCompletion = await OnPlaybackStopped(user.Id, key, libraryItem, info.PositionTicks).ConfigureAwait(false);
  522. }
  523. }
  524. EventHelper.QueueEventIfNotNull(PlaybackStopped, this, new PlaybackStopEventArgs
  525. {
  526. Item = libraryItem,
  527. Users = users,
  528. PlaybackPositionTicks = info.PositionTicks,
  529. PlayedToCompletion = playedToCompletion,
  530. MediaSourceId = info.MediaSourceId,
  531. MediaInfo = info.Item,
  532. DeviceName = session.DeviceName,
  533. ClientName = session.Client,
  534. DeviceId = session.DeviceId
  535. }, _logger);
  536. await SendPlaybackStoppedNotification(session, CancellationToken.None).ConfigureAwait(false);
  537. }
  538. private async Task<bool> OnPlaybackStopped(Guid userId, string userDataKey, BaseItem item, long? positionTicks)
  539. {
  540. var data = _userDataRepository.GetUserData(userId, userDataKey);
  541. bool playedToCompletion;
  542. if (positionTicks.HasValue)
  543. {
  544. playedToCompletion = UpdatePlayState(item, data, positionTicks.Value);
  545. }
  546. else
  547. {
  548. // If the client isn't able to report this, then we'll just have to make an assumption
  549. data.PlayCount++;
  550. data.Played = true;
  551. data.PlaybackPositionTicks = 0;
  552. playedToCompletion = true;
  553. }
  554. await _userDataRepository.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackFinished, CancellationToken.None).ConfigureAwait(false);
  555. return playedToCompletion;
  556. }
  557. /// <summary>
  558. /// Updates playstate position for an item but does not save
  559. /// </summary>
  560. /// <param name="item">The item</param>
  561. /// <param name="data">User data for the item</param>
  562. /// <param name="positionTicks">The current playback position</param>
  563. private bool UpdatePlayState(BaseItem item, UserItemData data, long positionTicks)
  564. {
  565. var playedToCompletion = false;
  566. var hasRuntime = item.RunTimeTicks.HasValue && item.RunTimeTicks > 0;
  567. // If a position has been reported, and if we know the duration
  568. if (positionTicks > 0 && hasRuntime)
  569. {
  570. var pctIn = Decimal.Divide(positionTicks, item.RunTimeTicks.Value) * 100;
  571. // Don't track in very beginning
  572. if (pctIn < _configurationManager.Configuration.MinResumePct)
  573. {
  574. positionTicks = 0;
  575. }
  576. // If we're at the end, assume completed
  577. else if (pctIn > _configurationManager.Configuration.MaxResumePct || positionTicks >= item.RunTimeTicks.Value)
  578. {
  579. positionTicks = 0;
  580. data.Played = playedToCompletion = true;
  581. }
  582. else
  583. {
  584. // Enforce MinResumeDuration
  585. var durationSeconds = TimeSpan.FromTicks(item.RunTimeTicks.Value).TotalSeconds;
  586. if (durationSeconds < _configurationManager.Configuration.MinResumeDurationSeconds)
  587. {
  588. positionTicks = 0;
  589. data.Played = playedToCompletion = true;
  590. }
  591. }
  592. }
  593. else if (!hasRuntime)
  594. {
  595. // If we don't know the runtime we'll just have to assume it was fully played
  596. data.Played = playedToCompletion = true;
  597. positionTicks = 0;
  598. }
  599. if (item is Audio)
  600. {
  601. positionTicks = 0;
  602. }
  603. data.PlaybackPositionTicks = positionTicks;
  604. return playedToCompletion;
  605. }
  606. /// <summary>
  607. /// Gets the session.
  608. /// </summary>
  609. /// <param name="sessionId">The session identifier.</param>
  610. /// <param name="throwOnMissing">if set to <c>true</c> [throw on missing].</param>
  611. /// <returns>SessionInfo.</returns>
  612. /// <exception cref="ResourceNotFoundException"></exception>
  613. private SessionInfo GetSession(string sessionId, bool throwOnMissing = true)
  614. {
  615. var session = Sessions.FirstOrDefault(i => string.Equals(i.Id, sessionId));
  616. if (session == null && throwOnMissing)
  617. {
  618. throw new ResourceNotFoundException(string.Format("Session {0} not found.", sessionId));
  619. }
  620. return session;
  621. }
  622. public Task SendMessageCommand(string controllingSessionId, string sessionId, MessageCommand command, CancellationToken cancellationToken)
  623. {
  624. var generalCommand = new GeneralCommand
  625. {
  626. Name = GeneralCommandType.DisplayMessage.ToString()
  627. };
  628. generalCommand.Arguments["Header"] = command.Header;
  629. generalCommand.Arguments["Text"] = command.Text;
  630. if (command.TimeoutMs.HasValue)
  631. {
  632. generalCommand.Arguments["TimeoutMs"] = command.TimeoutMs.Value.ToString(CultureInfo.InvariantCulture);
  633. }
  634. return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
  635. }
  636. public Task SendGeneralCommand(string controllingSessionId, string sessionId, GeneralCommand command, CancellationToken cancellationToken)
  637. {
  638. var session = GetSession(sessionId);
  639. var controllingSession = GetSession(controllingSessionId);
  640. AssertCanControl(session, controllingSession);
  641. return session.SessionController.SendGeneralCommand(command, cancellationToken);
  642. }
  643. public Task SendPlayCommand(string controllingSessionId, string sessionId, PlayRequest command, CancellationToken cancellationToken)
  644. {
  645. var session = GetSession(sessionId);
  646. var user = session.UserId.HasValue ? _userManager.GetUserById(session.UserId.Value) : null;
  647. List<BaseItem> items;
  648. if (command.PlayCommand == PlayCommand.PlayInstantMix)
  649. {
  650. items = command.ItemIds.SelectMany(i => TranslateItemForInstantMix(i, user))
  651. .Where(i => i.LocationType != LocationType.Virtual)
  652. .ToList();
  653. command.PlayCommand = PlayCommand.PlayNow;
  654. }
  655. else
  656. {
  657. items = command.ItemIds.SelectMany(i => TranslateItemForPlayback(i, user))
  658. .Where(i => i.LocationType != LocationType.Virtual)
  659. .ToList();
  660. }
  661. if (command.PlayCommand == PlayCommand.PlayShuffle)
  662. {
  663. items = items.OrderBy(i => Guid.NewGuid()).ToList();
  664. command.PlayCommand = PlayCommand.PlayNow;
  665. }
  666. command.ItemIds = items.Select(i => i.Id.ToString("N")).ToArray();
  667. if (user != null)
  668. {
  669. if (items.Any(i => i.GetPlayAccess(user) != PlayAccess.Full))
  670. {
  671. throw new ArgumentException(string.Format("{0} is not allowed to play media.", user.Name));
  672. }
  673. }
  674. if (command.PlayCommand != PlayCommand.PlayNow)
  675. {
  676. if (items.Any(i => !session.QueueableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  677. {
  678. throw new ArgumentException(string.Format("{0} is unable to queue the requested media type.", session.DeviceName ?? session.Id.ToString()));
  679. }
  680. }
  681. else
  682. {
  683. if (items.Any(i => !session.PlayableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  684. {
  685. throw new ArgumentException(string.Format("{0} is unable to play the requested media type.", session.DeviceName ?? session.Id.ToString()));
  686. }
  687. }
  688. var controllingSession = GetSession(controllingSessionId);
  689. AssertCanControl(session, controllingSession);
  690. if (controllingSession.UserId.HasValue)
  691. {
  692. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  693. }
  694. return session.SessionController.SendPlayCommand(command, cancellationToken);
  695. }
  696. private IEnumerable<BaseItem> TranslateItemForPlayback(string id, User user)
  697. {
  698. var item = _libraryManager.GetItemById(new Guid(id));
  699. if (item.IsFolder)
  700. {
  701. var folder = (Folder)item;
  702. var items = user == null ? folder.RecursiveChildren :
  703. folder.GetRecursiveChildren(user);
  704. items = items.Where(i => !i.IsFolder);
  705. items = items.OrderBy(i => i.SortName);
  706. return items;
  707. }
  708. return new[] { item };
  709. }
  710. private IEnumerable<BaseItem> TranslateItemForInstantMix(string id, User user)
  711. {
  712. var item = _libraryManager.GetItemById(new Guid(id));
  713. var audio = item as Audio;
  714. if (audio != null)
  715. {
  716. return _musicManager.GetInstantMixFromSong(audio, user);
  717. }
  718. var artist = item as MusicArtist;
  719. if (artist != null)
  720. {
  721. return _musicManager.GetInstantMixFromArtist(artist.Name, user);
  722. }
  723. var album = item as MusicAlbum;
  724. if (album != null)
  725. {
  726. return _musicManager.GetInstantMixFromAlbum(album, user);
  727. }
  728. var genre = item as MusicGenre;
  729. if (genre != null)
  730. {
  731. return _musicManager.GetInstantMixFromGenres(new[] { genre.Name }, user);
  732. }
  733. return new BaseItem[] { };
  734. }
  735. public Task SendBrowseCommand(string controllingSessionId, string sessionId, BrowseRequest command, CancellationToken cancellationToken)
  736. {
  737. var generalCommand = new GeneralCommand
  738. {
  739. Name = GeneralCommandType.DisplayContent.ToString()
  740. };
  741. generalCommand.Arguments["ItemId"] = command.ItemId;
  742. generalCommand.Arguments["ItemName"] = command.ItemName;
  743. generalCommand.Arguments["ItemType"] = command.ItemType;
  744. return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
  745. }
  746. public Task SendPlaystateCommand(string controllingSessionId, string sessionId, PlaystateRequest command, CancellationToken cancellationToken)
  747. {
  748. var session = GetSession(sessionId);
  749. var controllingSession = GetSession(controllingSessionId);
  750. AssertCanControl(session, controllingSession);
  751. if (controllingSession.UserId.HasValue)
  752. {
  753. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  754. }
  755. return session.SessionController.SendPlaystateCommand(command, cancellationToken);
  756. }
  757. private void AssertCanControl(SessionInfo session, SessionInfo controllingSession)
  758. {
  759. if (session == null)
  760. {
  761. throw new ArgumentNullException("session");
  762. }
  763. if (controllingSession == null)
  764. {
  765. throw new ArgumentNullException("controllingSession");
  766. }
  767. }
  768. /// <summary>
  769. /// Sends the restart required message.
  770. /// </summary>
  771. /// <param name="cancellationToken">The cancellation token.</param>
  772. /// <returns>Task.</returns>
  773. public Task SendRestartRequiredNotification(CancellationToken cancellationToken)
  774. {
  775. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  776. var info = _appHost.GetSystemInfo();
  777. var tasks = sessions.Select(session => Task.Run(async () =>
  778. {
  779. try
  780. {
  781. await session.SessionController.SendRestartRequiredNotification(info, cancellationToken).ConfigureAwait(false);
  782. }
  783. catch (Exception ex)
  784. {
  785. _logger.ErrorException("Error in SendRestartRequiredNotification.", ex);
  786. }
  787. }, cancellationToken));
  788. return Task.WhenAll(tasks);
  789. }
  790. /// <summary>
  791. /// Sends the server shutdown notification.
  792. /// </summary>
  793. /// <param name="cancellationToken">The cancellation token.</param>
  794. /// <returns>Task.</returns>
  795. public Task SendServerShutdownNotification(CancellationToken cancellationToken)
  796. {
  797. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  798. var tasks = sessions.Select(session => Task.Run(async () =>
  799. {
  800. try
  801. {
  802. await session.SessionController.SendServerShutdownNotification(cancellationToken).ConfigureAwait(false);
  803. }
  804. catch (Exception ex)
  805. {
  806. _logger.ErrorException("Error in SendServerShutdownNotification.", ex);
  807. }
  808. }, cancellationToken));
  809. return Task.WhenAll(tasks);
  810. }
  811. /// <summary>
  812. /// Sends the server restart notification.
  813. /// </summary>
  814. /// <param name="cancellationToken">The cancellation token.</param>
  815. /// <returns>Task.</returns>
  816. public Task SendServerRestartNotification(CancellationToken cancellationToken)
  817. {
  818. _logger.Debug("Beginning SendServerRestartNotification");
  819. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  820. var tasks = sessions.Select(session => Task.Run(async () =>
  821. {
  822. try
  823. {
  824. await session.SessionController.SendServerRestartNotification(cancellationToken).ConfigureAwait(false);
  825. }
  826. catch (Exception ex)
  827. {
  828. _logger.ErrorException("Error in SendServerRestartNotification.", ex);
  829. }
  830. }, cancellationToken));
  831. return Task.WhenAll(tasks);
  832. }
  833. public Task SendSessionEndedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  834. {
  835. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  836. var dto = GetSessionInfoDto(sessionInfo);
  837. var tasks = sessions.Select(session => Task.Run(async () =>
  838. {
  839. try
  840. {
  841. await session.SessionController.SendSessionEndedNotification(dto, cancellationToken).ConfigureAwait(false);
  842. }
  843. catch (Exception ex)
  844. {
  845. _logger.ErrorException("Error in SendSessionEndedNotification.", ex);
  846. }
  847. }, cancellationToken));
  848. return Task.WhenAll(tasks);
  849. }
  850. public Task SendPlaybackStartNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  851. {
  852. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  853. var dto = GetSessionInfoDto(sessionInfo);
  854. var tasks = sessions.Select(session => Task.Run(async () =>
  855. {
  856. try
  857. {
  858. await session.SessionController.SendPlaybackStartNotification(dto, cancellationToken).ConfigureAwait(false);
  859. }
  860. catch (Exception ex)
  861. {
  862. _logger.ErrorException("Error in SendPlaybackStartNotification.", ex);
  863. }
  864. }, cancellationToken));
  865. return Task.WhenAll(tasks);
  866. }
  867. public Task SendPlaybackStoppedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  868. {
  869. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  870. var dto = GetSessionInfoDto(sessionInfo);
  871. var tasks = sessions.Select(session => Task.Run(async () =>
  872. {
  873. try
  874. {
  875. await session.SessionController.SendPlaybackStoppedNotification(dto, cancellationToken).ConfigureAwait(false);
  876. }
  877. catch (Exception ex)
  878. {
  879. _logger.ErrorException("Error in SendPlaybackStoppedNotification.", ex);
  880. }
  881. }, cancellationToken));
  882. return Task.WhenAll(tasks);
  883. }
  884. /// <summary>
  885. /// Adds the additional user.
  886. /// </summary>
  887. /// <param name="sessionId">The session identifier.</param>
  888. /// <param name="userId">The user identifier.</param>
  889. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  890. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  891. public void AddAdditionalUser(string sessionId, Guid userId)
  892. {
  893. var session = GetSession(sessionId);
  894. if (!session.UserId.HasValue)
  895. {
  896. throw new UnauthorizedAccessException("Cannot modify additional users without authenticating first.");
  897. }
  898. if (session.UserId.Value == userId)
  899. {
  900. throw new ArgumentException("The requested user is already the primary user of the session.");
  901. }
  902. if (session.AdditionalUsers.All(i => new Guid(i.UserId) != userId))
  903. {
  904. var user = _userManager.GetUserById(userId);
  905. session.AdditionalUsers.Add(new SessionUserInfo
  906. {
  907. UserId = userId.ToString("N"),
  908. UserName = user.Name
  909. });
  910. }
  911. }
  912. /// <summary>
  913. /// Removes the additional user.
  914. /// </summary>
  915. /// <param name="sessionId">The session identifier.</param>
  916. /// <param name="userId">The user identifier.</param>
  917. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  918. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  919. public void RemoveAdditionalUser(string sessionId, Guid userId)
  920. {
  921. var session = GetSession(sessionId);
  922. if (!session.UserId.HasValue)
  923. {
  924. throw new UnauthorizedAccessException("Cannot modify additional users without authenticating first.");
  925. }
  926. if (session.UserId.Value == userId)
  927. {
  928. throw new ArgumentException("The requested user is already the primary user of the session.");
  929. }
  930. var user = session.AdditionalUsers.FirstOrDefault(i => new Guid(i.UserId) == userId);
  931. if (user != null)
  932. {
  933. session.AdditionalUsers.Remove(user);
  934. }
  935. }
  936. public void ValidateSecurityToken(string token)
  937. {
  938. }
  939. /// <summary>
  940. /// Authenticates the new session.
  941. /// </summary>
  942. /// <param name="username">The username.</param>
  943. /// <param name="password">The password.</param>
  944. /// <param name="clientType">Type of the client.</param>
  945. /// <param name="appVersion">The application version.</param>
  946. /// <param name="deviceId">The device identifier.</param>
  947. /// <param name="deviceName">Name of the device.</param>
  948. /// <param name="remoteEndPoint">The remote end point.</param>
  949. /// <returns>Task{SessionInfo}.</returns>
  950. /// <exception cref="System.UnauthorizedAccessException">Invalid user or password entered.</exception>
  951. /// <exception cref="UnauthorizedAccessException"></exception>
  952. public async Task<AuthenticationResult> AuthenticateNewSession(string username, string password, string clientType, string appVersion, string deviceId, string deviceName, string remoteEndPoint)
  953. {
  954. var result = await _userManager.AuthenticateUser(username, password).ConfigureAwait(false);
  955. if (!result)
  956. {
  957. throw new UnauthorizedAccessException("Invalid user or password entered.");
  958. }
  959. var user = _userManager.Users
  960. .First(i => string.Equals(username, i.Name, StringComparison.OrdinalIgnoreCase));
  961. var session = await LogSessionActivity(clientType,
  962. appVersion,
  963. deviceId,
  964. deviceName,
  965. remoteEndPoint,
  966. user)
  967. .ConfigureAwait(false);
  968. return new AuthenticationResult
  969. {
  970. User = _dtoService.GetUserDto(user),
  971. SessionInfo = GetSessionInfoDto(session),
  972. AuthenticationToken = Guid.NewGuid().ToString("N")
  973. };
  974. }
  975. /// <summary>
  976. /// Reports the capabilities.
  977. /// </summary>
  978. /// <param name="sessionId">The session identifier.</param>
  979. /// <param name="capabilities">The capabilities.</param>
  980. public void ReportCapabilities(string sessionId, SessionCapabilities capabilities)
  981. {
  982. var session = GetSession(sessionId);
  983. ReportCapabilities(session, capabilities, true);
  984. }
  985. private async void ReportCapabilities(SessionInfo session,
  986. SessionCapabilities capabilities,
  987. bool saveCapabilities)
  988. {
  989. session.PlayableMediaTypes = capabilities.PlayableMediaTypes;
  990. session.SupportedCommands = capabilities.SupportedCommands;
  991. if (!string.IsNullOrWhiteSpace(capabilities.MessageCallbackUrl))
  992. {
  993. var controller = session.SessionController as HttpSessionController;
  994. if (controller == null)
  995. {
  996. session.SessionController = new HttpSessionController(_httpClient, _jsonSerializer, session, capabilities.MessageCallbackUrl, this);
  997. }
  998. }
  999. EventHelper.FireEventIfNotNull(CapabilitiesChanged, this, new SessionEventArgs
  1000. {
  1001. SessionInfo = session
  1002. }, _logger);
  1003. if (saveCapabilities)
  1004. {
  1005. await SaveCapabilities(session.DeviceId, capabilities).ConfigureAwait(false);
  1006. }
  1007. }
  1008. private string GetCapabilitiesFilePath(string deviceId)
  1009. {
  1010. var filename = deviceId.GetMD5().ToString("N") + ".json";
  1011. return Path.Combine(_configurationManager.ApplicationPaths.CachePath, "devices", filename);
  1012. }
  1013. private SessionCapabilities GetSavedCapabilities(string deviceId)
  1014. {
  1015. var path = GetCapabilitiesFilePath(deviceId);
  1016. try
  1017. {
  1018. return _jsonSerializer.DeserializeFromFile<SessionCapabilities>(path);
  1019. }
  1020. catch (DirectoryNotFoundException)
  1021. {
  1022. return null;
  1023. }
  1024. catch (FileNotFoundException)
  1025. {
  1026. return null;
  1027. }
  1028. catch (Exception ex)
  1029. {
  1030. _logger.ErrorException("Error getting saved capabilities", ex);
  1031. return null;
  1032. }
  1033. }
  1034. private readonly SemaphoreSlim _capabilitiesLock = new SemaphoreSlim(1, 1);
  1035. private async Task SaveCapabilities(string deviceId, SessionCapabilities capabilities)
  1036. {
  1037. var path = GetCapabilitiesFilePath(deviceId);
  1038. Directory.CreateDirectory(Path.GetDirectoryName(path));
  1039. await _capabilitiesLock.WaitAsync().ConfigureAwait(false);
  1040. try
  1041. {
  1042. _jsonSerializer.SerializeToFile(capabilities, path);
  1043. }
  1044. finally
  1045. {
  1046. _capabilitiesLock.Release();
  1047. }
  1048. }
  1049. public SessionInfoDto GetSessionInfoDto(SessionInfo session)
  1050. {
  1051. var dto = new SessionInfoDto
  1052. {
  1053. Client = session.Client,
  1054. DeviceId = session.DeviceId,
  1055. DeviceName = session.DeviceName,
  1056. Id = session.Id,
  1057. LastActivityDate = session.LastActivityDate,
  1058. NowPlayingPositionTicks = session.PlayState.PositionTicks,
  1059. IsPaused = session.PlayState.IsPaused,
  1060. IsMuted = session.PlayState.IsMuted,
  1061. NowViewingItem = session.NowViewingItem,
  1062. ApplicationVersion = session.ApplicationVersion,
  1063. CanSeek = session.PlayState.CanSeek,
  1064. QueueableMediaTypes = session.QueueableMediaTypes,
  1065. PlayableMediaTypes = session.PlayableMediaTypes,
  1066. RemoteEndPoint = session.RemoteEndPoint,
  1067. AdditionalUsers = session.AdditionalUsers,
  1068. SupportedCommands = session.SupportedCommands,
  1069. UserName = session.UserName,
  1070. NowPlayingItem = session.NowPlayingItem,
  1071. SupportsRemoteControl = session.SupportsMediaControl,
  1072. PlayState = session.PlayState,
  1073. TranscodingInfo = session.NowPlayingItem == null ? null : session.TranscodingInfo
  1074. };
  1075. if (session.UserId.HasValue)
  1076. {
  1077. dto.UserId = session.UserId.Value.ToString("N");
  1078. var user = _userManager.GetUserById(session.UserId.Value);
  1079. if (user != null)
  1080. {
  1081. dto.UserPrimaryImageTag = GetImageCacheTag(user, ImageType.Primary);
  1082. }
  1083. }
  1084. return dto;
  1085. }
  1086. /// <summary>
  1087. /// Converts a BaseItem to a BaseItemInfo
  1088. /// </summary>
  1089. /// <param name="item">The item.</param>
  1090. /// <param name="chapterOwner">The chapter owner.</param>
  1091. /// <param name="mediaSourceId">The media source identifier.</param>
  1092. /// <returns>BaseItemInfo.</returns>
  1093. /// <exception cref="System.ArgumentNullException">item</exception>
  1094. private BaseItemInfo GetItemInfo(BaseItem item, BaseItem chapterOwner, string mediaSourceId)
  1095. {
  1096. if (item == null)
  1097. {
  1098. throw new ArgumentNullException("item");
  1099. }
  1100. var info = new BaseItemInfo
  1101. {
  1102. Id = GetDtoId(item),
  1103. Name = item.Name,
  1104. MediaType = item.MediaType,
  1105. Type = item.GetClientTypeName(),
  1106. RunTimeTicks = item.RunTimeTicks,
  1107. IndexNumber = item.IndexNumber,
  1108. ParentIndexNumber = item.ParentIndexNumber,
  1109. PremiereDate = item.PremiereDate,
  1110. ProductionYear = item.ProductionYear
  1111. };
  1112. info.PrimaryImageTag = GetImageCacheTag(item, ImageType.Primary);
  1113. if (info.PrimaryImageTag != null)
  1114. {
  1115. info.PrimaryImageItemId = GetDtoId(item);
  1116. }
  1117. var episode = item as Episode;
  1118. if (episode != null)
  1119. {
  1120. info.IndexNumberEnd = episode.IndexNumberEnd;
  1121. }
  1122. var hasSeries = item as IHasSeries;
  1123. if (hasSeries != null)
  1124. {
  1125. info.SeriesName = hasSeries.SeriesName;
  1126. }
  1127. var recording = item as ILiveTvRecording;
  1128. if (recording != null && recording.RecordingInfo != null)
  1129. {
  1130. if (recording.RecordingInfo.IsSeries)
  1131. {
  1132. info.Name = recording.RecordingInfo.EpisodeTitle;
  1133. info.SeriesName = recording.RecordingInfo.Name;
  1134. if (string.IsNullOrWhiteSpace(info.Name))
  1135. {
  1136. info.Name = recording.RecordingInfo.Name;
  1137. }
  1138. }
  1139. }
  1140. var audio = item as Audio;
  1141. if (audio != null)
  1142. {
  1143. info.Album = audio.Album;
  1144. info.Artists = audio.Artists;
  1145. if (info.PrimaryImageTag == null)
  1146. {
  1147. var album = audio.Parents.OfType<MusicAlbum>().FirstOrDefault();
  1148. if (album != null && album.HasImage(ImageType.Primary))
  1149. {
  1150. info.PrimaryImageTag = GetImageCacheTag(album, ImageType.Primary);
  1151. if (info.PrimaryImageTag != null)
  1152. {
  1153. info.PrimaryImageItemId = GetDtoId(album);
  1154. }
  1155. }
  1156. }
  1157. }
  1158. var musicVideo = item as MusicVideo;
  1159. if (musicVideo != null)
  1160. {
  1161. info.Album = musicVideo.Album;
  1162. if (!string.IsNullOrWhiteSpace(musicVideo.Artist))
  1163. {
  1164. info.Artists.Add(musicVideo.Artist);
  1165. }
  1166. }
  1167. var backropItem = item.HasImage(ImageType.Backdrop) ? item : null;
  1168. var thumbItem = item.HasImage(ImageType.Thumb) ? item : null;
  1169. var logoItem = item.HasImage(ImageType.Logo) ? item : null;
  1170. if (thumbItem == null)
  1171. {
  1172. if (episode != null)
  1173. {
  1174. var series = episode.Series;
  1175. if (series != null && series.HasImage(ImageType.Thumb))
  1176. {
  1177. thumbItem = series;
  1178. }
  1179. }
  1180. }
  1181. if (backropItem == null)
  1182. {
  1183. if (episode != null)
  1184. {
  1185. var series = episode.Series;
  1186. if (series != null && series.HasImage(ImageType.Backdrop))
  1187. {
  1188. backropItem = series;
  1189. }
  1190. }
  1191. }
  1192. if (backropItem == null)
  1193. {
  1194. backropItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Backdrop));
  1195. }
  1196. if (thumbItem == null)
  1197. {
  1198. thumbItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Thumb));
  1199. }
  1200. if (logoItem == null)
  1201. {
  1202. logoItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Logo));
  1203. }
  1204. if (thumbItem != null)
  1205. {
  1206. info.ThumbImageTag = GetImageCacheTag(thumbItem, ImageType.Thumb);
  1207. info.ThumbItemId = GetDtoId(thumbItem);
  1208. }
  1209. if (backropItem != null)
  1210. {
  1211. info.BackdropImageTag = GetImageCacheTag(backropItem, ImageType.Backdrop);
  1212. info.BackdropItemId = GetDtoId(backropItem);
  1213. }
  1214. if (logoItem != null)
  1215. {
  1216. info.LogoImageTag = GetImageCacheTag(logoItem, ImageType.Logo);
  1217. info.LogoItemId = GetDtoId(logoItem);
  1218. }
  1219. if (chapterOwner != null)
  1220. {
  1221. info.ChapterImagesItemId = chapterOwner.Id.ToString("N");
  1222. info.Chapters = _itemRepo.GetChapters(chapterOwner.Id).Select(i => _dtoService.GetChapterInfoDto(i, chapterOwner)).ToList();
  1223. }
  1224. if (!string.IsNullOrWhiteSpace(mediaSourceId))
  1225. {
  1226. info.MediaStreams = _itemRepo.GetMediaStreams(new MediaStreamQuery
  1227. {
  1228. ItemId = new Guid(mediaSourceId)
  1229. }).ToList();
  1230. }
  1231. return info;
  1232. }
  1233. private string GetImageCacheTag(BaseItem item, ImageType type)
  1234. {
  1235. try
  1236. {
  1237. return _imageProcessor.GetImageCacheTag(item, type);
  1238. }
  1239. catch (Exception ex)
  1240. {
  1241. _logger.ErrorException("Error getting {0} image info", ex, type);
  1242. return null;
  1243. }
  1244. }
  1245. private string GetDtoId(BaseItem item)
  1246. {
  1247. return _dtoService.GetDtoId(item);
  1248. }
  1249. public void ReportNowViewingItem(string sessionId, string itemId)
  1250. {
  1251. var item = _libraryManager.GetItemById(new Guid(itemId));
  1252. var info = GetItemInfo(item, null, null);
  1253. ReportNowViewingItem(sessionId, info);
  1254. }
  1255. public void ReportNowViewingItem(string sessionId, BaseItemInfo item)
  1256. {
  1257. var session = GetSession(sessionId);
  1258. session.NowViewingItem = item;
  1259. }
  1260. public void ReportTranscodingInfo(string deviceId, TranscodingInfo info)
  1261. {
  1262. var session = Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId));
  1263. if (session != null)
  1264. {
  1265. session.TranscodingInfo = info;
  1266. }
  1267. }
  1268. public void ClearTranscodingInfo(string deviceId)
  1269. {
  1270. ReportTranscodingInfo(deviceId, null);
  1271. }
  1272. public SessionInfo GetSession(string deviceId, string client, string version)
  1273. {
  1274. return Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId) &&
  1275. string.Equals(i.Client, client));
  1276. }
  1277. }
  1278. }