SessionManager.cs 63 KB

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