SessionManager.cs 67 KB

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