SessionManager.cs 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972
  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.Dto;
  18. using MediaBrowser.Model.Entities;
  19. using MediaBrowser.Model.Events;
  20. using MediaBrowser.Model.Library;
  21. using MediaBrowser.Model.Logging;
  22. using MediaBrowser.Model.Serialization;
  23. using MediaBrowser.Model.Session;
  24. using MediaBrowser.Model.Users;
  25. using System;
  26. using System.Collections.Concurrent;
  27. using System.Collections.Generic;
  28. using System.Globalization;
  29. using System.Linq;
  30. using System.Threading;
  31. using System.Threading.Tasks;
  32. using MediaBrowser.Controller.Net;
  33. using MediaBrowser.Model.Threading;
  34. namespace Emby.Server.Implementations.Session
  35. {
  36. /// <summary>
  37. /// Class SessionManager
  38. /// </summary>
  39. public class SessionManager : ISessionManager
  40. {
  41. /// <summary>
  42. /// The _user data repository
  43. /// </summary>
  44. private readonly IUserDataManager _userDataManager;
  45. /// <summary>
  46. /// The _logger
  47. /// </summary>
  48. private readonly ILogger _logger;
  49. private readonly ILibraryManager _libraryManager;
  50. private readonly IUserManager _userManager;
  51. private readonly IMusicManager _musicManager;
  52. private readonly IDtoService _dtoService;
  53. private readonly IImageProcessor _imageProcessor;
  54. private readonly IMediaSourceManager _mediaSourceManager;
  55. private readonly IHttpClient _httpClient;
  56. private readonly IJsonSerializer _jsonSerializer;
  57. private readonly IServerApplicationHost _appHost;
  58. private readonly IAuthenticationRepository _authRepo;
  59. private readonly IDeviceManager _deviceManager;
  60. private readonly ITimerFactory _timerFactory;
  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 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)
  87. {
  88. _userDataManager = userDataManager;
  89. _logger = logger;
  90. _libraryManager = libraryManager;
  91. _userManager = userManager;
  92. _musicManager = musicManager;
  93. _dtoService = dtoService;
  94. _imageProcessor = imageProcessor;
  95. _jsonSerializer = jsonSerializer;
  96. _appHost = appHost;
  97. _httpClient = httpClient;
  98. _authRepo = authRepo;
  99. _deviceManager = deviceManager;
  100. _mediaSourceManager = mediaSourceManager;
  101. _timerFactory = timerFactory;
  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. info.AppIconUrl = capabilities.IconUrl;
  142. ReportCapabilities(info, capabilities, false);
  143. }
  144. }
  145. }
  146. private async void OnSessionEnded(SessionInfo info)
  147. {
  148. try
  149. {
  150. await SendSessionEndedNotification(info, CancellationToken.None).ConfigureAwait(false);
  151. }
  152. catch (Exception ex)
  153. {
  154. _logger.ErrorException("Error in SendSessionEndedNotification", ex);
  155. }
  156. EventHelper.QueueEventIfNotNull(SessionEnded, this, new SessionEventArgs
  157. {
  158. SessionInfo = info
  159. }, _logger);
  160. var disposable = info.SessionController as IDisposable;
  161. if (disposable != null)
  162. {
  163. _logger.Debug("Disposing session controller {0}", disposable.GetType().Name);
  164. try
  165. {
  166. disposable.Dispose();
  167. }
  168. catch (Exception ex)
  169. {
  170. _logger.ErrorException("Error disposing session controller", ex);
  171. }
  172. }
  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. await _userManager.UpdateUser(user).ConfigureAwait(false);
  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. /// <param name="session">The session.</param>
  270. /// <param name="info">The information.</param>
  271. /// <param name="libraryItem">The library item.</param>
  272. private async Task UpdateNowPlayingItem(SessionInfo session, PlaybackProgressInfo info, BaseItem libraryItem)
  273. {
  274. if (string.IsNullOrWhiteSpace(info.MediaSourceId))
  275. {
  276. info.MediaSourceId = info.ItemId;
  277. }
  278. if (!string.IsNullOrWhiteSpace(info.ItemId) && info.Item == null && libraryItem != null)
  279. {
  280. var current = session.NowPlayingItem;
  281. if (current == null || !string.Equals(current.Id, info.ItemId, StringComparison.OrdinalIgnoreCase))
  282. {
  283. var runtimeTicks = libraryItem.RunTimeTicks;
  284. MediaSourceInfo mediaSource = null;
  285. var hasMediaSources = libraryItem as IHasMediaSources;
  286. if (hasMediaSources != null)
  287. {
  288. mediaSource = await GetMediaSource(hasMediaSources, info.MediaSourceId, info.LiveStreamId).ConfigureAwait(false);
  289. if (mediaSource != null)
  290. {
  291. runtimeTicks = mediaSource.RunTimeTicks;
  292. }
  293. }
  294. info.Item = GetItemInfo(libraryItem, libraryItem, mediaSource);
  295. info.Item.RunTimeTicks = runtimeTicks;
  296. }
  297. else
  298. {
  299. info.Item = current;
  300. }
  301. }
  302. session.NowPlayingItem = info.Item;
  303. session.LastActivityDate = DateTime.UtcNow;
  304. session.LastPlaybackCheckIn = DateTime.UtcNow;
  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
  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 = await _deviceManager.RegisterDevice(deviceId, deviceName, appName, appVersion, userIdString).ConfigureAwait(false);
  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 = await _deviceManager.RegisterDevice(deviceId, deviceName, appName, appVersion, userIdString).ConfigureAwait(false);
  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.Clear();
  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).ConfigureAwait(false);
  513. if (!string.IsNullOrEmpty(session.DeviceId) && info.PlayMethod != PlayMethod.Transcode)
  514. {
  515. ClearTranscodingInfo(session.DeviceId);
  516. }
  517. session.QueueableMediaTypes = info.QueueableMediaTypes;
  518. var users = GetUsers(session);
  519. if (libraryItem != null)
  520. {
  521. foreach (var user in users)
  522. {
  523. await OnPlaybackStart(user.Id, libraryItem).ConfigureAwait(false);
  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. /// <returns>Task.</returns>
  547. private async Task OnPlaybackStart(Guid userId, IHasUserData item)
  548. {
  549. var data = _userDataManager.GetUserData(userId, item);
  550. data.PlayCount++;
  551. data.LastPlayedDate = DateTime.UtcNow;
  552. if (item.SupportsPlayedStatus)
  553. {
  554. if (!(item is Video))
  555. {
  556. data.Played = true;
  557. }
  558. }
  559. else
  560. {
  561. data.Played = false;
  562. }
  563. await _userDataManager.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackStart, CancellationToken.None).ConfigureAwait(false);
  564. }
  565. /// <summary>
  566. /// Used to report playback progress for an item
  567. /// </summary>
  568. /// <param name="info">The info.</param>
  569. /// <returns>Task.</returns>
  570. /// <exception cref="System.ArgumentNullException"></exception>
  571. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  572. public async Task OnPlaybackProgress(PlaybackProgressInfo info)
  573. {
  574. if (info == null)
  575. {
  576. throw new ArgumentNullException("info");
  577. }
  578. var session = GetSession(info.SessionId);
  579. var libraryItem = string.IsNullOrWhiteSpace(info.ItemId)
  580. ? null
  581. : GetNowPlayingItem(session, info.ItemId);
  582. await UpdateNowPlayingItem(session, info, libraryItem).ConfigureAwait(false);
  583. var users = GetUsers(session);
  584. if (libraryItem != null)
  585. {
  586. foreach (var user in users)
  587. {
  588. await OnPlaybackProgress(user, libraryItem, info).ConfigureAwait(false);
  589. }
  590. }
  591. if (!string.IsNullOrWhiteSpace(info.LiveStreamId))
  592. {
  593. try
  594. {
  595. await _mediaSourceManager.PingLiveStream(info.LiveStreamId, CancellationToken.None).ConfigureAwait(false);
  596. }
  597. catch (Exception ex)
  598. {
  599. _logger.ErrorException("Error closing live stream", ex);
  600. }
  601. }
  602. EventHelper.FireEventIfNotNull(PlaybackProgress, this, new PlaybackProgressEventArgs
  603. {
  604. Item = libraryItem,
  605. Users = users,
  606. PlaybackPositionTicks = session.PlayState.PositionTicks,
  607. MediaSourceId = session.PlayState.MediaSourceId,
  608. MediaInfo = info.Item,
  609. DeviceName = session.DeviceName,
  610. ClientName = session.Client,
  611. DeviceId = session.DeviceId,
  612. IsPaused = info.IsPaused,
  613. PlaySessionId = info.PlaySessionId
  614. }, _logger);
  615. StartIdleCheckTimer();
  616. }
  617. private async Task OnPlaybackProgress(User user, BaseItem item, PlaybackProgressInfo info)
  618. {
  619. var data = _userDataManager.GetUserData(user.Id, item);
  620. var positionTicks = info.PositionTicks;
  621. if (positionTicks.HasValue)
  622. {
  623. _userDataManager.UpdatePlayState(item, data, positionTicks.Value);
  624. UpdatePlaybackSettings(user, info, data);
  625. await _userDataManager.SaveUserData(user.Id, item, data, UserDataSaveReason.PlaybackProgress, CancellationToken.None).ConfigureAwait(false);
  626. }
  627. }
  628. private void UpdatePlaybackSettings(User user, PlaybackProgressInfo info, UserItemData data)
  629. {
  630. if (user.Configuration.RememberAudioSelections)
  631. {
  632. data.AudioStreamIndex = info.AudioStreamIndex;
  633. }
  634. else
  635. {
  636. data.AudioStreamIndex = null;
  637. }
  638. if (user.Configuration.RememberSubtitleSelections)
  639. {
  640. data.SubtitleStreamIndex = info.SubtitleStreamIndex;
  641. }
  642. else
  643. {
  644. data.SubtitleStreamIndex = null;
  645. }
  646. }
  647. /// <summary>
  648. /// Used to report that playback has ended for an item
  649. /// </summary>
  650. /// <param name="info">The info.</param>
  651. /// <returns>Task.</returns>
  652. /// <exception cref="System.ArgumentNullException">info</exception>
  653. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  654. public async Task OnPlaybackStopped(PlaybackStopInfo info)
  655. {
  656. if (info == null)
  657. {
  658. throw new ArgumentNullException("info");
  659. }
  660. if (info.PositionTicks.HasValue && info.PositionTicks.Value < 0)
  661. {
  662. throw new ArgumentOutOfRangeException("positionTicks");
  663. }
  664. var session = GetSession(info.SessionId);
  665. var libraryItem = string.IsNullOrWhiteSpace(info.ItemId)
  666. ? null
  667. : GetNowPlayingItem(session, info.ItemId);
  668. // Normalize
  669. if (string.IsNullOrWhiteSpace(info.MediaSourceId))
  670. {
  671. info.MediaSourceId = info.ItemId;
  672. }
  673. if (!string.IsNullOrWhiteSpace(info.ItemId) && info.Item == null && libraryItem != null)
  674. {
  675. var current = session.NowPlayingItem;
  676. if (current == null || !string.Equals(current.Id, info.ItemId, StringComparison.OrdinalIgnoreCase))
  677. {
  678. MediaSourceInfo mediaSource = null;
  679. var hasMediaSources = libraryItem as IHasMediaSources;
  680. if (hasMediaSources != null)
  681. {
  682. mediaSource = await GetMediaSource(hasMediaSources, info.MediaSourceId, info.LiveStreamId).ConfigureAwait(false);
  683. }
  684. info.Item = GetItemInfo(libraryItem, libraryItem, mediaSource);
  685. }
  686. else
  687. {
  688. info.Item = current;
  689. }
  690. }
  691. if (info.Item != null)
  692. {
  693. var msString = info.PositionTicks.HasValue ? (info.PositionTicks.Value / 10000).ToString(CultureInfo.InvariantCulture) : "unknown";
  694. _logger.Info("Playback stopped reported by app {0} {1} playing {2}. Stopped at {3} ms",
  695. session.Client,
  696. session.ApplicationVersion,
  697. info.Item.Name,
  698. msString);
  699. }
  700. RemoveNowPlayingItem(session);
  701. var users = GetUsers(session);
  702. var playedToCompletion = false;
  703. if (libraryItem != null)
  704. {
  705. foreach (var user in users)
  706. {
  707. playedToCompletion = await OnPlaybackStopped(user.Id, libraryItem, info.PositionTicks, info.Failed).ConfigureAwait(false);
  708. }
  709. }
  710. if (!string.IsNullOrWhiteSpace(info.LiveStreamId))
  711. {
  712. try
  713. {
  714. await _mediaSourceManager.CloseLiveStream(info.LiveStreamId).ConfigureAwait(false);
  715. }
  716. catch (Exception ex)
  717. {
  718. _logger.ErrorException("Error closing live stream", ex);
  719. }
  720. }
  721. EventHelper.QueueEventIfNotNull(PlaybackStopped, this, new PlaybackStopEventArgs
  722. {
  723. Item = libraryItem,
  724. Users = users,
  725. PlaybackPositionTicks = info.PositionTicks,
  726. PlayedToCompletion = playedToCompletion,
  727. MediaSourceId = info.MediaSourceId,
  728. MediaInfo = info.Item,
  729. DeviceName = session.DeviceName,
  730. ClientName = session.Client,
  731. DeviceId = session.DeviceId
  732. }, _logger);
  733. await SendPlaybackStoppedNotification(session, CancellationToken.None).ConfigureAwait(false);
  734. }
  735. private async Task<bool> OnPlaybackStopped(Guid userId, BaseItem item, long? positionTicks, bool playbackFailed)
  736. {
  737. bool playedToCompletion = false;
  738. if (!playbackFailed)
  739. {
  740. var data = _userDataManager.GetUserData(userId, item);
  741. if (positionTicks.HasValue)
  742. {
  743. playedToCompletion = _userDataManager.UpdatePlayState(item, data, positionTicks.Value);
  744. }
  745. else
  746. {
  747. // If the client isn't able to report this, then we'll just have to make an assumption
  748. data.PlayCount++;
  749. data.Played = item.SupportsPlayedStatus;
  750. data.PlaybackPositionTicks = 0;
  751. playedToCompletion = true;
  752. }
  753. await _userDataManager.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackFinished, CancellationToken.None).ConfigureAwait(false);
  754. }
  755. return playedToCompletion;
  756. }
  757. /// <summary>
  758. /// Gets the session.
  759. /// </summary>
  760. /// <param name="sessionId">The session identifier.</param>
  761. /// <param name="throwOnMissing">if set to <c>true</c> [throw on missing].</param>
  762. /// <returns>SessionInfo.</returns>
  763. /// <exception cref="ResourceNotFoundException"></exception>
  764. private SessionInfo GetSession(string sessionId, bool throwOnMissing = true)
  765. {
  766. var session = Sessions.FirstOrDefault(i => string.Equals(i.Id, sessionId));
  767. if (session == null && throwOnMissing)
  768. {
  769. throw new ResourceNotFoundException(string.Format("Session {0} not found.", sessionId));
  770. }
  771. return session;
  772. }
  773. private SessionInfo GetSessionToRemoteControl(string sessionId)
  774. {
  775. // Accept either device id or session id
  776. var session = Sessions.FirstOrDefault(i => string.Equals(i.Id, sessionId));
  777. if (session == null)
  778. {
  779. throw new ResourceNotFoundException(string.Format("Session {0} not found.", sessionId));
  780. }
  781. return session;
  782. }
  783. public Task SendMessageCommand(string controllingSessionId, string sessionId, MessageCommand command, CancellationToken cancellationToken)
  784. {
  785. var generalCommand = new GeneralCommand
  786. {
  787. Name = GeneralCommandType.DisplayMessage.ToString()
  788. };
  789. generalCommand.Arguments["Header"] = command.Header;
  790. generalCommand.Arguments["Text"] = command.Text;
  791. if (command.TimeoutMs.HasValue)
  792. {
  793. generalCommand.Arguments["TimeoutMs"] = command.TimeoutMs.Value.ToString(CultureInfo.InvariantCulture);
  794. }
  795. return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
  796. }
  797. public Task SendGeneralCommand(string controllingSessionId, string sessionId, GeneralCommand command, CancellationToken cancellationToken)
  798. {
  799. var session = GetSessionToRemoteControl(sessionId);
  800. if (!string.IsNullOrWhiteSpace(controllingSessionId))
  801. {
  802. var controllingSession = GetSession(controllingSessionId);
  803. AssertCanControl(session, controllingSession);
  804. }
  805. return session.SessionController.SendGeneralCommand(command, cancellationToken);
  806. }
  807. public async Task SendPlayCommand(string controllingSessionId, string sessionId, PlayRequest command, CancellationToken cancellationToken)
  808. {
  809. var session = GetSessionToRemoteControl(sessionId);
  810. var user = session.UserId.HasValue ? _userManager.GetUserById(session.UserId.Value) : null;
  811. List<BaseItem> items;
  812. if (command.PlayCommand == PlayCommand.PlayInstantMix)
  813. {
  814. items = command.ItemIds.SelectMany(i => TranslateItemForInstantMix(i, user))
  815. .Where(i => i.LocationType != LocationType.Virtual)
  816. .ToList();
  817. command.PlayCommand = PlayCommand.PlayNow;
  818. }
  819. else
  820. {
  821. var list = new List<BaseItem>();
  822. foreach (var itemId in command.ItemIds)
  823. {
  824. var subItems = await TranslateItemForPlayback(itemId, user).ConfigureAwait(false);
  825. list.AddRange(subItems);
  826. }
  827. items = list
  828. .Where(i => i.LocationType != LocationType.Virtual)
  829. .ToList();
  830. }
  831. if (command.PlayCommand == PlayCommand.PlayShuffle)
  832. {
  833. items = items.OrderBy(i => Guid.NewGuid()).ToList();
  834. command.PlayCommand = PlayCommand.PlayNow;
  835. }
  836. command.ItemIds = items.Select(i => i.Id.ToString("N")).ToArray();
  837. if (user != null)
  838. {
  839. if (items.Any(i => i.GetPlayAccess(user) != PlayAccess.Full))
  840. {
  841. throw new ArgumentException(string.Format("{0} is not allowed to play media.", user.Name));
  842. }
  843. }
  844. if (command.PlayCommand != PlayCommand.PlayNow)
  845. {
  846. if (items.Any(i => !session.QueueableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  847. {
  848. throw new ArgumentException(string.Format("{0} is unable to queue the requested media type.", session.DeviceName ?? session.Id));
  849. }
  850. }
  851. else
  852. {
  853. if (items.Any(i => !session.PlayableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  854. {
  855. throw new ArgumentException(string.Format("{0} is unable to play the requested media type.", session.DeviceName ?? session.Id));
  856. }
  857. }
  858. if (user != null && command.ItemIds.Length == 1 && user.Configuration.EnableNextEpisodeAutoPlay)
  859. {
  860. var episode = _libraryManager.GetItemById(command.ItemIds[0]) as Episode;
  861. if (episode != null)
  862. {
  863. var series = episode.Series;
  864. if (series != null)
  865. {
  866. var episodes = series.GetEpisodes(user)
  867. .Where(i => !i.IsVirtualItem)
  868. .SkipWhile(i => i.Id != episode.Id)
  869. .ToList();
  870. if (episodes.Count > 0)
  871. {
  872. command.ItemIds = episodes.Select(i => i.Id.ToString("N")).ToArray();
  873. }
  874. }
  875. }
  876. }
  877. if (!string.IsNullOrWhiteSpace(controllingSessionId))
  878. {
  879. var controllingSession = GetSession(controllingSessionId);
  880. AssertCanControl(session, controllingSession);
  881. if (controllingSession.UserId.HasValue)
  882. {
  883. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  884. }
  885. }
  886. await session.SessionController.SendPlayCommand(command, cancellationToken).ConfigureAwait(false);
  887. }
  888. private async Task<List<BaseItem>> TranslateItemForPlayback(string id, User user)
  889. {
  890. var item = _libraryManager.GetItemById(id);
  891. if (item == null)
  892. {
  893. _logger.Error("A non-existant item Id {0} was passed into TranslateItemForPlayback", id);
  894. return new List<BaseItem>();
  895. }
  896. var byName = item as IItemByName;
  897. if (byName != null)
  898. {
  899. var items = byName.GetTaggedItems(new InternalItemsQuery(user)
  900. {
  901. IsFolder = false,
  902. Recursive = true
  903. });
  904. return FilterToSingleMediaType(items)
  905. .OrderBy(i => i.SortName)
  906. .ToList();
  907. }
  908. if (item.IsFolder)
  909. {
  910. var folder = (Folder)item;
  911. var itemsResult = await folder.GetItems(new InternalItemsQuery(user)
  912. {
  913. Recursive = true,
  914. IsFolder = false
  915. }).ConfigureAwait(false);
  916. return FilterToSingleMediaType(itemsResult.Items)
  917. .OrderBy(i => i.SortName)
  918. .ToList();
  919. }
  920. return new List<BaseItem> { item };
  921. }
  922. private IEnumerable<BaseItem> FilterToSingleMediaType(IEnumerable<BaseItem> items)
  923. {
  924. return items
  925. .Where(i => !string.IsNullOrWhiteSpace(i.MediaType))
  926. .ToLookup(i => i.MediaType, StringComparer.OrdinalIgnoreCase)
  927. .OrderByDescending(i => i.Count())
  928. .FirstOrDefault();
  929. }
  930. private IEnumerable<BaseItem> TranslateItemForInstantMix(string id, User user)
  931. {
  932. var item = _libraryManager.GetItemById(id);
  933. if (item == null)
  934. {
  935. _logger.Error("A non-existant item Id {0} was passed into TranslateItemForInstantMix", id);
  936. return new List<BaseItem>();
  937. }
  938. return _musicManager.GetInstantMixFromItem(item, user);
  939. }
  940. public Task SendBrowseCommand(string controllingSessionId, string sessionId, BrowseRequest command, CancellationToken cancellationToken)
  941. {
  942. var generalCommand = new GeneralCommand
  943. {
  944. Name = GeneralCommandType.DisplayContent.ToString()
  945. };
  946. generalCommand.Arguments["ItemId"] = command.ItemId;
  947. generalCommand.Arguments["ItemName"] = command.ItemName;
  948. generalCommand.Arguments["ItemType"] = command.ItemType;
  949. return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
  950. }
  951. public Task SendPlaystateCommand(string controllingSessionId, string sessionId, PlaystateRequest command, CancellationToken cancellationToken)
  952. {
  953. var session = GetSessionToRemoteControl(sessionId);
  954. if (!string.IsNullOrWhiteSpace(controllingSessionId))
  955. {
  956. var controllingSession = GetSession(controllingSessionId);
  957. AssertCanControl(session, controllingSession);
  958. if (controllingSession.UserId.HasValue)
  959. {
  960. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  961. }
  962. }
  963. return session.SessionController.SendPlaystateCommand(command, cancellationToken);
  964. }
  965. private void AssertCanControl(SessionInfo session, SessionInfo controllingSession)
  966. {
  967. if (session == null)
  968. {
  969. throw new ArgumentNullException("session");
  970. }
  971. if (controllingSession == null)
  972. {
  973. throw new ArgumentNullException("controllingSession");
  974. }
  975. }
  976. /// <summary>
  977. /// Sends the restart required message.
  978. /// </summary>
  979. /// <param name="cancellationToken">The cancellation token.</param>
  980. /// <returns>Task.</returns>
  981. public async Task SendRestartRequiredNotification(CancellationToken cancellationToken)
  982. {
  983. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  984. var info = await _appHost.GetSystemInfo().ConfigureAwait(false);
  985. var tasks = sessions.Select(session => Task.Run(async () =>
  986. {
  987. try
  988. {
  989. await session.SessionController.SendRestartRequiredNotification(info, cancellationToken).ConfigureAwait(false);
  990. }
  991. catch (Exception ex)
  992. {
  993. _logger.ErrorException("Error in SendRestartRequiredNotification.", ex);
  994. }
  995. }, cancellationToken));
  996. await Task.WhenAll(tasks).ConfigureAwait(false);
  997. }
  998. /// <summary>
  999. /// Sends the server shutdown notification.
  1000. /// </summary>
  1001. /// <param name="cancellationToken">The cancellation token.</param>
  1002. /// <returns>Task.</returns>
  1003. public Task SendServerShutdownNotification(CancellationToken cancellationToken)
  1004. {
  1005. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  1006. var tasks = sessions.Select(session => Task.Run(async () =>
  1007. {
  1008. try
  1009. {
  1010. await session.SessionController.SendServerShutdownNotification(cancellationToken).ConfigureAwait(false);
  1011. }
  1012. catch (Exception ex)
  1013. {
  1014. _logger.ErrorException("Error in SendServerShutdownNotification.", ex);
  1015. }
  1016. }, cancellationToken));
  1017. return Task.WhenAll(tasks);
  1018. }
  1019. /// <summary>
  1020. /// Sends the server restart notification.
  1021. /// </summary>
  1022. /// <param name="cancellationToken">The cancellation token.</param>
  1023. /// <returns>Task.</returns>
  1024. public Task SendServerRestartNotification(CancellationToken cancellationToken)
  1025. {
  1026. _logger.Debug("Beginning SendServerRestartNotification");
  1027. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  1028. var tasks = sessions.Select(session => Task.Run(async () =>
  1029. {
  1030. try
  1031. {
  1032. await session.SessionController.SendServerRestartNotification(cancellationToken).ConfigureAwait(false);
  1033. }
  1034. catch (Exception ex)
  1035. {
  1036. _logger.ErrorException("Error in SendServerRestartNotification.", ex);
  1037. }
  1038. }, cancellationToken));
  1039. return Task.WhenAll(tasks);
  1040. }
  1041. public Task SendSessionEndedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  1042. {
  1043. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  1044. var dto = GetSessionInfoDto(sessionInfo);
  1045. var tasks = sessions.Select(session => Task.Run(async () =>
  1046. {
  1047. try
  1048. {
  1049. await session.SessionController.SendSessionEndedNotification(dto, cancellationToken).ConfigureAwait(false);
  1050. }
  1051. catch (Exception ex)
  1052. {
  1053. _logger.ErrorException("Error in SendSessionEndedNotification.", ex);
  1054. }
  1055. }, cancellationToken));
  1056. return Task.WhenAll(tasks);
  1057. }
  1058. public Task SendPlaybackStartNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  1059. {
  1060. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  1061. var dto = GetSessionInfoDto(sessionInfo);
  1062. var tasks = sessions.Select(session => Task.Run(async () =>
  1063. {
  1064. try
  1065. {
  1066. await session.SessionController.SendPlaybackStartNotification(dto, cancellationToken).ConfigureAwait(false);
  1067. }
  1068. catch (Exception ex)
  1069. {
  1070. _logger.ErrorException("Error in SendPlaybackStartNotification.", ex);
  1071. }
  1072. }, cancellationToken));
  1073. return Task.WhenAll(tasks);
  1074. }
  1075. public Task SendPlaybackStoppedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  1076. {
  1077. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  1078. var dto = GetSessionInfoDto(sessionInfo);
  1079. var tasks = sessions.Select(session => Task.Run(async () =>
  1080. {
  1081. try
  1082. {
  1083. await session.SessionController.SendPlaybackStoppedNotification(dto, cancellationToken).ConfigureAwait(false);
  1084. }
  1085. catch (Exception ex)
  1086. {
  1087. _logger.ErrorException("Error in SendPlaybackStoppedNotification.", ex);
  1088. }
  1089. }, cancellationToken));
  1090. return Task.WhenAll(tasks);
  1091. }
  1092. /// <summary>
  1093. /// Adds the additional user.
  1094. /// </summary>
  1095. /// <param name="sessionId">The session identifier.</param>
  1096. /// <param name="userId">The user identifier.</param>
  1097. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  1098. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  1099. public void AddAdditionalUser(string sessionId, string userId)
  1100. {
  1101. var session = GetSession(sessionId);
  1102. if (session.UserId.HasValue && session.UserId.Value == new Guid(userId))
  1103. {
  1104. throw new ArgumentException("The requested user is already the primary user of the session.");
  1105. }
  1106. if (session.AdditionalUsers.All(i => new Guid(i.UserId) != new Guid(userId)))
  1107. {
  1108. var user = _userManager.GetUserById(userId);
  1109. session.AdditionalUsers.Add(new SessionUserInfo
  1110. {
  1111. UserId = userId,
  1112. UserName = user.Name
  1113. });
  1114. }
  1115. }
  1116. /// <summary>
  1117. /// Removes the additional user.
  1118. /// </summary>
  1119. /// <param name="sessionId">The session identifier.</param>
  1120. /// <param name="userId">The user identifier.</param>
  1121. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  1122. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  1123. public void RemoveAdditionalUser(string sessionId, string userId)
  1124. {
  1125. var session = GetSession(sessionId);
  1126. if (session.UserId.HasValue && session.UserId.Value == new Guid(userId))
  1127. {
  1128. throw new ArgumentException("The requested user is already the primary user of the session.");
  1129. }
  1130. var user = session.AdditionalUsers.FirstOrDefault(i => new Guid(i.UserId) == new Guid(userId));
  1131. if (user != null)
  1132. {
  1133. session.AdditionalUsers.Remove(user);
  1134. }
  1135. }
  1136. /// <summary>
  1137. /// Authenticates the new session.
  1138. /// </summary>
  1139. /// <param name="request">The request.</param>
  1140. /// <returns>Task{SessionInfo}.</returns>
  1141. public Task<AuthenticationResult> AuthenticateNewSession(AuthenticationRequest request)
  1142. {
  1143. return AuthenticateNewSessionInternal(request, true);
  1144. }
  1145. public Task<AuthenticationResult> CreateNewSession(AuthenticationRequest request)
  1146. {
  1147. return AuthenticateNewSessionInternal(request, false);
  1148. }
  1149. private async Task<AuthenticationResult> AuthenticateNewSessionInternal(AuthenticationRequest request, bool enforcePassword)
  1150. {
  1151. User user = null;
  1152. if (!string.IsNullOrWhiteSpace(request.UserId))
  1153. {
  1154. var idGuid = new Guid(request.UserId);
  1155. user = _userManager.Users
  1156. .FirstOrDefault(i => i.Id == idGuid);
  1157. }
  1158. if (user == null)
  1159. {
  1160. user = _userManager.Users
  1161. .FirstOrDefault(i => string.Equals(request.Username, i.Name, StringComparison.OrdinalIgnoreCase));
  1162. }
  1163. if (user != null && !string.IsNullOrWhiteSpace(request.DeviceId))
  1164. {
  1165. if (!_deviceManager.CanAccessDevice(user.Id.ToString("N"), request.DeviceId))
  1166. {
  1167. throw new SecurityException("User is not allowed access from this device.");
  1168. }
  1169. }
  1170. if (enforcePassword)
  1171. {
  1172. var result = await _userManager.AuthenticateUser(request.Username, request.PasswordSha1, request.PasswordMd5, request.RemoteEndPoint).ConfigureAwait(false);
  1173. if (result == null)
  1174. {
  1175. EventHelper.FireEventIfNotNull(AuthenticationFailed, this, new GenericEventArgs<AuthenticationRequest>(request), _logger);
  1176. throw new SecurityException("Invalid user or password entered.");
  1177. }
  1178. user = result;
  1179. }
  1180. var token = await GetAuthorizationToken(user.Id.ToString("N"), request.DeviceId, request.App, request.AppVersion, request.DeviceName).ConfigureAwait(false);
  1181. EventHelper.FireEventIfNotNull(AuthenticationSucceeded, this, new GenericEventArgs<AuthenticationRequest>(request), _logger);
  1182. var session = await LogSessionActivity(request.App,
  1183. request.AppVersion,
  1184. request.DeviceId,
  1185. request.DeviceName,
  1186. request.RemoteEndPoint,
  1187. user)
  1188. .ConfigureAwait(false);
  1189. return new AuthenticationResult
  1190. {
  1191. User = _userManager.GetUserDto(user, request.RemoteEndPoint),
  1192. SessionInfo = GetSessionInfoDto(session),
  1193. AccessToken = token,
  1194. ServerId = _appHost.SystemId
  1195. };
  1196. }
  1197. private async Task<string> GetAuthorizationToken(string userId, string deviceId, string app, string appVersion, string deviceName)
  1198. {
  1199. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1200. {
  1201. DeviceId = deviceId,
  1202. IsActive = true,
  1203. UserId = userId,
  1204. Limit = 1
  1205. });
  1206. if (existing.Items.Length > 0)
  1207. {
  1208. var token = existing.Items[0].AccessToken;
  1209. _logger.Info("Reissuing access token: " + token);
  1210. return token;
  1211. }
  1212. var newToken = new AuthenticationInfo
  1213. {
  1214. AppName = app,
  1215. AppVersion = appVersion,
  1216. DateCreated = DateTime.UtcNow,
  1217. DeviceId = deviceId,
  1218. DeviceName = deviceName,
  1219. UserId = userId,
  1220. IsActive = true,
  1221. AccessToken = Guid.NewGuid().ToString("N")
  1222. };
  1223. _logger.Info("Creating new access token for user {0}", userId);
  1224. await _authRepo.Create(newToken, CancellationToken.None).ConfigureAwait(false);
  1225. return newToken.AccessToken;
  1226. }
  1227. public async Task Logout(string accessToken)
  1228. {
  1229. if (string.IsNullOrWhiteSpace(accessToken))
  1230. {
  1231. throw new ArgumentNullException("accessToken");
  1232. }
  1233. _logger.Info("Logging out access token {0}", accessToken);
  1234. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1235. {
  1236. Limit = 1,
  1237. AccessToken = accessToken
  1238. }).Items.FirstOrDefault();
  1239. if (existing != null)
  1240. {
  1241. existing.IsActive = false;
  1242. await _authRepo.Update(existing, CancellationToken.None).ConfigureAwait(false);
  1243. var sessions = Sessions
  1244. .Where(i => string.Equals(i.DeviceId, existing.DeviceId, StringComparison.OrdinalIgnoreCase))
  1245. .ToList();
  1246. foreach (var session in sessions)
  1247. {
  1248. try
  1249. {
  1250. ReportSessionEnded(session.Id);
  1251. }
  1252. catch (Exception ex)
  1253. {
  1254. _logger.ErrorException("Error reporting session ended", ex);
  1255. }
  1256. }
  1257. }
  1258. }
  1259. public async Task RevokeUserTokens(string userId, string currentAccessToken)
  1260. {
  1261. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1262. {
  1263. IsActive = true,
  1264. UserId = userId
  1265. });
  1266. foreach (var info in existing.Items)
  1267. {
  1268. if (!string.Equals(currentAccessToken, info.AccessToken, StringComparison.OrdinalIgnoreCase))
  1269. {
  1270. await Logout(info.AccessToken).ConfigureAwait(false);
  1271. }
  1272. }
  1273. }
  1274. public Task RevokeToken(string token)
  1275. {
  1276. return Logout(token);
  1277. }
  1278. /// <summary>
  1279. /// Reports the capabilities.
  1280. /// </summary>
  1281. /// <param name="sessionId">The session identifier.</param>
  1282. /// <param name="capabilities">The capabilities.</param>
  1283. public void ReportCapabilities(string sessionId, ClientCapabilities capabilities)
  1284. {
  1285. var session = GetSession(sessionId);
  1286. ReportCapabilities(session, capabilities, true);
  1287. }
  1288. private async void ReportCapabilities(SessionInfo session,
  1289. ClientCapabilities capabilities,
  1290. bool saveCapabilities)
  1291. {
  1292. session.Capabilities = capabilities;
  1293. if (!string.IsNullOrWhiteSpace(capabilities.MessageCallbackUrl))
  1294. {
  1295. var controller = session.SessionController as HttpSessionController;
  1296. if (controller == null)
  1297. {
  1298. session.SessionController = new HttpSessionController(_httpClient, _jsonSerializer, session, capabilities.MessageCallbackUrl, this);
  1299. }
  1300. }
  1301. EventHelper.FireEventIfNotNull(CapabilitiesChanged, this, new SessionEventArgs
  1302. {
  1303. SessionInfo = session
  1304. }, _logger);
  1305. if (saveCapabilities)
  1306. {
  1307. try
  1308. {
  1309. await SaveCapabilities(session.DeviceId, capabilities).ConfigureAwait(false);
  1310. }
  1311. catch (Exception ex)
  1312. {
  1313. _logger.ErrorException("Error saving device capabilities", ex);
  1314. }
  1315. }
  1316. }
  1317. private ClientCapabilities GetSavedCapabilities(string deviceId)
  1318. {
  1319. return _deviceManager.GetCapabilities(deviceId);
  1320. }
  1321. private Task SaveCapabilities(string deviceId, ClientCapabilities capabilities)
  1322. {
  1323. return _deviceManager.SaveCapabilities(deviceId, capabilities);
  1324. }
  1325. public SessionInfoDto GetSessionInfoDto(SessionInfo session)
  1326. {
  1327. var dto = new SessionInfoDto
  1328. {
  1329. Client = session.Client,
  1330. DeviceId = session.DeviceId,
  1331. DeviceName = session.DeviceName,
  1332. Id = session.Id,
  1333. LastActivityDate = session.LastActivityDate,
  1334. NowViewingItem = session.NowViewingItem,
  1335. ApplicationVersion = session.ApplicationVersion,
  1336. QueueableMediaTypes = session.QueueableMediaTypes,
  1337. PlayableMediaTypes = session.PlayableMediaTypes,
  1338. AdditionalUsers = session.AdditionalUsers,
  1339. SupportedCommands = session.SupportedCommands,
  1340. UserName = session.UserName,
  1341. NowPlayingItem = session.NowPlayingItem,
  1342. SupportsRemoteControl = session.SupportsMediaControl,
  1343. PlayState = session.PlayState,
  1344. AppIconUrl = session.AppIconUrl,
  1345. TranscodingInfo = session.NowPlayingItem == null ? null : session.TranscodingInfo
  1346. };
  1347. if (session.UserId.HasValue)
  1348. {
  1349. dto.UserId = session.UserId.Value.ToString("N");
  1350. var user = _userManager.GetUserById(session.UserId.Value);
  1351. if (user != null)
  1352. {
  1353. dto.UserPrimaryImageTag = GetImageCacheTag(user, ImageType.Primary);
  1354. }
  1355. }
  1356. return dto;
  1357. }
  1358. /// <summary>
  1359. /// Converts a BaseItem to a BaseItemInfo
  1360. /// </summary>
  1361. /// <param name="item">The item.</param>
  1362. /// <param name="chapterOwner">The chapter owner.</param>
  1363. /// <param name="mediaSource">The media source.</param>
  1364. /// <returns>BaseItemInfo.</returns>
  1365. /// <exception cref="System.ArgumentNullException">item</exception>
  1366. private BaseItemInfo GetItemInfo(BaseItem item, BaseItem chapterOwner, MediaSourceInfo mediaSource)
  1367. {
  1368. if (item == null)
  1369. {
  1370. throw new ArgumentNullException("item");
  1371. }
  1372. var info = new BaseItemInfo
  1373. {
  1374. Id = GetDtoId(item),
  1375. Name = item.Name,
  1376. MediaType = item.MediaType,
  1377. Type = item.GetClientTypeName(),
  1378. RunTimeTicks = item.RunTimeTicks,
  1379. IndexNumber = item.IndexNumber,
  1380. ParentIndexNumber = item.ParentIndexNumber,
  1381. PremiereDate = item.PremiereDate,
  1382. ProductionYear = item.ProductionYear,
  1383. IsThemeMedia = item.IsThemeMedia
  1384. };
  1385. info.PrimaryImageTag = GetImageCacheTag(item, ImageType.Primary);
  1386. if (info.PrimaryImageTag != null)
  1387. {
  1388. info.PrimaryImageItemId = GetDtoId(item);
  1389. }
  1390. var episode = item as Episode;
  1391. if (episode != null)
  1392. {
  1393. info.IndexNumberEnd = episode.IndexNumberEnd;
  1394. }
  1395. var hasSeries = item as IHasSeries;
  1396. if (hasSeries != null)
  1397. {
  1398. info.SeriesName = hasSeries.SeriesName;
  1399. }
  1400. var recording = item as ILiveTvRecording;
  1401. if (recording != null)
  1402. {
  1403. if (recording.IsSeries)
  1404. {
  1405. info.Name = recording.EpisodeTitle;
  1406. info.SeriesName = recording.Name;
  1407. if (string.IsNullOrWhiteSpace(info.Name))
  1408. {
  1409. info.Name = recording.Name;
  1410. }
  1411. }
  1412. }
  1413. var audio = item as Audio;
  1414. if (audio != null)
  1415. {
  1416. info.Album = audio.Album;
  1417. info.Artists = audio.Artists;
  1418. if (info.PrimaryImageTag == null)
  1419. {
  1420. var album = audio.AlbumEntity;
  1421. if (album != null && album.HasImage(ImageType.Primary))
  1422. {
  1423. info.PrimaryImageTag = GetImageCacheTag(album, ImageType.Primary);
  1424. if (info.PrimaryImageTag != null)
  1425. {
  1426. info.PrimaryImageItemId = GetDtoId(album);
  1427. }
  1428. }
  1429. }
  1430. }
  1431. var musicVideo = item as MusicVideo;
  1432. if (musicVideo != null)
  1433. {
  1434. info.Album = musicVideo.Album;
  1435. info.Artists = musicVideo.Artists.ToList();
  1436. }
  1437. var backropItem = item.HasImage(ImageType.Backdrop) ? item : null;
  1438. var thumbItem = item.HasImage(ImageType.Thumb) ? item : null;
  1439. var logoItem = item.HasImage(ImageType.Logo) ? item : null;
  1440. if (thumbItem == null)
  1441. {
  1442. if (episode != null)
  1443. {
  1444. var series = episode.Series;
  1445. if (series != null && series.HasImage(ImageType.Thumb))
  1446. {
  1447. thumbItem = series;
  1448. }
  1449. }
  1450. }
  1451. if (backropItem == null)
  1452. {
  1453. if (episode != null)
  1454. {
  1455. var series = episode.Series;
  1456. if (series != null && series.HasImage(ImageType.Backdrop))
  1457. {
  1458. backropItem = series;
  1459. }
  1460. }
  1461. }
  1462. if (backropItem == null)
  1463. {
  1464. backropItem = item.GetParents().FirstOrDefault(i => i.HasImage(ImageType.Backdrop));
  1465. }
  1466. if (thumbItem == null)
  1467. {
  1468. thumbItem = item.GetParents().FirstOrDefault(i => i.HasImage(ImageType.Thumb));
  1469. }
  1470. if (logoItem == null)
  1471. {
  1472. logoItem = item.GetParents().FirstOrDefault(i => i.HasImage(ImageType.Logo));
  1473. }
  1474. if (thumbItem != null)
  1475. {
  1476. info.ThumbImageTag = GetImageCacheTag(thumbItem, ImageType.Thumb);
  1477. info.ThumbItemId = GetDtoId(thumbItem);
  1478. }
  1479. if (backropItem != null)
  1480. {
  1481. info.BackdropImageTag = GetImageCacheTag(backropItem, ImageType.Backdrop);
  1482. info.BackdropItemId = GetDtoId(backropItem);
  1483. }
  1484. if (logoItem != null)
  1485. {
  1486. info.LogoImageTag = GetImageCacheTag(logoItem, ImageType.Logo);
  1487. info.LogoItemId = GetDtoId(logoItem);
  1488. }
  1489. if (chapterOwner != null)
  1490. {
  1491. info.ChapterImagesItemId = chapterOwner.Id.ToString("N");
  1492. info.Chapters = _dtoService.GetChapterInfoDtos(chapterOwner).ToList();
  1493. }
  1494. if (mediaSource != null)
  1495. {
  1496. info.MediaStreams = mediaSource.MediaStreams;
  1497. }
  1498. return info;
  1499. }
  1500. private string GetImageCacheTag(BaseItem item, ImageType type)
  1501. {
  1502. try
  1503. {
  1504. return _imageProcessor.GetImageCacheTag(item, type);
  1505. }
  1506. catch (Exception ex)
  1507. {
  1508. _logger.ErrorException("Error getting {0} image info", ex, type);
  1509. return null;
  1510. }
  1511. }
  1512. private string GetDtoId(BaseItem item)
  1513. {
  1514. return _dtoService.GetDtoId(item);
  1515. }
  1516. public void ReportNowViewingItem(string sessionId, string itemId)
  1517. {
  1518. if (string.IsNullOrWhiteSpace(itemId))
  1519. {
  1520. throw new ArgumentNullException("itemId");
  1521. }
  1522. //var item = _libraryManager.GetItemById(new Guid(itemId));
  1523. //var info = GetItemInfo(item, null, null);
  1524. //ReportNowViewingItem(sessionId, info);
  1525. }
  1526. public void ReportNowViewingItem(string sessionId, BaseItemInfo item)
  1527. {
  1528. //var session = GetSession(sessionId);
  1529. //session.NowViewingItem = item;
  1530. }
  1531. public void ReportTranscodingInfo(string deviceId, TranscodingInfo info)
  1532. {
  1533. var session = Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId));
  1534. if (session != null)
  1535. {
  1536. session.TranscodingInfo = info;
  1537. }
  1538. }
  1539. public void ClearTranscodingInfo(string deviceId)
  1540. {
  1541. ReportTranscodingInfo(deviceId, null);
  1542. }
  1543. public SessionInfo GetSession(string deviceId, string client, string version)
  1544. {
  1545. return Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId) &&
  1546. string.Equals(i.Client, client));
  1547. }
  1548. public Task<SessionInfo> GetSessionByAuthenticationToken(AuthenticationInfo info, string deviceId, string remoteEndpoint, string appVersion)
  1549. {
  1550. if (info == null)
  1551. {
  1552. throw new ArgumentNullException("info");
  1553. }
  1554. var user = string.IsNullOrWhiteSpace(info.UserId)
  1555. ? null
  1556. : _userManager.GetUserById(info.UserId);
  1557. appVersion = string.IsNullOrWhiteSpace(appVersion)
  1558. ? info.AppVersion
  1559. : appVersion;
  1560. var deviceName = info.DeviceName;
  1561. var appName = info.AppName;
  1562. if (!string.IsNullOrWhiteSpace(deviceId))
  1563. {
  1564. // Replace the info from the token with more recent info
  1565. var device = _deviceManager.GetDevice(deviceId);
  1566. if (device != null)
  1567. {
  1568. deviceName = device.Name;
  1569. appName = device.AppName;
  1570. if (!string.IsNullOrWhiteSpace(device.AppVersion))
  1571. {
  1572. appVersion = device.AppVersion;
  1573. }
  1574. }
  1575. }
  1576. else
  1577. {
  1578. deviceId = info.DeviceId;
  1579. }
  1580. // Prevent argument exception
  1581. if (string.IsNullOrWhiteSpace(appVersion))
  1582. {
  1583. appVersion = "1";
  1584. }
  1585. return LogSessionActivity(appName, appVersion, deviceId, deviceName, remoteEndpoint, user);
  1586. }
  1587. public Task<SessionInfo> GetSessionByAuthenticationToken(string token, string deviceId, string remoteEndpoint)
  1588. {
  1589. var result = _authRepo.Get(new AuthenticationInfoQuery
  1590. {
  1591. AccessToken = token
  1592. });
  1593. var info = result.Items.FirstOrDefault();
  1594. if (info == null)
  1595. {
  1596. return Task.FromResult<SessionInfo>(null);
  1597. }
  1598. return GetSessionByAuthenticationToken(info, deviceId, remoteEndpoint, null);
  1599. }
  1600. public Task SendMessageToAdminSessions<T>(string name, T data, CancellationToken cancellationToken)
  1601. {
  1602. var adminUserIds = _userManager.Users.Where(i => i.Policy.IsAdministrator).Select(i => i.Id.ToString("N")).ToList();
  1603. return SendMessageToUserSessions(adminUserIds, name, data, cancellationToken);
  1604. }
  1605. public Task SendMessageToUserSessions<T>(List<string> userIds, string name, T data,
  1606. CancellationToken cancellationToken)
  1607. {
  1608. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null && userIds.Any(i.ContainsUser)).ToList();
  1609. var tasks = sessions.Select(session => Task.Run(async () =>
  1610. {
  1611. try
  1612. {
  1613. await session.SessionController.SendMessage(name, data, cancellationToken).ConfigureAwait(false);
  1614. }
  1615. catch (Exception ex)
  1616. {
  1617. _logger.ErrorException("Error sending message", ex);
  1618. }
  1619. }, cancellationToken));
  1620. return Task.WhenAll(tasks);
  1621. }
  1622. public Task SendMessageToUserDeviceSessions<T>(string deviceId, string name, T data,
  1623. CancellationToken cancellationToken)
  1624. {
  1625. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null && string.Equals(i.DeviceId, deviceId, StringComparison.OrdinalIgnoreCase)).ToList();
  1626. var tasks = sessions.Select(session => Task.Run(async () =>
  1627. {
  1628. try
  1629. {
  1630. await session.SessionController.SendMessage(name, data, cancellationToken).ConfigureAwait(false);
  1631. }
  1632. catch (Exception ex)
  1633. {
  1634. _logger.ErrorException("Error sending message", ex);
  1635. }
  1636. }, cancellationToken));
  1637. return Task.WhenAll(tasks);
  1638. }
  1639. }
  1640. }