SessionManager.cs 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961
  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)
  853. .Where(i => !i.IsVirtualItem)
  854. .SkipWhile(i => i.Id != episode.Id)
  855. .ToList();
  856. if (episodes.Count > 0)
  857. {
  858. command.ItemIds = episodes.Select(i => i.Id.ToString("N")).ToArray();
  859. }
  860. }
  861. }
  862. }
  863. if (!string.IsNullOrWhiteSpace(controllingSessionId))
  864. {
  865. var controllingSession = GetSession(controllingSessionId);
  866. AssertCanControl(session, controllingSession);
  867. if (controllingSession.UserId.HasValue)
  868. {
  869. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  870. }
  871. }
  872. await session.SessionController.SendPlayCommand(command, cancellationToken).ConfigureAwait(false);
  873. }
  874. private async Task<List<BaseItem>> TranslateItemForPlayback(string id, User user)
  875. {
  876. var item = _libraryManager.GetItemById(id);
  877. if (item == null)
  878. {
  879. _logger.Error("A non-existant item Id {0} was passed into TranslateItemForPlayback", id);
  880. return new List<BaseItem>();
  881. }
  882. var byName = item as IItemByName;
  883. if (byName != null)
  884. {
  885. var items = byName.GetTaggedItems(new InternalItemsQuery(user)
  886. {
  887. IsFolder = false,
  888. Recursive = true
  889. });
  890. return FilterToSingleMediaType(items)
  891. .OrderBy(i => i.SortName)
  892. .ToList();
  893. }
  894. if (item.IsFolder)
  895. {
  896. var folder = (Folder)item;
  897. var itemsResult = await folder.GetItems(new InternalItemsQuery(user)
  898. {
  899. Recursive = true,
  900. IsFolder = false
  901. }).ConfigureAwait(false);
  902. return FilterToSingleMediaType(itemsResult.Items)
  903. .OrderBy(i => i.SortName)
  904. .ToList();
  905. }
  906. return new List<BaseItem> { item };
  907. }
  908. private IEnumerable<BaseItem> FilterToSingleMediaType(IEnumerable<BaseItem> items)
  909. {
  910. return items
  911. .Where(i => !string.IsNullOrWhiteSpace(i.MediaType))
  912. .ToLookup(i => i.MediaType, StringComparer.OrdinalIgnoreCase)
  913. .OrderByDescending(i => i.Count())
  914. .FirstOrDefault();
  915. }
  916. private IEnumerable<BaseItem> TranslateItemForInstantMix(string id, User user)
  917. {
  918. var item = _libraryManager.GetItemById(id);
  919. if (item == null)
  920. {
  921. _logger.Error("A non-existant item Id {0} was passed into TranslateItemForInstantMix", id);
  922. return new List<BaseItem>();
  923. }
  924. return _musicManager.GetInstantMixFromItem(item, user);
  925. }
  926. public Task SendBrowseCommand(string controllingSessionId, string sessionId, BrowseRequest command, CancellationToken cancellationToken)
  927. {
  928. var generalCommand = new GeneralCommand
  929. {
  930. Name = GeneralCommandType.DisplayContent.ToString()
  931. };
  932. generalCommand.Arguments["ItemId"] = command.ItemId;
  933. generalCommand.Arguments["ItemName"] = command.ItemName;
  934. generalCommand.Arguments["ItemType"] = command.ItemType;
  935. return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
  936. }
  937. public Task SendPlaystateCommand(string controllingSessionId, string sessionId, PlaystateRequest command, CancellationToken cancellationToken)
  938. {
  939. var session = GetSessionToRemoteControl(sessionId);
  940. if (!string.IsNullOrWhiteSpace(controllingSessionId))
  941. {
  942. var controllingSession = GetSession(controllingSessionId);
  943. AssertCanControl(session, controllingSession);
  944. if (controllingSession.UserId.HasValue)
  945. {
  946. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  947. }
  948. }
  949. return session.SessionController.SendPlaystateCommand(command, cancellationToken);
  950. }
  951. private void AssertCanControl(SessionInfo session, SessionInfo controllingSession)
  952. {
  953. if (session == null)
  954. {
  955. throw new ArgumentNullException("session");
  956. }
  957. if (controllingSession == null)
  958. {
  959. throw new ArgumentNullException("controllingSession");
  960. }
  961. }
  962. /// <summary>
  963. /// Sends the restart required message.
  964. /// </summary>
  965. /// <param name="cancellationToken">The cancellation token.</param>
  966. /// <returns>Task.</returns>
  967. public async Task SendRestartRequiredNotification(CancellationToken cancellationToken)
  968. {
  969. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  970. var info = await _appHost.GetSystemInfo().ConfigureAwait(false);
  971. var tasks = sessions.Select(session => Task.Run(async () =>
  972. {
  973. try
  974. {
  975. await session.SessionController.SendRestartRequiredNotification(info, cancellationToken).ConfigureAwait(false);
  976. }
  977. catch (Exception ex)
  978. {
  979. _logger.ErrorException("Error in SendRestartRequiredNotification.", ex);
  980. }
  981. }, cancellationToken));
  982. await Task.WhenAll(tasks).ConfigureAwait(false);
  983. }
  984. /// <summary>
  985. /// Sends the server shutdown notification.
  986. /// </summary>
  987. /// <param name="cancellationToken">The cancellation token.</param>
  988. /// <returns>Task.</returns>
  989. public Task SendServerShutdownNotification(CancellationToken cancellationToken)
  990. {
  991. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  992. var tasks = sessions.Select(session => Task.Run(async () =>
  993. {
  994. try
  995. {
  996. await session.SessionController.SendServerShutdownNotification(cancellationToken).ConfigureAwait(false);
  997. }
  998. catch (Exception ex)
  999. {
  1000. _logger.ErrorException("Error in SendServerShutdownNotification.", ex);
  1001. }
  1002. }, cancellationToken));
  1003. return Task.WhenAll(tasks);
  1004. }
  1005. /// <summary>
  1006. /// Sends the server restart notification.
  1007. /// </summary>
  1008. /// <param name="cancellationToken">The cancellation token.</param>
  1009. /// <returns>Task.</returns>
  1010. public Task SendServerRestartNotification(CancellationToken cancellationToken)
  1011. {
  1012. _logger.Debug("Beginning SendServerRestartNotification");
  1013. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  1014. var tasks = sessions.Select(session => Task.Run(async () =>
  1015. {
  1016. try
  1017. {
  1018. await session.SessionController.SendServerRestartNotification(cancellationToken).ConfigureAwait(false);
  1019. }
  1020. catch (Exception ex)
  1021. {
  1022. _logger.ErrorException("Error in SendServerRestartNotification.", ex);
  1023. }
  1024. }, cancellationToken));
  1025. return Task.WhenAll(tasks);
  1026. }
  1027. public Task SendSessionEndedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  1028. {
  1029. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  1030. var dto = GetSessionInfoDto(sessionInfo);
  1031. var tasks = sessions.Select(session => Task.Run(async () =>
  1032. {
  1033. try
  1034. {
  1035. await session.SessionController.SendSessionEndedNotification(dto, cancellationToken).ConfigureAwait(false);
  1036. }
  1037. catch (Exception ex)
  1038. {
  1039. _logger.ErrorException("Error in SendSessionEndedNotification.", ex);
  1040. }
  1041. }, cancellationToken));
  1042. return Task.WhenAll(tasks);
  1043. }
  1044. public Task SendPlaybackStartNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  1045. {
  1046. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  1047. var dto = GetSessionInfoDto(sessionInfo);
  1048. var tasks = sessions.Select(session => Task.Run(async () =>
  1049. {
  1050. try
  1051. {
  1052. await session.SessionController.SendPlaybackStartNotification(dto, cancellationToken).ConfigureAwait(false);
  1053. }
  1054. catch (Exception ex)
  1055. {
  1056. _logger.ErrorException("Error in SendPlaybackStartNotification.", ex);
  1057. }
  1058. }, cancellationToken));
  1059. return Task.WhenAll(tasks);
  1060. }
  1061. public Task SendPlaybackStoppedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  1062. {
  1063. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  1064. var dto = GetSessionInfoDto(sessionInfo);
  1065. var tasks = sessions.Select(session => Task.Run(async () =>
  1066. {
  1067. try
  1068. {
  1069. await session.SessionController.SendPlaybackStoppedNotification(dto, cancellationToken).ConfigureAwait(false);
  1070. }
  1071. catch (Exception ex)
  1072. {
  1073. _logger.ErrorException("Error in SendPlaybackStoppedNotification.", ex);
  1074. }
  1075. }, cancellationToken));
  1076. return Task.WhenAll(tasks);
  1077. }
  1078. /// <summary>
  1079. /// Adds the additional user.
  1080. /// </summary>
  1081. /// <param name="sessionId">The session identifier.</param>
  1082. /// <param name="userId">The user identifier.</param>
  1083. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  1084. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  1085. public void AddAdditionalUser(string sessionId, string userId)
  1086. {
  1087. var session = GetSession(sessionId);
  1088. if (session.UserId.HasValue && session.UserId.Value == new Guid(userId))
  1089. {
  1090. throw new ArgumentException("The requested user is already the primary user of the session.");
  1091. }
  1092. if (session.AdditionalUsers.All(i => new Guid(i.UserId) != new Guid(userId)))
  1093. {
  1094. var user = _userManager.GetUserById(userId);
  1095. session.AdditionalUsers.Add(new SessionUserInfo
  1096. {
  1097. UserId = userId,
  1098. UserName = user.Name
  1099. });
  1100. }
  1101. }
  1102. /// <summary>
  1103. /// Removes the additional user.
  1104. /// </summary>
  1105. /// <param name="sessionId">The session identifier.</param>
  1106. /// <param name="userId">The user identifier.</param>
  1107. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  1108. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  1109. public void RemoveAdditionalUser(string sessionId, string userId)
  1110. {
  1111. var session = GetSession(sessionId);
  1112. if (session.UserId.HasValue && session.UserId.Value == new Guid(userId))
  1113. {
  1114. throw new ArgumentException("The requested user is already the primary user of the session.");
  1115. }
  1116. var user = session.AdditionalUsers.FirstOrDefault(i => new Guid(i.UserId) == new Guid(userId));
  1117. if (user != null)
  1118. {
  1119. session.AdditionalUsers.Remove(user);
  1120. }
  1121. }
  1122. /// <summary>
  1123. /// Authenticates the new session.
  1124. /// </summary>
  1125. /// <param name="request">The request.</param>
  1126. /// <returns>Task{SessionInfo}.</returns>
  1127. public Task<AuthenticationResult> AuthenticateNewSession(AuthenticationRequest request)
  1128. {
  1129. return AuthenticateNewSessionInternal(request, true);
  1130. }
  1131. public Task<AuthenticationResult> CreateNewSession(AuthenticationRequest request)
  1132. {
  1133. return AuthenticateNewSessionInternal(request, false);
  1134. }
  1135. private async Task<AuthenticationResult> AuthenticateNewSessionInternal(AuthenticationRequest request, bool enforcePassword)
  1136. {
  1137. User user = null;
  1138. if (!string.IsNullOrWhiteSpace(request.UserId))
  1139. {
  1140. var idGuid = new Guid(request.UserId);
  1141. user = _userManager.Users
  1142. .FirstOrDefault(i => i.Id == idGuid);
  1143. }
  1144. if (user == null)
  1145. {
  1146. user = _userManager.Users
  1147. .FirstOrDefault(i => string.Equals(request.Username, i.Name, StringComparison.OrdinalIgnoreCase));
  1148. }
  1149. if (user != null && !string.IsNullOrWhiteSpace(request.DeviceId))
  1150. {
  1151. if (!_deviceManager.CanAccessDevice(user.Id.ToString("N"), request.DeviceId))
  1152. {
  1153. throw new SecurityException("User is not allowed access from this device.");
  1154. }
  1155. }
  1156. if (enforcePassword)
  1157. {
  1158. var result = await _userManager.AuthenticateUser(request.Username, request.PasswordSha1, request.PasswordMd5, request.RemoteEndPoint).ConfigureAwait(false);
  1159. if (result == null)
  1160. {
  1161. EventHelper.FireEventIfNotNull(AuthenticationFailed, this, new GenericEventArgs<AuthenticationRequest>(request), _logger);
  1162. throw new SecurityException("Invalid user or password entered.");
  1163. }
  1164. user = result;
  1165. }
  1166. var token = await GetAuthorizationToken(user.Id.ToString("N"), request.DeviceId, request.App, request.AppVersion, request.DeviceName).ConfigureAwait(false);
  1167. EventHelper.FireEventIfNotNull(AuthenticationSucceeded, this, new GenericEventArgs<AuthenticationRequest>(request), _logger);
  1168. var session = await LogSessionActivity(request.App,
  1169. request.AppVersion,
  1170. request.DeviceId,
  1171. request.DeviceName,
  1172. request.RemoteEndPoint,
  1173. user)
  1174. .ConfigureAwait(false);
  1175. return new AuthenticationResult
  1176. {
  1177. User = _userManager.GetUserDto(user, request.RemoteEndPoint),
  1178. SessionInfo = GetSessionInfoDto(session),
  1179. AccessToken = token,
  1180. ServerId = _appHost.SystemId
  1181. };
  1182. }
  1183. private async Task<string> GetAuthorizationToken(string userId, string deviceId, string app, string appVersion, string deviceName)
  1184. {
  1185. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1186. {
  1187. DeviceId = deviceId,
  1188. IsActive = true,
  1189. UserId = userId,
  1190. Limit = 1
  1191. });
  1192. if (existing.Items.Length > 0)
  1193. {
  1194. var token = existing.Items[0].AccessToken;
  1195. _logger.Info("Reissuing access token: " + token);
  1196. return token;
  1197. }
  1198. var newToken = new AuthenticationInfo
  1199. {
  1200. AppName = app,
  1201. AppVersion = appVersion,
  1202. DateCreated = DateTime.UtcNow,
  1203. DeviceId = deviceId,
  1204. DeviceName = deviceName,
  1205. UserId = userId,
  1206. IsActive = true,
  1207. AccessToken = Guid.NewGuid().ToString("N")
  1208. };
  1209. _logger.Info("Creating new access token for user {0}", userId);
  1210. await _authRepo.Create(newToken, CancellationToken.None).ConfigureAwait(false);
  1211. return newToken.AccessToken;
  1212. }
  1213. public async Task Logout(string accessToken)
  1214. {
  1215. if (string.IsNullOrWhiteSpace(accessToken))
  1216. {
  1217. throw new ArgumentNullException("accessToken");
  1218. }
  1219. _logger.Info("Logging out access token {0}", accessToken);
  1220. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1221. {
  1222. Limit = 1,
  1223. AccessToken = accessToken
  1224. }).Items.FirstOrDefault();
  1225. if (existing != null)
  1226. {
  1227. existing.IsActive = false;
  1228. await _authRepo.Update(existing, CancellationToken.None).ConfigureAwait(false);
  1229. var sessions = Sessions
  1230. .Where(i => string.Equals(i.DeviceId, existing.DeviceId, StringComparison.OrdinalIgnoreCase))
  1231. .ToList();
  1232. foreach (var session in sessions)
  1233. {
  1234. try
  1235. {
  1236. ReportSessionEnded(session.Id);
  1237. }
  1238. catch (Exception ex)
  1239. {
  1240. _logger.ErrorException("Error reporting session ended", ex);
  1241. }
  1242. }
  1243. }
  1244. }
  1245. public async Task RevokeUserTokens(string userId, string currentAccessToken)
  1246. {
  1247. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1248. {
  1249. IsActive = true,
  1250. UserId = userId
  1251. });
  1252. foreach (var info in existing.Items)
  1253. {
  1254. if (!string.Equals(currentAccessToken, info.AccessToken, StringComparison.OrdinalIgnoreCase))
  1255. {
  1256. await Logout(info.AccessToken).ConfigureAwait(false);
  1257. }
  1258. }
  1259. }
  1260. public Task RevokeToken(string token)
  1261. {
  1262. return Logout(token);
  1263. }
  1264. /// <summary>
  1265. /// Reports the capabilities.
  1266. /// </summary>
  1267. /// <param name="sessionId">The session identifier.</param>
  1268. /// <param name="capabilities">The capabilities.</param>
  1269. public void ReportCapabilities(string sessionId, ClientCapabilities capabilities)
  1270. {
  1271. var session = GetSession(sessionId);
  1272. ReportCapabilities(session, capabilities, true);
  1273. }
  1274. private async void ReportCapabilities(SessionInfo session,
  1275. ClientCapabilities capabilities,
  1276. bool saveCapabilities)
  1277. {
  1278. session.Capabilities = capabilities;
  1279. if (!string.IsNullOrWhiteSpace(capabilities.MessageCallbackUrl))
  1280. {
  1281. var controller = session.SessionController as HttpSessionController;
  1282. if (controller == null)
  1283. {
  1284. session.SessionController = new HttpSessionController(_httpClient, _jsonSerializer, session, capabilities.MessageCallbackUrl, this);
  1285. }
  1286. }
  1287. EventHelper.FireEventIfNotNull(CapabilitiesChanged, this, new SessionEventArgs
  1288. {
  1289. SessionInfo = session
  1290. }, _logger);
  1291. if (saveCapabilities)
  1292. {
  1293. try
  1294. {
  1295. await SaveCapabilities(session.DeviceId, capabilities).ConfigureAwait(false);
  1296. }
  1297. catch (Exception ex)
  1298. {
  1299. _logger.ErrorException("Error saving device capabilities", ex);
  1300. }
  1301. }
  1302. }
  1303. private ClientCapabilities GetSavedCapabilities(string deviceId)
  1304. {
  1305. return _deviceManager.GetCapabilities(deviceId);
  1306. }
  1307. private Task SaveCapabilities(string deviceId, ClientCapabilities capabilities)
  1308. {
  1309. return _deviceManager.SaveCapabilities(deviceId, capabilities);
  1310. }
  1311. public SessionInfoDto GetSessionInfoDto(SessionInfo session)
  1312. {
  1313. var dto = new SessionInfoDto
  1314. {
  1315. Client = session.Client,
  1316. DeviceId = session.DeviceId,
  1317. DeviceName = session.DeviceName,
  1318. Id = session.Id,
  1319. LastActivityDate = session.LastActivityDate,
  1320. NowViewingItem = session.NowViewingItem,
  1321. ApplicationVersion = session.ApplicationVersion,
  1322. PlayableMediaTypes = session.PlayableMediaTypes,
  1323. AdditionalUsers = session.AdditionalUsers,
  1324. SupportedCommands = session.SupportedCommands,
  1325. UserName = session.UserName,
  1326. NowPlayingItem = session.NowPlayingItem,
  1327. SupportsRemoteControl = session.SupportsMediaControl,
  1328. PlayState = session.PlayState,
  1329. AppIconUrl = session.AppIconUrl,
  1330. TranscodingInfo = session.NowPlayingItem == null ? null : session.TranscodingInfo
  1331. };
  1332. if (session.UserId.HasValue)
  1333. {
  1334. dto.UserId = session.UserId.Value.ToString("N");
  1335. var user = _userManager.GetUserById(session.UserId.Value);
  1336. if (user != null)
  1337. {
  1338. dto.UserPrimaryImageTag = GetImageCacheTag(user, ImageType.Primary);
  1339. }
  1340. }
  1341. return dto;
  1342. }
  1343. /// <summary>
  1344. /// Converts a BaseItem to a BaseItemInfo
  1345. /// </summary>
  1346. /// <param name="item">The item.</param>
  1347. /// <param name="chapterOwner">The chapter owner.</param>
  1348. /// <param name="mediaSource">The media source.</param>
  1349. /// <returns>BaseItemInfo.</returns>
  1350. /// <exception cref="System.ArgumentNullException">item</exception>
  1351. private BaseItemInfo GetItemInfo(BaseItem item, BaseItem chapterOwner, MediaSourceInfo mediaSource)
  1352. {
  1353. if (item == null)
  1354. {
  1355. throw new ArgumentNullException("item");
  1356. }
  1357. var info = new BaseItemInfo
  1358. {
  1359. Id = GetDtoId(item),
  1360. Name = item.Name,
  1361. MediaType = item.MediaType,
  1362. Type = item.GetClientTypeName(),
  1363. RunTimeTicks = item.RunTimeTicks,
  1364. IndexNumber = item.IndexNumber,
  1365. ParentIndexNumber = item.ParentIndexNumber,
  1366. PremiereDate = item.PremiereDate,
  1367. ProductionYear = item.ProductionYear,
  1368. IsThemeMedia = item.IsThemeMedia
  1369. };
  1370. info.PrimaryImageTag = GetImageCacheTag(item, ImageType.Primary);
  1371. if (info.PrimaryImageTag != null)
  1372. {
  1373. info.PrimaryImageItemId = GetDtoId(item);
  1374. }
  1375. var episode = item as Episode;
  1376. if (episode != null)
  1377. {
  1378. info.IndexNumberEnd = episode.IndexNumberEnd;
  1379. }
  1380. var hasSeries = item as IHasSeries;
  1381. if (hasSeries != null)
  1382. {
  1383. info.SeriesName = hasSeries.SeriesName;
  1384. }
  1385. var recording = item as ILiveTvRecording;
  1386. if (recording != null)
  1387. {
  1388. if (recording.IsSeries)
  1389. {
  1390. info.Name = recording.EpisodeTitle;
  1391. info.SeriesName = recording.Name;
  1392. if (string.IsNullOrWhiteSpace(info.Name))
  1393. {
  1394. info.Name = recording.Name;
  1395. }
  1396. }
  1397. }
  1398. var audio = item as Audio;
  1399. if (audio != null)
  1400. {
  1401. info.Album = audio.Album;
  1402. info.Artists = audio.Artists;
  1403. if (info.PrimaryImageTag == null)
  1404. {
  1405. var album = audio.AlbumEntity;
  1406. if (album != null && album.HasImage(ImageType.Primary))
  1407. {
  1408. info.PrimaryImageTag = GetImageCacheTag(album, ImageType.Primary);
  1409. if (info.PrimaryImageTag != null)
  1410. {
  1411. info.PrimaryImageItemId = GetDtoId(album);
  1412. }
  1413. }
  1414. }
  1415. }
  1416. var musicVideo = item as MusicVideo;
  1417. if (musicVideo != null)
  1418. {
  1419. info.Album = musicVideo.Album;
  1420. info.Artists = musicVideo.Artists.ToList();
  1421. }
  1422. var backropItem = item.HasImage(ImageType.Backdrop) ? item : null;
  1423. var thumbItem = item.HasImage(ImageType.Thumb) ? item : null;
  1424. var logoItem = item.HasImage(ImageType.Logo) ? item : null;
  1425. if (thumbItem == null)
  1426. {
  1427. if (episode != null)
  1428. {
  1429. var series = episode.Series;
  1430. if (series != null && series.HasImage(ImageType.Thumb))
  1431. {
  1432. thumbItem = series;
  1433. }
  1434. }
  1435. }
  1436. if (backropItem == null)
  1437. {
  1438. if (episode != null)
  1439. {
  1440. var series = episode.Series;
  1441. if (series != null && series.HasImage(ImageType.Backdrop))
  1442. {
  1443. backropItem = series;
  1444. }
  1445. }
  1446. }
  1447. if (backropItem == null)
  1448. {
  1449. backropItem = item.GetParents().FirstOrDefault(i => i.HasImage(ImageType.Backdrop));
  1450. }
  1451. if (thumbItem == null)
  1452. {
  1453. thumbItem = item.GetParents().FirstOrDefault(i => i.HasImage(ImageType.Thumb));
  1454. }
  1455. if (logoItem == null)
  1456. {
  1457. logoItem = item.GetParents().FirstOrDefault(i => i.HasImage(ImageType.Logo));
  1458. }
  1459. if (thumbItem != null)
  1460. {
  1461. info.ThumbImageTag = GetImageCacheTag(thumbItem, ImageType.Thumb);
  1462. info.ThumbItemId = GetDtoId(thumbItem);
  1463. }
  1464. if (backropItem != null)
  1465. {
  1466. info.BackdropImageTag = GetImageCacheTag(backropItem, ImageType.Backdrop);
  1467. info.BackdropItemId = GetDtoId(backropItem);
  1468. }
  1469. if (logoItem != null)
  1470. {
  1471. info.LogoImageTag = GetImageCacheTag(logoItem, ImageType.Logo);
  1472. info.LogoItemId = GetDtoId(logoItem);
  1473. }
  1474. if (chapterOwner != null)
  1475. {
  1476. info.ChapterImagesItemId = chapterOwner.Id.ToString("N");
  1477. info.Chapters = _dtoService.GetChapterInfoDtos(chapterOwner).ToList();
  1478. }
  1479. if (mediaSource != null)
  1480. {
  1481. info.MediaStreams = mediaSource.MediaStreams;
  1482. }
  1483. return info;
  1484. }
  1485. private string GetImageCacheTag(BaseItem item, ImageType type)
  1486. {
  1487. try
  1488. {
  1489. return _imageProcessor.GetImageCacheTag(item, type);
  1490. }
  1491. catch (Exception ex)
  1492. {
  1493. _logger.ErrorException("Error getting {0} image info", ex, type);
  1494. return null;
  1495. }
  1496. }
  1497. private string GetDtoId(BaseItem item)
  1498. {
  1499. return _dtoService.GetDtoId(item);
  1500. }
  1501. public void ReportNowViewingItem(string sessionId, string itemId)
  1502. {
  1503. if (string.IsNullOrWhiteSpace(itemId))
  1504. {
  1505. throw new ArgumentNullException("itemId");
  1506. }
  1507. //var item = _libraryManager.GetItemById(new Guid(itemId));
  1508. //var info = GetItemInfo(item, null, null);
  1509. //ReportNowViewingItem(sessionId, info);
  1510. }
  1511. public void ReportNowViewingItem(string sessionId, BaseItemInfo item)
  1512. {
  1513. //var session = GetSession(sessionId);
  1514. //session.NowViewingItem = item;
  1515. }
  1516. public void ReportTranscodingInfo(string deviceId, TranscodingInfo info)
  1517. {
  1518. var session = Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId));
  1519. if (session != null)
  1520. {
  1521. session.TranscodingInfo = info;
  1522. }
  1523. }
  1524. public void ClearTranscodingInfo(string deviceId)
  1525. {
  1526. ReportTranscodingInfo(deviceId, null);
  1527. }
  1528. public SessionInfo GetSession(string deviceId, string client, string version)
  1529. {
  1530. return Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId) &&
  1531. string.Equals(i.Client, client));
  1532. }
  1533. public Task<SessionInfo> GetSessionByAuthenticationToken(AuthenticationInfo info, string deviceId, string remoteEndpoint, string appVersion)
  1534. {
  1535. if (info == null)
  1536. {
  1537. throw new ArgumentNullException("info");
  1538. }
  1539. var user = string.IsNullOrWhiteSpace(info.UserId)
  1540. ? null
  1541. : _userManager.GetUserById(info.UserId);
  1542. appVersion = string.IsNullOrWhiteSpace(appVersion)
  1543. ? info.AppVersion
  1544. : appVersion;
  1545. var deviceName = info.DeviceName;
  1546. var appName = info.AppName;
  1547. if (!string.IsNullOrWhiteSpace(deviceId))
  1548. {
  1549. // Replace the info from the token with more recent info
  1550. var device = _deviceManager.GetDevice(deviceId);
  1551. if (device != null)
  1552. {
  1553. deviceName = device.Name;
  1554. appName = device.AppName;
  1555. if (!string.IsNullOrWhiteSpace(device.AppVersion))
  1556. {
  1557. appVersion = device.AppVersion;
  1558. }
  1559. }
  1560. }
  1561. else
  1562. {
  1563. deviceId = info.DeviceId;
  1564. }
  1565. // Prevent argument exception
  1566. if (string.IsNullOrWhiteSpace(appVersion))
  1567. {
  1568. appVersion = "1";
  1569. }
  1570. return LogSessionActivity(appName, appVersion, deviceId, deviceName, remoteEndpoint, user);
  1571. }
  1572. public Task<SessionInfo> GetSessionByAuthenticationToken(string token, string deviceId, string remoteEndpoint)
  1573. {
  1574. var result = _authRepo.Get(new AuthenticationInfoQuery
  1575. {
  1576. AccessToken = token
  1577. });
  1578. var info = result.Items.FirstOrDefault();
  1579. if (info == null)
  1580. {
  1581. return Task.FromResult<SessionInfo>(null);
  1582. }
  1583. return GetSessionByAuthenticationToken(info, deviceId, remoteEndpoint, null);
  1584. }
  1585. public Task SendMessageToAdminSessions<T>(string name, T data, CancellationToken cancellationToken)
  1586. {
  1587. var adminUserIds = _userManager.Users.Where(i => i.Policy.IsAdministrator).Select(i => i.Id.ToString("N")).ToList();
  1588. return SendMessageToUserSessions(adminUserIds, name, data, cancellationToken);
  1589. }
  1590. public Task SendMessageToUserSessions<T>(List<string> userIds, string name, T data,
  1591. CancellationToken cancellationToken)
  1592. {
  1593. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null && userIds.Any(i.ContainsUser)).ToList();
  1594. var tasks = sessions.Select(session => Task.Run(async () =>
  1595. {
  1596. try
  1597. {
  1598. await session.SessionController.SendMessage(name, data, cancellationToken).ConfigureAwait(false);
  1599. }
  1600. catch (Exception ex)
  1601. {
  1602. _logger.ErrorException("Error sending message", ex);
  1603. }
  1604. }, cancellationToken));
  1605. return Task.WhenAll(tasks);
  1606. }
  1607. public Task SendMessageToUserDeviceSessions<T>(string deviceId, string name, T data,
  1608. CancellationToken cancellationToken)
  1609. {
  1610. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null && string.Equals(i.DeviceId, deviceId, StringComparison.OrdinalIgnoreCase)).ToList();
  1611. var tasks = sessions.Select(session => Task.Run(async () =>
  1612. {
  1613. try
  1614. {
  1615. await session.SessionController.SendMessage(name, data, cancellationToken).ConfigureAwait(false);
  1616. }
  1617. catch (Exception ex)
  1618. {
  1619. _logger.ErrorException("Error sending message", ex);
  1620. }
  1621. }, cancellationToken));
  1622. return Task.WhenAll(tasks);
  1623. }
  1624. }
  1625. }