SessionManager.cs 56 KB

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