SessionManager.cs 70 KB

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