SessionManager.cs 70 KB

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