SessionManager.cs 67 KB

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