SessionManager.cs 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578
  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. if (!string.IsNullOrWhiteSpace(info.ItemId) && libraryItem != null)
  516. {
  517. var current = session.NowPlayingItem;
  518. if (current == null || !string.Equals(current.Id, info.ItemId, StringComparison.OrdinalIgnoreCase))
  519. {
  520. info.Item = GetItemInfo(libraryItem, libraryItem, info.MediaSourceId);
  521. }
  522. else
  523. {
  524. info.Item = current;
  525. }
  526. }
  527. RemoveNowPlayingItem(session);
  528. var users = GetUsers(session);
  529. var playedToCompletion = false;
  530. if (libraryItem != null)
  531. {
  532. var key = libraryItem.GetUserDataKey();
  533. foreach (var user in users)
  534. {
  535. playedToCompletion = await OnPlaybackStopped(user.Id, key, libraryItem, info.PositionTicks).ConfigureAwait(false);
  536. }
  537. }
  538. EventHelper.QueueEventIfNotNull(PlaybackStopped, this, new PlaybackStopEventArgs
  539. {
  540. Item = libraryItem,
  541. Users = users,
  542. PlaybackPositionTicks = info.PositionTicks,
  543. PlayedToCompletion = playedToCompletion,
  544. MediaSourceId = info.MediaSourceId,
  545. MediaInfo = info.Item,
  546. DeviceName = session.DeviceName,
  547. ClientName = session.Client,
  548. DeviceId = session.DeviceId
  549. }, _logger);
  550. await SendPlaybackStoppedNotification(session, CancellationToken.None).ConfigureAwait(false);
  551. }
  552. private async Task<bool> OnPlaybackStopped(Guid userId, string userDataKey, BaseItem item, long? positionTicks)
  553. {
  554. var data = _userDataRepository.GetUserData(userId, userDataKey);
  555. bool playedToCompletion;
  556. if (positionTicks.HasValue)
  557. {
  558. playedToCompletion = UpdatePlayState(item, data, positionTicks.Value);
  559. }
  560. else
  561. {
  562. // If the client isn't able to report this, then we'll just have to make an assumption
  563. data.PlayCount++;
  564. data.Played = true;
  565. data.PlaybackPositionTicks = 0;
  566. playedToCompletion = true;
  567. }
  568. await _userDataRepository.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackFinished, CancellationToken.None).ConfigureAwait(false);
  569. return playedToCompletion;
  570. }
  571. /// <summary>
  572. /// Updates playstate position for an item but does not save
  573. /// </summary>
  574. /// <param name="item">The item</param>
  575. /// <param name="data">User data for the item</param>
  576. /// <param name="positionTicks">The current playback position</param>
  577. private bool UpdatePlayState(BaseItem item, UserItemData data, long positionTicks)
  578. {
  579. var playedToCompletion = false;
  580. var hasRuntime = item.RunTimeTicks.HasValue && item.RunTimeTicks > 0;
  581. // If a position has been reported, and if we know the duration
  582. if (positionTicks > 0 && hasRuntime)
  583. {
  584. var pctIn = Decimal.Divide(positionTicks, item.RunTimeTicks.Value) * 100;
  585. // Don't track in very beginning
  586. if (pctIn < _configurationManager.Configuration.MinResumePct)
  587. {
  588. positionTicks = 0;
  589. }
  590. // If we're at the end, assume completed
  591. else if (pctIn > _configurationManager.Configuration.MaxResumePct || positionTicks >= item.RunTimeTicks.Value)
  592. {
  593. positionTicks = 0;
  594. data.Played = playedToCompletion = true;
  595. }
  596. else
  597. {
  598. // Enforce MinResumeDuration
  599. var durationSeconds = TimeSpan.FromTicks(item.RunTimeTicks.Value).TotalSeconds;
  600. if (durationSeconds < _configurationManager.Configuration.MinResumeDurationSeconds)
  601. {
  602. positionTicks = 0;
  603. data.Played = playedToCompletion = true;
  604. }
  605. }
  606. }
  607. else if (!hasRuntime)
  608. {
  609. // If we don't know the runtime we'll just have to assume it was fully played
  610. data.Played = playedToCompletion = true;
  611. positionTicks = 0;
  612. }
  613. if (item is Audio)
  614. {
  615. positionTicks = 0;
  616. }
  617. data.PlaybackPositionTicks = positionTicks;
  618. return playedToCompletion;
  619. }
  620. /// <summary>
  621. /// Gets the session.
  622. /// </summary>
  623. /// <param name="sessionId">The session identifier.</param>
  624. /// <param name="throwOnMissing">if set to <c>true</c> [throw on missing].</param>
  625. /// <returns>SessionInfo.</returns>
  626. /// <exception cref="ResourceNotFoundException"></exception>
  627. private SessionInfo GetSession(string sessionId, bool throwOnMissing = true)
  628. {
  629. var session = Sessions.FirstOrDefault(i => string.Equals(i.Id, sessionId));
  630. if (session == null && throwOnMissing)
  631. {
  632. throw new ResourceNotFoundException(string.Format("Session {0} not found.", sessionId));
  633. }
  634. return session;
  635. }
  636. public Task SendMessageCommand(string controllingSessionId, string sessionId, MessageCommand command, CancellationToken cancellationToken)
  637. {
  638. var generalCommand = new GeneralCommand
  639. {
  640. Name = GeneralCommandType.DisplayMessage.ToString()
  641. };
  642. generalCommand.Arguments["Header"] = command.Header;
  643. generalCommand.Arguments["Text"] = command.Text;
  644. if (command.TimeoutMs.HasValue)
  645. {
  646. generalCommand.Arguments["TimeoutMs"] = command.TimeoutMs.Value.ToString(CultureInfo.InvariantCulture);
  647. }
  648. return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
  649. }
  650. public Task SendGeneralCommand(string controllingSessionId, string sessionId, GeneralCommand command, CancellationToken cancellationToken)
  651. {
  652. var session = GetSession(sessionId);
  653. var controllingSession = GetSession(controllingSessionId);
  654. AssertCanControl(session, controllingSession);
  655. return session.SessionController.SendGeneralCommand(command, cancellationToken);
  656. }
  657. public Task SendPlayCommand(string controllingSessionId, string sessionId, PlayRequest command, CancellationToken cancellationToken)
  658. {
  659. var session = GetSession(sessionId);
  660. var user = session.UserId.HasValue ? _userManager.GetUserById(session.UserId.Value) : null;
  661. List<BaseItem> items;
  662. if (command.PlayCommand == PlayCommand.PlayInstantMix)
  663. {
  664. items = command.ItemIds.SelectMany(i => TranslateItemForInstantMix(i, user))
  665. .Where(i => i.LocationType != LocationType.Virtual)
  666. .ToList();
  667. command.PlayCommand = PlayCommand.PlayNow;
  668. }
  669. else
  670. {
  671. items = command.ItemIds.SelectMany(i => TranslateItemForPlayback(i, user))
  672. .Where(i => i.LocationType != LocationType.Virtual)
  673. .ToList();
  674. }
  675. if (command.PlayCommand == PlayCommand.PlayShuffle)
  676. {
  677. items = items.OrderBy(i => Guid.NewGuid()).ToList();
  678. command.PlayCommand = PlayCommand.PlayNow;
  679. }
  680. command.ItemIds = items.Select(i => i.Id.ToString("N")).ToArray();
  681. if (user != null)
  682. {
  683. if (items.Any(i => i.GetPlayAccess(user) != PlayAccess.Full))
  684. {
  685. throw new ArgumentException(string.Format("{0} is not allowed to play media.", user.Name));
  686. }
  687. }
  688. if (command.PlayCommand != PlayCommand.PlayNow)
  689. {
  690. if (items.Any(i => !session.QueueableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  691. {
  692. throw new ArgumentException(string.Format("{0} is unable to queue the requested media type.", session.DeviceName ?? session.Id.ToString()));
  693. }
  694. }
  695. else
  696. {
  697. if (items.Any(i => !session.PlayableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  698. {
  699. throw new ArgumentException(string.Format("{0} is unable to play the requested media type.", session.DeviceName ?? session.Id.ToString()));
  700. }
  701. }
  702. var controllingSession = GetSession(controllingSessionId);
  703. AssertCanControl(session, controllingSession);
  704. if (controllingSession.UserId.HasValue)
  705. {
  706. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  707. }
  708. return session.SessionController.SendPlayCommand(command, cancellationToken);
  709. }
  710. private IEnumerable<BaseItem> TranslateItemForPlayback(string id, User user)
  711. {
  712. var item = _libraryManager.GetItemById(new Guid(id));
  713. if (item.IsFolder)
  714. {
  715. var folder = (Folder)item;
  716. var items = user == null ? folder.RecursiveChildren :
  717. folder.GetRecursiveChildren(user);
  718. items = items.Where(i => !i.IsFolder);
  719. items = items.OrderBy(i => i.SortName);
  720. return items;
  721. }
  722. return new[] { item };
  723. }
  724. private IEnumerable<BaseItem> TranslateItemForInstantMix(string id, User user)
  725. {
  726. var item = _libraryManager.GetItemById(new Guid(id));
  727. var audio = item as Audio;
  728. if (audio != null)
  729. {
  730. return _musicManager.GetInstantMixFromSong(audio, user);
  731. }
  732. var artist = item as MusicArtist;
  733. if (artist != null)
  734. {
  735. return _musicManager.GetInstantMixFromArtist(artist.Name, user);
  736. }
  737. var album = item as MusicAlbum;
  738. if (album != null)
  739. {
  740. return _musicManager.GetInstantMixFromAlbum(album, user);
  741. }
  742. var genre = item as MusicGenre;
  743. if (genre != null)
  744. {
  745. return _musicManager.GetInstantMixFromGenres(new[] { genre.Name }, user);
  746. }
  747. return new BaseItem[] { };
  748. }
  749. public Task SendBrowseCommand(string controllingSessionId, string sessionId, BrowseRequest command, CancellationToken cancellationToken)
  750. {
  751. var generalCommand = new GeneralCommand
  752. {
  753. Name = GeneralCommandType.DisplayContent.ToString()
  754. };
  755. generalCommand.Arguments["ItemId"] = command.ItemId;
  756. generalCommand.Arguments["ItemName"] = command.ItemName;
  757. generalCommand.Arguments["ItemType"] = command.ItemType;
  758. return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
  759. }
  760. public Task SendPlaystateCommand(string controllingSessionId, string sessionId, PlaystateRequest command, CancellationToken cancellationToken)
  761. {
  762. var session = GetSession(sessionId);
  763. var controllingSession = GetSession(controllingSessionId);
  764. AssertCanControl(session, controllingSession);
  765. if (controllingSession.UserId.HasValue)
  766. {
  767. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  768. }
  769. return session.SessionController.SendPlaystateCommand(command, cancellationToken);
  770. }
  771. private void AssertCanControl(SessionInfo session, SessionInfo controllingSession)
  772. {
  773. if (session == null)
  774. {
  775. throw new ArgumentNullException("session");
  776. }
  777. if (controllingSession == null)
  778. {
  779. throw new ArgumentNullException("controllingSession");
  780. }
  781. }
  782. /// <summary>
  783. /// Sends the restart required message.
  784. /// </summary>
  785. /// <param name="cancellationToken">The cancellation token.</param>
  786. /// <returns>Task.</returns>
  787. public Task SendRestartRequiredNotification(CancellationToken cancellationToken)
  788. {
  789. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  790. var info = _appHost.GetSystemInfo();
  791. var tasks = sessions.Select(session => Task.Run(async () =>
  792. {
  793. try
  794. {
  795. await session.SessionController.SendRestartRequiredNotification(info, cancellationToken).ConfigureAwait(false);
  796. }
  797. catch (Exception ex)
  798. {
  799. _logger.ErrorException("Error in SendRestartRequiredNotification.", ex);
  800. }
  801. }, cancellationToken));
  802. return Task.WhenAll(tasks);
  803. }
  804. /// <summary>
  805. /// Sends the server shutdown notification.
  806. /// </summary>
  807. /// <param name="cancellationToken">The cancellation token.</param>
  808. /// <returns>Task.</returns>
  809. public Task SendServerShutdownNotification(CancellationToken cancellationToken)
  810. {
  811. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  812. var tasks = sessions.Select(session => Task.Run(async () =>
  813. {
  814. try
  815. {
  816. await session.SessionController.SendServerShutdownNotification(cancellationToken).ConfigureAwait(false);
  817. }
  818. catch (Exception ex)
  819. {
  820. _logger.ErrorException("Error in SendServerShutdownNotification.", ex);
  821. }
  822. }, cancellationToken));
  823. return Task.WhenAll(tasks);
  824. }
  825. /// <summary>
  826. /// Sends the server restart notification.
  827. /// </summary>
  828. /// <param name="cancellationToken">The cancellation token.</param>
  829. /// <returns>Task.</returns>
  830. public Task SendServerRestartNotification(CancellationToken cancellationToken)
  831. {
  832. _logger.Debug("Beginning SendServerRestartNotification");
  833. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  834. var tasks = sessions.Select(session => Task.Run(async () =>
  835. {
  836. try
  837. {
  838. await session.SessionController.SendServerRestartNotification(cancellationToken).ConfigureAwait(false);
  839. }
  840. catch (Exception ex)
  841. {
  842. _logger.ErrorException("Error in SendServerRestartNotification.", ex);
  843. }
  844. }, cancellationToken));
  845. return Task.WhenAll(tasks);
  846. }
  847. public Task SendSessionEndedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  848. {
  849. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  850. var dto = GetSessionInfoDto(sessionInfo);
  851. var tasks = sessions.Select(session => Task.Run(async () =>
  852. {
  853. try
  854. {
  855. await session.SessionController.SendSessionEndedNotification(dto, cancellationToken).ConfigureAwait(false);
  856. }
  857. catch (Exception ex)
  858. {
  859. _logger.ErrorException("Error in SendSessionEndedNotification.", ex);
  860. }
  861. }, cancellationToken));
  862. return Task.WhenAll(tasks);
  863. }
  864. public Task SendPlaybackStartNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  865. {
  866. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  867. var dto = GetSessionInfoDto(sessionInfo);
  868. var tasks = sessions.Select(session => Task.Run(async () =>
  869. {
  870. try
  871. {
  872. await session.SessionController.SendPlaybackStartNotification(dto, cancellationToken).ConfigureAwait(false);
  873. }
  874. catch (Exception ex)
  875. {
  876. _logger.ErrorException("Error in SendPlaybackStartNotification.", ex);
  877. }
  878. }, cancellationToken));
  879. return Task.WhenAll(tasks);
  880. }
  881. public Task SendPlaybackStoppedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  882. {
  883. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  884. var dto = GetSessionInfoDto(sessionInfo);
  885. var tasks = sessions.Select(session => Task.Run(async () =>
  886. {
  887. try
  888. {
  889. await session.SessionController.SendPlaybackStoppedNotification(dto, cancellationToken).ConfigureAwait(false);
  890. }
  891. catch (Exception ex)
  892. {
  893. _logger.ErrorException("Error in SendPlaybackStoppedNotification.", ex);
  894. }
  895. }, cancellationToken));
  896. return Task.WhenAll(tasks);
  897. }
  898. /// <summary>
  899. /// Adds the additional user.
  900. /// </summary>
  901. /// <param name="sessionId">The session identifier.</param>
  902. /// <param name="userId">The user identifier.</param>
  903. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  904. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  905. public void AddAdditionalUser(string sessionId, Guid userId)
  906. {
  907. var session = GetSession(sessionId);
  908. if (!session.UserId.HasValue)
  909. {
  910. throw new UnauthorizedAccessException("Cannot modify additional users without authenticating first.");
  911. }
  912. if (session.UserId.Value == userId)
  913. {
  914. throw new ArgumentException("The requested user is already the primary user of the session.");
  915. }
  916. if (session.AdditionalUsers.All(i => new Guid(i.UserId) != userId))
  917. {
  918. var user = _userManager.GetUserById(userId);
  919. session.AdditionalUsers.Add(new SessionUserInfo
  920. {
  921. UserId = userId.ToString("N"),
  922. UserName = user.Name
  923. });
  924. }
  925. }
  926. /// <summary>
  927. /// Removes the additional user.
  928. /// </summary>
  929. /// <param name="sessionId">The session identifier.</param>
  930. /// <param name="userId">The user identifier.</param>
  931. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  932. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  933. public void RemoveAdditionalUser(string sessionId, Guid userId)
  934. {
  935. var session = GetSession(sessionId);
  936. if (!session.UserId.HasValue)
  937. {
  938. throw new UnauthorizedAccessException("Cannot modify additional users without authenticating first.");
  939. }
  940. if (session.UserId.Value == userId)
  941. {
  942. throw new ArgumentException("The requested user is already the primary user of the session.");
  943. }
  944. var user = session.AdditionalUsers.FirstOrDefault(i => new Guid(i.UserId) == userId);
  945. if (user != null)
  946. {
  947. session.AdditionalUsers.Remove(user);
  948. }
  949. }
  950. public void ValidateSecurityToken(string token)
  951. {
  952. }
  953. /// <summary>
  954. /// Authenticates the new session.
  955. /// </summary>
  956. /// <param name="username">The username.</param>
  957. /// <param name="password">The password.</param>
  958. /// <param name="clientType">Type of the client.</param>
  959. /// <param name="appVersion">The application version.</param>
  960. /// <param name="deviceId">The device identifier.</param>
  961. /// <param name="deviceName">Name of the device.</param>
  962. /// <param name="remoteEndPoint">The remote end point.</param>
  963. /// <returns>Task{SessionInfo}.</returns>
  964. /// <exception cref="System.UnauthorizedAccessException">Invalid user or password entered.</exception>
  965. /// <exception cref="UnauthorizedAccessException"></exception>
  966. public async Task<AuthenticationResult> AuthenticateNewSession(string username, string password, string clientType, string appVersion, string deviceId, string deviceName, string remoteEndPoint)
  967. {
  968. var result = await _userManager.AuthenticateUser(username, password).ConfigureAwait(false);
  969. if (!result)
  970. {
  971. throw new UnauthorizedAccessException("Invalid user or password entered.");
  972. }
  973. var user = _userManager.Users
  974. .First(i => string.Equals(username, i.Name, StringComparison.OrdinalIgnoreCase));
  975. var session = await LogSessionActivity(clientType,
  976. appVersion,
  977. deviceId,
  978. deviceName,
  979. remoteEndPoint,
  980. user)
  981. .ConfigureAwait(false);
  982. return new AuthenticationResult
  983. {
  984. User = _dtoService.GetUserDto(user),
  985. SessionInfo = GetSessionInfoDto(session),
  986. AuthenticationToken = Guid.NewGuid().ToString("N")
  987. };
  988. }
  989. private bool IsLocal(string remoteEndpoint)
  990. {
  991. if (string.IsNullOrWhiteSpace(remoteEndpoint))
  992. {
  993. throw new ArgumentNullException("remoteEndpoint");
  994. }
  995. // Private address space:
  996. // http://en.wikipedia.org/wiki/Private_network
  997. return remoteEndpoint.IndexOf("localhost", StringComparison.OrdinalIgnoreCase) != -1 ||
  998. remoteEndpoint.StartsWith("10.", StringComparison.OrdinalIgnoreCase) ||
  999. remoteEndpoint.StartsWith("192.", StringComparison.OrdinalIgnoreCase) ||
  1000. remoteEndpoint.StartsWith("172.", StringComparison.OrdinalIgnoreCase) ||
  1001. remoteEndpoint.StartsWith("127.", StringComparison.OrdinalIgnoreCase) ||
  1002. remoteEndpoint.StartsWith("::", StringComparison.OrdinalIgnoreCase);
  1003. }
  1004. /// <summary>
  1005. /// Reports the capabilities.
  1006. /// </summary>
  1007. /// <param name="sessionId">The session identifier.</param>
  1008. /// <param name="capabilities">The capabilities.</param>
  1009. public void ReportCapabilities(string sessionId, SessionCapabilities capabilities)
  1010. {
  1011. var session = GetSession(sessionId);
  1012. ReportCapabilities(session, capabilities, true);
  1013. }
  1014. private async void ReportCapabilities(SessionInfo session,
  1015. SessionCapabilities capabilities,
  1016. bool saveCapabilities)
  1017. {
  1018. session.PlayableMediaTypes = capabilities.PlayableMediaTypes;
  1019. session.SupportedCommands = capabilities.SupportedCommands;
  1020. if (!string.IsNullOrWhiteSpace(capabilities.MessageCallbackUrl))
  1021. {
  1022. var controller = session.SessionController as HttpSessionController;
  1023. if (controller == null)
  1024. {
  1025. session.SessionController = new HttpSessionController(_httpClient, _jsonSerializer, session, capabilities.MessageCallbackUrl, this);
  1026. }
  1027. }
  1028. EventHelper.FireEventIfNotNull(CapabilitiesChanged, this, new SessionEventArgs
  1029. {
  1030. SessionInfo = session
  1031. }, _logger);
  1032. if (saveCapabilities)
  1033. {
  1034. await SaveCapabilities(session.DeviceId, capabilities).ConfigureAwait(false);
  1035. }
  1036. }
  1037. private string GetCapabilitiesFilePath(string deviceId)
  1038. {
  1039. var filename = deviceId.GetMD5().ToString("N") + ".json";
  1040. return Path.Combine(_configurationManager.ApplicationPaths.CachePath, "devices", filename);
  1041. }
  1042. private SessionCapabilities GetSavedCapabilities(string deviceId)
  1043. {
  1044. var path = GetCapabilitiesFilePath(deviceId);
  1045. try
  1046. {
  1047. return _jsonSerializer.DeserializeFromFile<SessionCapabilities>(path);
  1048. }
  1049. catch (DirectoryNotFoundException)
  1050. {
  1051. return null;
  1052. }
  1053. catch (FileNotFoundException)
  1054. {
  1055. return null;
  1056. }
  1057. catch (Exception ex)
  1058. {
  1059. _logger.ErrorException("Error getting saved capabilities", ex);
  1060. return null;
  1061. }
  1062. }
  1063. private readonly SemaphoreSlim _capabilitiesLock = new SemaphoreSlim(1, 1);
  1064. private async Task SaveCapabilities(string deviceId, SessionCapabilities capabilities)
  1065. {
  1066. var path = GetCapabilitiesFilePath(deviceId);
  1067. Directory.CreateDirectory(Path.GetDirectoryName(path));
  1068. await _capabilitiesLock.WaitAsync().ConfigureAwait(false);
  1069. try
  1070. {
  1071. _jsonSerializer.SerializeToFile(capabilities, path);
  1072. }
  1073. finally
  1074. {
  1075. _capabilitiesLock.Release();
  1076. }
  1077. }
  1078. public SessionInfoDto GetSessionInfoDto(SessionInfo session)
  1079. {
  1080. var dto = new SessionInfoDto
  1081. {
  1082. Client = session.Client,
  1083. DeviceId = session.DeviceId,
  1084. DeviceName = session.DeviceName,
  1085. Id = session.Id,
  1086. LastActivityDate = session.LastActivityDate,
  1087. NowViewingItem = session.NowViewingItem,
  1088. ApplicationVersion = session.ApplicationVersion,
  1089. QueueableMediaTypes = session.QueueableMediaTypes,
  1090. PlayableMediaTypes = session.PlayableMediaTypes,
  1091. AdditionalUsers = session.AdditionalUsers,
  1092. SupportedCommands = session.SupportedCommands,
  1093. UserName = session.UserName,
  1094. NowPlayingItem = session.NowPlayingItem,
  1095. SupportsRemoteControl = session.SupportsMediaControl,
  1096. PlayState = session.PlayState,
  1097. TranscodingInfo = session.NowPlayingItem == null ? null : session.TranscodingInfo
  1098. };
  1099. if (session.UserId.HasValue)
  1100. {
  1101. dto.UserId = session.UserId.Value.ToString("N");
  1102. var user = _userManager.GetUserById(session.UserId.Value);
  1103. if (user != null)
  1104. {
  1105. dto.UserPrimaryImageTag = GetImageCacheTag(user, ImageType.Primary);
  1106. }
  1107. }
  1108. return dto;
  1109. }
  1110. /// <summary>
  1111. /// Converts a BaseItem to a BaseItemInfo
  1112. /// </summary>
  1113. /// <param name="item">The item.</param>
  1114. /// <param name="chapterOwner">The chapter owner.</param>
  1115. /// <param name="mediaSourceId">The media source identifier.</param>
  1116. /// <returns>BaseItemInfo.</returns>
  1117. /// <exception cref="System.ArgumentNullException">item</exception>
  1118. private BaseItemInfo GetItemInfo(BaseItem item, BaseItem chapterOwner, string mediaSourceId)
  1119. {
  1120. if (item == null)
  1121. {
  1122. throw new ArgumentNullException("item");
  1123. }
  1124. var info = new BaseItemInfo
  1125. {
  1126. Id = GetDtoId(item),
  1127. Name = item.Name,
  1128. MediaType = item.MediaType,
  1129. Type = item.GetClientTypeName(),
  1130. RunTimeTicks = item.RunTimeTicks,
  1131. IndexNumber = item.IndexNumber,
  1132. ParentIndexNumber = item.ParentIndexNumber,
  1133. PremiereDate = item.PremiereDate,
  1134. ProductionYear = item.ProductionYear
  1135. };
  1136. info.PrimaryImageTag = GetImageCacheTag(item, ImageType.Primary);
  1137. if (info.PrimaryImageTag != null)
  1138. {
  1139. info.PrimaryImageItemId = GetDtoId(item);
  1140. }
  1141. var episode = item as Episode;
  1142. if (episode != null)
  1143. {
  1144. info.IndexNumberEnd = episode.IndexNumberEnd;
  1145. }
  1146. var hasSeries = item as IHasSeries;
  1147. if (hasSeries != null)
  1148. {
  1149. info.SeriesName = hasSeries.SeriesName;
  1150. }
  1151. var recording = item as ILiveTvRecording;
  1152. if (recording != null && recording.RecordingInfo != null)
  1153. {
  1154. if (recording.RecordingInfo.IsSeries)
  1155. {
  1156. info.Name = recording.RecordingInfo.EpisodeTitle;
  1157. info.SeriesName = recording.RecordingInfo.Name;
  1158. if (string.IsNullOrWhiteSpace(info.Name))
  1159. {
  1160. info.Name = recording.RecordingInfo.Name;
  1161. }
  1162. }
  1163. }
  1164. var audio = item as Audio;
  1165. if (audio != null)
  1166. {
  1167. info.Album = audio.Album;
  1168. info.Artists = audio.Artists;
  1169. if (info.PrimaryImageTag == null)
  1170. {
  1171. var album = audio.Parents.OfType<MusicAlbum>().FirstOrDefault();
  1172. if (album != null && album.HasImage(ImageType.Primary))
  1173. {
  1174. info.PrimaryImageTag = GetImageCacheTag(album, ImageType.Primary);
  1175. if (info.PrimaryImageTag != null)
  1176. {
  1177. info.PrimaryImageItemId = GetDtoId(album);
  1178. }
  1179. }
  1180. }
  1181. }
  1182. var musicVideo = item as MusicVideo;
  1183. if (musicVideo != null)
  1184. {
  1185. info.Album = musicVideo.Album;
  1186. if (!string.IsNullOrWhiteSpace(musicVideo.Artist))
  1187. {
  1188. info.Artists.Add(musicVideo.Artist);
  1189. }
  1190. }
  1191. var backropItem = item.HasImage(ImageType.Backdrop) ? item : null;
  1192. var thumbItem = item.HasImage(ImageType.Thumb) ? item : null;
  1193. var logoItem = item.HasImage(ImageType.Logo) ? item : null;
  1194. if (thumbItem == null)
  1195. {
  1196. if (episode != null)
  1197. {
  1198. var series = episode.Series;
  1199. if (series != null && series.HasImage(ImageType.Thumb))
  1200. {
  1201. thumbItem = series;
  1202. }
  1203. }
  1204. }
  1205. if (backropItem == null)
  1206. {
  1207. if (episode != null)
  1208. {
  1209. var series = episode.Series;
  1210. if (series != null && series.HasImage(ImageType.Backdrop))
  1211. {
  1212. backropItem = series;
  1213. }
  1214. }
  1215. }
  1216. if (backropItem == null)
  1217. {
  1218. backropItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Backdrop));
  1219. }
  1220. if (thumbItem == null)
  1221. {
  1222. thumbItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Thumb));
  1223. }
  1224. if (logoItem == null)
  1225. {
  1226. logoItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Logo));
  1227. }
  1228. if (thumbItem != null)
  1229. {
  1230. info.ThumbImageTag = GetImageCacheTag(thumbItem, ImageType.Thumb);
  1231. info.ThumbItemId = GetDtoId(thumbItem);
  1232. }
  1233. if (backropItem != null)
  1234. {
  1235. info.BackdropImageTag = GetImageCacheTag(backropItem, ImageType.Backdrop);
  1236. info.BackdropItemId = GetDtoId(backropItem);
  1237. }
  1238. if (logoItem != null)
  1239. {
  1240. info.LogoImageTag = GetImageCacheTag(logoItem, ImageType.Logo);
  1241. info.LogoItemId = GetDtoId(logoItem);
  1242. }
  1243. if (chapterOwner != null)
  1244. {
  1245. info.ChapterImagesItemId = chapterOwner.Id.ToString("N");
  1246. info.Chapters = _itemRepo.GetChapters(chapterOwner.Id).Select(i => _dtoService.GetChapterInfoDto(i, chapterOwner)).ToList();
  1247. }
  1248. if (!string.IsNullOrWhiteSpace(mediaSourceId))
  1249. {
  1250. info.MediaStreams = _itemRepo.GetMediaStreams(new MediaStreamQuery
  1251. {
  1252. ItemId = new Guid(mediaSourceId)
  1253. }).ToList();
  1254. }
  1255. return info;
  1256. }
  1257. private string GetImageCacheTag(BaseItem item, ImageType type)
  1258. {
  1259. try
  1260. {
  1261. return _imageProcessor.GetImageCacheTag(item, type);
  1262. }
  1263. catch (Exception ex)
  1264. {
  1265. _logger.ErrorException("Error getting {0} image info", ex, type);
  1266. return null;
  1267. }
  1268. }
  1269. private string GetDtoId(BaseItem item)
  1270. {
  1271. return _dtoService.GetDtoId(item);
  1272. }
  1273. public void ReportNowViewingItem(string sessionId, string itemId)
  1274. {
  1275. var item = _libraryManager.GetItemById(new Guid(itemId));
  1276. var info = GetItemInfo(item, null, null);
  1277. ReportNowViewingItem(sessionId, info);
  1278. }
  1279. public void ReportNowViewingItem(string sessionId, BaseItemInfo item)
  1280. {
  1281. var session = GetSession(sessionId);
  1282. session.NowViewingItem = item;
  1283. }
  1284. public void ReportTranscodingInfo(string deviceId, TranscodingInfo info)
  1285. {
  1286. var session = Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId));
  1287. if (session != null)
  1288. {
  1289. session.TranscodingInfo = info;
  1290. }
  1291. }
  1292. public void ClearTranscodingInfo(string deviceId)
  1293. {
  1294. ReportTranscodingInfo(deviceId, null);
  1295. }
  1296. public SessionInfo GetSession(string deviceId, string client, string version)
  1297. {
  1298. return Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId) &&
  1299. string.Equals(i.Client, client));
  1300. }
  1301. }
  1302. }