SessionManager.cs 69 KB

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