LiveTvManager.cs 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000
  1. using MediaBrowser.Common;
  2. using MediaBrowser.Common.Configuration;
  3. using MediaBrowser.Common.Extensions;
  4. using MediaBrowser.Common.Progress;
  5. using MediaBrowser.Common.ScheduledTasks;
  6. using MediaBrowser.Controller.Configuration;
  7. using MediaBrowser.Controller.Drawing;
  8. using MediaBrowser.Controller.Dto;
  9. using MediaBrowser.Controller.Entities;
  10. using MediaBrowser.Controller.Library;
  11. using MediaBrowser.Controller.LiveTv;
  12. using MediaBrowser.Controller.Localization;
  13. using MediaBrowser.Controller.Persistence;
  14. using MediaBrowser.Controller.Providers;
  15. using MediaBrowser.Controller.Sorting;
  16. using MediaBrowser.Model.Dto;
  17. using MediaBrowser.Model.Entities;
  18. using MediaBrowser.Model.LiveTv;
  19. using MediaBrowser.Model.Logging;
  20. using MediaBrowser.Model.Querying;
  21. using MediaBrowser.Model.Serialization;
  22. using System;
  23. using System.Collections.Concurrent;
  24. using System.Collections.Generic;
  25. using System.Linq;
  26. using System.Threading;
  27. using System.Threading.Tasks;
  28. namespace MediaBrowser.Server.Implementations.LiveTv
  29. {
  30. /// <summary>
  31. /// Class LiveTvManager
  32. /// </summary>
  33. public class LiveTvManager : ILiveTvManager, IDisposable
  34. {
  35. private readonly IServerConfigurationManager _config;
  36. private readonly ILogger _logger;
  37. private readonly IItemRepository _itemRepo;
  38. private readonly IUserManager _userManager;
  39. private readonly IUserDataManager _userDataManager;
  40. private readonly ILibraryManager _libraryManager;
  41. private readonly ITaskManager _taskManager;
  42. private readonly IJsonSerializer _jsonSerializer;
  43. private readonly IProviderManager _providerManager;
  44. private readonly IDtoService _dtoService;
  45. private readonly ILocalizationManager _localization;
  46. private readonly LiveTvDtoService _tvDtoService;
  47. private readonly List<ILiveTvService> _services = new List<ILiveTvService>();
  48. private readonly ConcurrentDictionary<string, LiveStreamData> _openStreams =
  49. new ConcurrentDictionary<string, LiveStreamData>();
  50. private List<Guid> _channelIdList = new List<Guid>();
  51. private Dictionary<Guid, LiveTvProgram> _programs = new Dictionary<Guid, LiveTvProgram>();
  52. private readonly ConcurrentDictionary<Guid, bool> _refreshedPrograms = new ConcurrentDictionary<Guid, bool>();
  53. private readonly SemaphoreSlim _refreshSemaphore = new SemaphoreSlim(1, 1);
  54. public LiveTvManager(IApplicationHost appHost, IServerConfigurationManager config, ILogger logger, IItemRepository itemRepo, IImageProcessor imageProcessor, IUserDataManager userDataManager, IDtoService dtoService, IUserManager userManager, ILibraryManager libraryManager, ITaskManager taskManager, ILocalizationManager localization, IJsonSerializer jsonSerializer, IProviderManager providerManager)
  55. {
  56. _config = config;
  57. _logger = logger;
  58. _itemRepo = itemRepo;
  59. _userManager = userManager;
  60. _libraryManager = libraryManager;
  61. _taskManager = taskManager;
  62. _localization = localization;
  63. _jsonSerializer = jsonSerializer;
  64. _providerManager = providerManager;
  65. _dtoService = dtoService;
  66. _userDataManager = userDataManager;
  67. _tvDtoService = new LiveTvDtoService(dtoService, userDataManager, imageProcessor, logger, appHost);
  68. }
  69. /// <summary>
  70. /// Gets the services.
  71. /// </summary>
  72. /// <value>The services.</value>
  73. public IReadOnlyList<ILiveTvService> Services
  74. {
  75. get { return _services; }
  76. }
  77. private LiveTvOptions GetConfiguration()
  78. {
  79. return _config.GetConfiguration<LiveTvOptions>("livetv");
  80. }
  81. /// <summary>
  82. /// Adds the parts.
  83. /// </summary>
  84. /// <param name="services">The services.</param>
  85. public void AddParts(IEnumerable<ILiveTvService> services)
  86. {
  87. _services.AddRange(services);
  88. foreach (var service in _services)
  89. {
  90. service.DataSourceChanged += service_DataSourceChanged;
  91. }
  92. }
  93. void service_DataSourceChanged(object sender, EventArgs e)
  94. {
  95. _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
  96. }
  97. public async Task<QueryResult<LiveTvChannel>> GetInternalChannels(LiveTvChannelQuery query, CancellationToken cancellationToken)
  98. {
  99. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  100. var channels = _channelIdList.Select(_libraryManager.GetItemById)
  101. .Where(i => i != null)
  102. .OfType<LiveTvChannel>();
  103. if (user != null)
  104. {
  105. // Avoid implicitly captured closure
  106. var currentUser = user;
  107. channels = channels
  108. .Where(i => i.IsVisible(currentUser))
  109. .OrderBy(i =>
  110. {
  111. double number = 0;
  112. if (!string.IsNullOrEmpty(i.Number))
  113. {
  114. double.TryParse(i.Number, out number);
  115. }
  116. return number;
  117. });
  118. if (query.IsFavorite.HasValue)
  119. {
  120. var val = query.IsFavorite.Value;
  121. channels = channels
  122. .Where(i => _userDataManager.GetUserData(user.Id, i.GetUserDataKey()).IsFavorite == val);
  123. }
  124. if (query.IsLiked.HasValue)
  125. {
  126. var val = query.IsLiked.Value;
  127. channels = channels
  128. .Where(i =>
  129. {
  130. var likes = _userDataManager.GetUserData(user.Id, i.GetUserDataKey()).Likes;
  131. return likes.HasValue && likes.Value == val;
  132. });
  133. }
  134. if (query.IsDisliked.HasValue)
  135. {
  136. var val = query.IsDisliked.Value;
  137. channels = channels
  138. .Where(i =>
  139. {
  140. var likes = _userDataManager.GetUserData(user.Id, i.GetUserDataKey()).Likes;
  141. return likes.HasValue && likes.Value != val;
  142. });
  143. }
  144. }
  145. var enableFavoriteSorting = query.EnableFavoriteSorting;
  146. channels = channels.OrderBy(i =>
  147. {
  148. if (enableFavoriteSorting)
  149. {
  150. var userData = _userDataManager.GetUserData(user.Id, i.GetUserDataKey());
  151. if (userData.IsFavorite)
  152. {
  153. return 0;
  154. }
  155. if (userData.Likes.HasValue)
  156. {
  157. if (!userData.Likes.Value)
  158. {
  159. return 3;
  160. }
  161. return 1;
  162. }
  163. }
  164. return 2;
  165. });
  166. var allChannels = channels.ToList();
  167. IEnumerable<LiveTvChannel> allEnumerable = allChannels;
  168. if (query.StartIndex.HasValue)
  169. {
  170. allEnumerable = allEnumerable.Skip(query.StartIndex.Value);
  171. }
  172. if (query.Limit.HasValue)
  173. {
  174. allEnumerable = allEnumerable.Take(query.Limit.Value);
  175. }
  176. var result = new QueryResult<LiveTvChannel>
  177. {
  178. Items = allEnumerable.ToArray(),
  179. TotalRecordCount = allChannels.Count
  180. };
  181. return result;
  182. }
  183. public async Task<QueryResult<ChannelInfoDto>> GetChannels(LiveTvChannelQuery query, CancellationToken cancellationToken)
  184. {
  185. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  186. var internalResult = await GetInternalChannels(query, cancellationToken).ConfigureAwait(false);
  187. var returnList = new List<ChannelInfoDto>();
  188. foreach (var channel in internalResult.Items)
  189. {
  190. var currentProgram = GetCurrentProgram(channel.ExternalId);
  191. returnList.Add(_tvDtoService.GetChannelInfoDto(channel, currentProgram, user));
  192. }
  193. var result = new QueryResult<ChannelInfoDto>
  194. {
  195. Items = returnList.ToArray(),
  196. TotalRecordCount = internalResult.TotalRecordCount
  197. };
  198. return result;
  199. }
  200. public LiveTvChannel GetInternalChannel(string id)
  201. {
  202. return GetInternalChannel(new Guid(id));
  203. }
  204. private LiveTvChannel GetInternalChannel(Guid id)
  205. {
  206. return _libraryManager.GetItemById(id) as LiveTvChannel;
  207. }
  208. private LiveTvProgram GetInternalProgram(string id)
  209. {
  210. var guid = new Guid(id);
  211. LiveTvProgram obj = null;
  212. _programs.TryGetValue(guid, out obj);
  213. if (obj != null)
  214. {
  215. RefreshIfNeeded(obj);
  216. }
  217. return obj;
  218. }
  219. private void RefreshIfNeeded(LiveTvProgram program)
  220. {
  221. if (!_refreshedPrograms.ContainsKey(program.Id))
  222. {
  223. _refreshedPrograms.TryAdd(program.Id, true);
  224. _providerManager.QueueRefresh(program.Id, new MetadataRefreshOptions());
  225. }
  226. }
  227. private void RefreshIfNeeded(IEnumerable<LiveTvProgram> programs)
  228. {
  229. foreach (var program in programs)
  230. {
  231. RefreshIfNeeded(program);
  232. }
  233. }
  234. public async Task<ILiveTvRecording> GetInternalRecording(string id, CancellationToken cancellationToken)
  235. {
  236. var result = await GetInternalRecordings(new RecordingQuery
  237. {
  238. Id = id
  239. }, cancellationToken).ConfigureAwait(false);
  240. return result.Items.FirstOrDefault() as ILiveTvRecording;
  241. }
  242. private readonly SemaphoreSlim _liveStreamSemaphore = new SemaphoreSlim(1, 1);
  243. public async Task<MediaSourceInfo> GetRecordingStream(string id, CancellationToken cancellationToken)
  244. {
  245. return await GetLiveStream(id, false, cancellationToken).ConfigureAwait(false);
  246. }
  247. public async Task<MediaSourceInfo> GetChannelStream(string id, CancellationToken cancellationToken)
  248. {
  249. return await GetLiveStream(id, true, cancellationToken).ConfigureAwait(false);
  250. }
  251. public async Task<IEnumerable<MediaSourceInfo>> GetRecordingMediaSources(string id, CancellationToken cancellationToken)
  252. {
  253. var item = await GetInternalRecording(id, cancellationToken).ConfigureAwait(false);
  254. var service = GetService(item);
  255. return await service.GetRecordingStreamMediaSources(id, cancellationToken).ConfigureAwait(false);
  256. }
  257. public async Task<IEnumerable<MediaSourceInfo>> GetChannelMediaSources(string id, CancellationToken cancellationToken)
  258. {
  259. var item = GetInternalChannel(id);
  260. var service = GetService(item);
  261. return await service.GetChannelStreamMediaSources(id, cancellationToken).ConfigureAwait(false);
  262. }
  263. private ILiveTvService GetService(ILiveTvItem item)
  264. {
  265. return GetService(item.ServiceName);
  266. }
  267. private ILiveTvService GetService(string name)
  268. {
  269. return _services.FirstOrDefault(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase));
  270. }
  271. private async Task<MediaSourceInfo> GetLiveStream(string id, bool isChannel, CancellationToken cancellationToken)
  272. {
  273. await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  274. try
  275. {
  276. MediaSourceInfo info;
  277. bool isVideo;
  278. if (isChannel)
  279. {
  280. var channel = GetInternalChannel(id);
  281. isVideo = channel.ChannelType == ChannelType.TV;
  282. var service = GetService(channel);
  283. _logger.Info("Opening channel stream from {0}, external channel Id: {1}", service.Name, channel.ExternalId);
  284. info = await service.GetChannelStream(channel.ExternalId, null, cancellationToken).ConfigureAwait(false);
  285. info.RequiresClosing = true;
  286. if (info.RequiresClosing)
  287. {
  288. var idPrefix = service.GetType().FullName.GetMD5().ToString("N") + "_";
  289. info.LiveStreamId = idPrefix + info.Id;
  290. }
  291. }
  292. else
  293. {
  294. var recording = await GetInternalRecording(id, cancellationToken).ConfigureAwait(false);
  295. isVideo = !string.Equals(recording.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase);
  296. var service = GetService(recording);
  297. _logger.Info("Opening recording stream from {0}, external recording Id: {1}", service.Name, recording.RecordingInfo.Id);
  298. info = await service.GetRecordingStream(recording.RecordingInfo.Id, null, cancellationToken).ConfigureAwait(false);
  299. info.RequiresClosing = true;
  300. if (info.RequiresClosing)
  301. {
  302. var idPrefix = service.GetType().FullName.GetMD5().ToString("N") + "_";
  303. info.LiveStreamId = idPrefix + info.Id;
  304. }
  305. }
  306. _logger.Info("Live stream info: {0}", _jsonSerializer.SerializeToString(info));
  307. Normalize(info, isVideo);
  308. var data = new LiveStreamData
  309. {
  310. Info = info,
  311. IsChannel = isChannel,
  312. ItemId = id
  313. };
  314. _openStreams.AddOrUpdate(info.Id, data, (key, i) => data);
  315. return info;
  316. }
  317. catch (Exception ex)
  318. {
  319. _logger.ErrorException("Error getting channel stream", ex);
  320. throw;
  321. }
  322. finally
  323. {
  324. _liveStreamSemaphore.Release();
  325. }
  326. }
  327. private void Normalize(MediaSourceInfo mediaSource, bool isVideo)
  328. {
  329. if (mediaSource.MediaStreams.Count == 0)
  330. {
  331. if (isVideo)
  332. {
  333. mediaSource.MediaStreams.AddRange(new List<MediaStream>
  334. {
  335. new MediaStream
  336. {
  337. Type = MediaStreamType.Video,
  338. // Set the index to -1 because we don't know the exact index of the video stream within the container
  339. Index = -1,
  340. // Set to true if unknown to enable deinterlacing
  341. IsInterlaced = true
  342. },
  343. new MediaStream
  344. {
  345. Type = MediaStreamType.Audio,
  346. // Set the index to -1 because we don't know the exact index of the audio stream within the container
  347. Index = -1
  348. }
  349. });
  350. }
  351. else
  352. {
  353. mediaSource.MediaStreams.AddRange(new List<MediaStream>
  354. {
  355. new MediaStream
  356. {
  357. Type = MediaStreamType.Audio,
  358. // Set the index to -1 because we don't know the exact index of the audio stream within the container
  359. Index = -1
  360. }
  361. });
  362. }
  363. }
  364. // Clean some bad data coming from providers
  365. foreach (var stream in mediaSource.MediaStreams)
  366. {
  367. if (stream.BitRate.HasValue && stream.BitRate <= 0)
  368. {
  369. stream.BitRate = null;
  370. }
  371. if (stream.Channels.HasValue && stream.Channels <= 0)
  372. {
  373. stream.Channels = null;
  374. }
  375. if (stream.AverageFrameRate.HasValue && stream.AverageFrameRate <= 0)
  376. {
  377. stream.AverageFrameRate = null;
  378. }
  379. if (stream.RealFrameRate.HasValue && stream.RealFrameRate <= 0)
  380. {
  381. stream.RealFrameRate = null;
  382. }
  383. if (stream.Width.HasValue && stream.Width <= 0)
  384. {
  385. stream.Width = null;
  386. }
  387. if (stream.Height.HasValue && stream.Height <= 0)
  388. {
  389. stream.Height = null;
  390. }
  391. if (stream.SampleRate.HasValue && stream.SampleRate <= 0)
  392. {
  393. stream.SampleRate = null;
  394. }
  395. if (stream.Level.HasValue && stream.Level <= 0)
  396. {
  397. stream.Level = null;
  398. }
  399. }
  400. var indexes = mediaSource.MediaStreams.Select(i => i.Index).Distinct().ToList();
  401. // If there are duplicate stream indexes, set them all to unknown
  402. if (indexes.Count != mediaSource.MediaStreams.Count)
  403. {
  404. foreach (var stream in mediaSource.MediaStreams)
  405. {
  406. stream.Index = -1;
  407. }
  408. }
  409. }
  410. private async Task<LiveTvChannel> GetChannel(ChannelInfo channelInfo, string serviceName, CancellationToken cancellationToken)
  411. {
  412. var isNew = false;
  413. var id = _tvDtoService.GetInternalChannelId(serviceName, channelInfo.Id);
  414. var item = _itemRepo.RetrieveItem(id) as LiveTvChannel;
  415. if (item == null)
  416. {
  417. item = new LiveTvChannel
  418. {
  419. Name = channelInfo.Name,
  420. Id = id,
  421. DateCreated = DateTime.UtcNow,
  422. };
  423. isNew = true;
  424. }
  425. item.ChannelType = channelInfo.ChannelType;
  426. item.ExternalId = channelInfo.Id;
  427. item.ServiceName = serviceName;
  428. item.Number = channelInfo.Number;
  429. var replaceImages = new List<ImageType>();
  430. if (!string.Equals(item.ProviderImageUrl, channelInfo.ImageUrl, StringComparison.OrdinalIgnoreCase))
  431. {
  432. isNew = true;
  433. replaceImages.Add(ImageType.Primary);
  434. }
  435. if (!string.Equals(item.ProviderImagePath, channelInfo.ImagePath, StringComparison.OrdinalIgnoreCase))
  436. {
  437. isNew = true;
  438. replaceImages.Add(ImageType.Primary);
  439. }
  440. item.ProviderImageUrl = channelInfo.ImageUrl;
  441. item.HasProviderImage = channelInfo.HasImage;
  442. item.ProviderImagePath = channelInfo.ImagePath;
  443. if (string.IsNullOrEmpty(item.Name))
  444. {
  445. item.Name = channelInfo.Name;
  446. }
  447. await item.RefreshMetadata(new MetadataRefreshOptions
  448. {
  449. ForceSave = isNew,
  450. ReplaceImages = replaceImages.Distinct().ToList()
  451. }, cancellationToken);
  452. return item;
  453. }
  454. private async Task<LiveTvProgram> GetProgram(ProgramInfo info, ChannelType channelType, string serviceName, CancellationToken cancellationToken)
  455. {
  456. var id = _tvDtoService.GetInternalProgramId(serviceName, info.Id);
  457. var item = _libraryManager.GetItemById(id) as LiveTvProgram;
  458. if (item == null)
  459. {
  460. item = new LiveTvProgram
  461. {
  462. Name = info.Name,
  463. Id = id,
  464. DateCreated = DateTime.UtcNow,
  465. DateModified = DateTime.UtcNow
  466. };
  467. }
  468. item.ChannelType = channelType;
  469. item.ServiceName = serviceName;
  470. item.Audio = info.Audio;
  471. item.ExternalChannelId = info.ChannelId;
  472. item.CommunityRating = info.CommunityRating;
  473. item.EndDate = info.EndDate;
  474. item.EpisodeTitle = info.EpisodeTitle;
  475. item.ExternalId = info.Id;
  476. item.Genres = info.Genres;
  477. item.HasProviderImage = info.HasImage;
  478. item.IsHD = info.IsHD;
  479. item.IsKids = info.IsKids;
  480. item.IsLive = info.IsLive;
  481. item.IsMovie = info.IsMovie;
  482. item.IsNews = info.IsNews;
  483. item.IsPremiere = info.IsPremiere;
  484. item.IsRepeat = info.IsRepeat;
  485. item.IsSeries = info.IsSeries;
  486. item.IsSports = info.IsSports;
  487. item.Name = info.Name;
  488. item.OfficialRating = info.OfficialRating;
  489. item.Overview = info.Overview;
  490. item.PremiereDate = info.OriginalAirDate;
  491. item.ProviderImagePath = info.ImagePath;
  492. item.ProviderImageUrl = info.ImageUrl;
  493. item.RunTimeTicks = (info.EndDate - info.StartDate).Ticks;
  494. item.StartDate = info.StartDate;
  495. item.ProductionYear = info.ProductionYear;
  496. await item.UpdateToRepository(ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
  497. return item;
  498. }
  499. private async Task<ILiveTvRecording> GetRecording(RecordingInfo info, string serviceName, CancellationToken cancellationToken)
  500. {
  501. var isNew = false;
  502. var id = _tvDtoService.GetInternalRecordingId(serviceName, info.Id);
  503. var item = _itemRepo.RetrieveItem(id) as ILiveTvRecording;
  504. if (item == null)
  505. {
  506. if (info.ChannelType == ChannelType.TV)
  507. {
  508. item = new LiveTvVideoRecording
  509. {
  510. Name = info.Name,
  511. Id = id,
  512. DateCreated = DateTime.UtcNow,
  513. DateModified = DateTime.UtcNow,
  514. VideoType = VideoType.VideoFile
  515. };
  516. }
  517. else
  518. {
  519. item = new LiveTvAudioRecording
  520. {
  521. Name = info.Name,
  522. Id = id,
  523. DateCreated = DateTime.UtcNow,
  524. DateModified = DateTime.UtcNow
  525. };
  526. }
  527. isNew = true;
  528. }
  529. item.RecordingInfo = info;
  530. item.ServiceName = serviceName;
  531. var originalPath = item.Path;
  532. if (!string.IsNullOrEmpty(info.Path))
  533. {
  534. item.Path = info.Path;
  535. }
  536. else if (!string.IsNullOrEmpty(info.Url))
  537. {
  538. item.Path = info.Url;
  539. }
  540. var pathChanged = !string.Equals(originalPath, item.Path);
  541. await item.RefreshMetadata(new MetadataRefreshOptions
  542. {
  543. ForceSave = isNew || pathChanged
  544. }, cancellationToken);
  545. _libraryManager.RegisterItem((BaseItem)item);
  546. return item;
  547. }
  548. private LiveTvChannel GetChannel(LiveTvProgram program)
  549. {
  550. var programChannelId = program.ExternalChannelId;
  551. if (string.IsNullOrWhiteSpace(programChannelId)) return null;
  552. var internalProgramChannelId = _tvDtoService.GetInternalChannelId(program.ServiceName, programChannelId);
  553. return GetInternalChannel(internalProgramChannelId);
  554. }
  555. public async Task<ProgramInfoDto> GetProgram(string id, CancellationToken cancellationToken, User user = null)
  556. {
  557. var program = GetInternalProgram(id);
  558. var channel = GetChannel(program);
  559. var dto = _tvDtoService.GetProgramInfoDto(program, channel, user);
  560. await AddRecordingInfo(new[] { dto }, cancellationToken).ConfigureAwait(false);
  561. return dto;
  562. }
  563. public async Task<QueryResult<ProgramInfoDto>> GetPrograms(ProgramQuery query, CancellationToken cancellationToken)
  564. {
  565. IEnumerable<LiveTvProgram> programs = _programs.Values;
  566. if (query.MinEndDate.HasValue)
  567. {
  568. var val = query.MinEndDate.Value;
  569. programs = programs.Where(i => i.EndDate.HasValue && i.EndDate.Value >= val);
  570. }
  571. if (query.MinStartDate.HasValue)
  572. {
  573. var val = query.MinStartDate.Value;
  574. programs = programs.Where(i => i.StartDate >= val);
  575. }
  576. if (query.MaxEndDate.HasValue)
  577. {
  578. var val = query.MaxEndDate.Value;
  579. programs = programs.Where(i => i.EndDate.HasValue && i.EndDate.Value <= val);
  580. }
  581. if (query.MaxStartDate.HasValue)
  582. {
  583. var val = query.MaxStartDate.Value;
  584. programs = programs.Where(i => i.StartDate <= val);
  585. }
  586. if (query.HasAired.HasValue)
  587. {
  588. var val = query.HasAired.Value;
  589. programs = programs.Where(i => i.HasAired == val);
  590. }
  591. if (query.ChannelIds.Length > 0)
  592. {
  593. var guids = query.ChannelIds.Select(i => new Guid(i)).ToList();
  594. programs = programs.Where(i =>
  595. {
  596. var programChannelId = i.ExternalChannelId;
  597. var service = GetService(i);
  598. var internalProgramChannelId = _tvDtoService.GetInternalChannelId(service.Name, programChannelId);
  599. return guids.Contains(internalProgramChannelId);
  600. });
  601. }
  602. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  603. if (user != null)
  604. {
  605. // Avoid implicitly captured closure
  606. var currentUser = user;
  607. programs = programs.Where(i => i.IsVisible(currentUser));
  608. }
  609. // Apply genre filter
  610. if (query.Genres.Length > 0)
  611. {
  612. programs = programs.Where(p => p.Genres.Any(g => query.Genres.Contains(g, StringComparer.OrdinalIgnoreCase)));
  613. }
  614. if (query.IsMovie.HasValue)
  615. {
  616. programs = programs.Where(p => p.IsMovie == query.IsMovie);
  617. }
  618. programs = _libraryManager.Sort(programs, user, query.SortBy, query.SortOrder ?? SortOrder.Ascending)
  619. .Cast<LiveTvProgram>();
  620. var programList = programs.ToList();
  621. IEnumerable<LiveTvProgram> returnPrograms = programList;
  622. if (query.StartIndex.HasValue)
  623. {
  624. returnPrograms = returnPrograms.Skip(query.StartIndex.Value);
  625. }
  626. if (query.Limit.HasValue)
  627. {
  628. returnPrograms = returnPrograms.Take(query.Limit.Value);
  629. }
  630. var returnArray = returnPrograms
  631. .Select(i =>
  632. {
  633. var channel = GetChannel(i);
  634. return _tvDtoService.GetProgramInfoDto(i, channel, user);
  635. })
  636. .ToArray();
  637. RefreshIfNeeded(programList);
  638. await AddRecordingInfo(returnArray, cancellationToken).ConfigureAwait(false);
  639. var result = new QueryResult<ProgramInfoDto>
  640. {
  641. Items = returnArray,
  642. TotalRecordCount = programList.Count
  643. };
  644. return result;
  645. }
  646. public async Task<QueryResult<LiveTvProgram>> GetRecommendedProgramsInternal(RecommendedProgramQuery query, CancellationToken cancellationToken)
  647. {
  648. IEnumerable<LiveTvProgram> programs = _programs.Values;
  649. var user = _userManager.GetUserById(query.UserId);
  650. // Avoid implicitly captured closure
  651. var currentUser = user;
  652. programs = programs.Where(i => i.IsVisible(currentUser));
  653. if (query.IsAiring.HasValue)
  654. {
  655. var val = query.IsAiring.Value;
  656. programs = programs.Where(i => i.IsAiring == val);
  657. }
  658. if (query.HasAired.HasValue)
  659. {
  660. var val = query.HasAired.Value;
  661. programs = programs.Where(i => i.HasAired == val);
  662. }
  663. if (query.IsMovie.HasValue)
  664. {
  665. programs = programs.Where(p => p.IsMovie == query.IsMovie.Value);
  666. }
  667. var programList = programs.ToList();
  668. var genres = programList.SelectMany(i => i.Genres)
  669. .Distinct(StringComparer.OrdinalIgnoreCase)
  670. .Select(i => _libraryManager.GetGenre(i))
  671. .ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);
  672. programs = programList.OrderBy(i => i.HasImage(ImageType.Primary) ? 0 : 1)
  673. .ThenByDescending(i => GetRecommendationScore(i, user.Id, genres))
  674. .ThenBy(i => i.StartDate);
  675. if (query.Limit.HasValue)
  676. {
  677. programs = programs.Take(query.Limit.Value)
  678. .OrderBy(i => i.StartDate);
  679. }
  680. programList = programs.ToList();
  681. RefreshIfNeeded(programList);
  682. var returnArray = programList.ToArray();
  683. var result = new QueryResult<LiveTvProgram>
  684. {
  685. Items = returnArray,
  686. TotalRecordCount = returnArray.Length
  687. };
  688. return result;
  689. }
  690. public async Task<QueryResult<ProgramInfoDto>> GetRecommendedPrograms(RecommendedProgramQuery query, CancellationToken cancellationToken)
  691. {
  692. var internalResult = await GetRecommendedProgramsInternal(query, cancellationToken).ConfigureAwait(false);
  693. var user = _userManager.GetUserById(query.UserId);
  694. var returnArray = internalResult.Items
  695. .Select(i =>
  696. {
  697. var channel = GetChannel(i);
  698. return _tvDtoService.GetProgramInfoDto(i, channel, user);
  699. })
  700. .ToArray();
  701. await AddRecordingInfo(returnArray, cancellationToken).ConfigureAwait(false);
  702. var result = new QueryResult<ProgramInfoDto>
  703. {
  704. Items = returnArray,
  705. TotalRecordCount = internalResult.TotalRecordCount
  706. };
  707. return result;
  708. }
  709. private int GetRecommendationScore(LiveTvProgram program, Guid userId, Dictionary<string, Genre> genres)
  710. {
  711. var score = 0;
  712. if (program.IsLive)
  713. {
  714. score++;
  715. }
  716. if (program.IsSeries && !program.IsRepeat)
  717. {
  718. score++;
  719. }
  720. var internalChannelId = _tvDtoService.GetInternalChannelId(program.ServiceName, program.ExternalChannelId);
  721. var channel = GetInternalChannel(internalChannelId);
  722. var channelUserdata = _userDataManager.GetUserData(userId, channel.GetUserDataKey());
  723. if ((channelUserdata.Likes ?? false))
  724. {
  725. score += 2;
  726. }
  727. else if (!(channelUserdata.Likes ?? true))
  728. {
  729. score -= 2;
  730. }
  731. if (channelUserdata.IsFavorite)
  732. {
  733. score += 3;
  734. }
  735. score += GetGenreScore(program.Genres, userId, genres);
  736. return score;
  737. }
  738. private int GetGenreScore(IEnumerable<string> programGenres, Guid userId, Dictionary<string, Genre> genres)
  739. {
  740. return programGenres.Select(i =>
  741. {
  742. var score = 0;
  743. Genre genre;
  744. if (genres.TryGetValue(i, out genre))
  745. {
  746. var genreUserdata = _userDataManager.GetUserData(userId, genre.GetUserDataKey());
  747. if ((genreUserdata.Likes ?? false))
  748. {
  749. score++;
  750. }
  751. else if (!(genreUserdata.Likes ?? true))
  752. {
  753. score--;
  754. }
  755. if (genreUserdata.IsFavorite)
  756. {
  757. score += 2;
  758. }
  759. }
  760. return score;
  761. }).Sum();
  762. }
  763. private async Task AddRecordingInfo(IEnumerable<ProgramInfoDto> programs, CancellationToken cancellationToken)
  764. {
  765. var timers = new Dictionary<string, List<TimerInfo>>();
  766. foreach (var program in programs)
  767. {
  768. List<TimerInfo> timerList;
  769. if (!timers.TryGetValue(program.ServiceName, out timerList))
  770. {
  771. var tempTimers = await GetService(program.ServiceName).GetTimersAsync(cancellationToken).ConfigureAwait(false);
  772. timers[program.ServiceName] = timerList = tempTimers.ToList();
  773. }
  774. var timer = timerList.FirstOrDefault(i => string.Equals(i.ProgramId, program.ExternalId, StringComparison.OrdinalIgnoreCase));
  775. if (timer != null)
  776. {
  777. program.TimerId = _tvDtoService.GetInternalTimerId(program.ServiceName, timer.Id)
  778. .ToString("N");
  779. if (!string.IsNullOrEmpty(timer.SeriesTimerId))
  780. {
  781. program.SeriesTimerId = _tvDtoService.GetInternalSeriesTimerId(program.ServiceName, timer.SeriesTimerId)
  782. .ToString("N");
  783. }
  784. }
  785. }
  786. }
  787. internal async Task RefreshChannels(IProgress<double> progress, CancellationToken cancellationToken)
  788. {
  789. await _refreshSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  790. try
  791. {
  792. var innerProgress = new ActionableProgress<double>();
  793. innerProgress.RegisterAction(p => progress.Report(p * .9));
  794. await RefreshChannelsInternal(innerProgress, cancellationToken).ConfigureAwait(false);
  795. innerProgress = new ActionableProgress<double>();
  796. innerProgress.RegisterAction(p => progress.Report(90 + (p * .1)));
  797. await CleanDatabaseInternal(progress, cancellationToken).ConfigureAwait(false);
  798. }
  799. finally
  800. {
  801. _refreshSemaphore.Release();
  802. }
  803. }
  804. private async Task RefreshChannelsInternal(IProgress<double> progress, CancellationToken cancellationToken)
  805. {
  806. var numComplete = 0;
  807. double progressPerService = _services.Count == 0
  808. ? 0
  809. : 1 / _services.Count;
  810. foreach (var service in _services)
  811. {
  812. cancellationToken.ThrowIfCancellationRequested();
  813. try
  814. {
  815. var innerProgress = new ActionableProgress<double>();
  816. innerProgress.RegisterAction(p => progress.Report(p * progressPerService));
  817. await RefreshChannelsInternal(service, innerProgress, cancellationToken).ConfigureAwait(false);
  818. }
  819. catch (OperationCanceledException)
  820. {
  821. throw;
  822. }
  823. catch (Exception ex)
  824. {
  825. _logger.ErrorException("Error refreshing channels for service", ex);
  826. }
  827. numComplete++;
  828. double percent = numComplete;
  829. percent /= _services.Count;
  830. progress.Report(100 * percent);
  831. }
  832. progress.Report(100);
  833. }
  834. private async Task RefreshChannelsInternal(ILiveTvService service, IProgress<double> progress, CancellationToken cancellationToken)
  835. {
  836. progress.Report(10);
  837. var allChannels = await GetChannels(service, cancellationToken).ConfigureAwait(false);
  838. var allChannelsList = allChannels.ToList();
  839. var list = new List<LiveTvChannel>();
  840. var numComplete = 0;
  841. foreach (var channelInfo in allChannelsList)
  842. {
  843. cancellationToken.ThrowIfCancellationRequested();
  844. try
  845. {
  846. var item = await GetChannel(channelInfo.Item2, channelInfo.Item1, cancellationToken).ConfigureAwait(false);
  847. list.Add(item);
  848. _libraryManager.RegisterItem(item);
  849. }
  850. catch (OperationCanceledException)
  851. {
  852. throw;
  853. }
  854. catch (Exception ex)
  855. {
  856. _logger.ErrorException("Error getting channel information for {0}", ex, channelInfo.Item2.Name);
  857. }
  858. numComplete++;
  859. double percent = numComplete;
  860. percent /= allChannelsList.Count;
  861. progress.Report(5 * percent + 10);
  862. }
  863. _channelIdList = list.Select(i => i.Id).ToList();
  864. progress.Report(15);
  865. numComplete = 0;
  866. var programs = new List<LiveTvProgram>();
  867. var guideDays = GetGuideDays(list.Count);
  868. cancellationToken.ThrowIfCancellationRequested();
  869. foreach (var item in list)
  870. {
  871. cancellationToken.ThrowIfCancellationRequested();
  872. // Avoid implicitly captured closure
  873. var currentChannel = item;
  874. try
  875. {
  876. var start = DateTime.UtcNow.AddHours(-1);
  877. var end = start.AddDays(guideDays);
  878. var channelPrograms = await service.GetProgramsAsync(currentChannel.ExternalId, start, end, cancellationToken).ConfigureAwait(false);
  879. foreach (var program in channelPrograms)
  880. {
  881. programs.Add(await GetProgram(program, currentChannel.ChannelType, service.Name, cancellationToken).ConfigureAwait(false));
  882. }
  883. }
  884. catch (OperationCanceledException)
  885. {
  886. throw;
  887. }
  888. catch (Exception ex)
  889. {
  890. _logger.ErrorException("Error getting programs for channel {0}", ex, currentChannel.Name);
  891. }
  892. numComplete++;
  893. double percent = numComplete;
  894. percent /= allChannelsList.Count;
  895. progress.Report(80 * percent + 10);
  896. }
  897. _programs = programs.ToDictionary(i => i.Id);
  898. _refreshedPrograms.Clear();
  899. progress.Report(90);
  900. // Load these now which will prefetch metadata
  901. await GetRecordings(new RecordingQuery(), cancellationToken).ConfigureAwait(false);
  902. progress.Report(100);
  903. }
  904. public async Task CleanDatabase(IProgress<double> progress, CancellationToken cancellationToken)
  905. {
  906. await _refreshSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  907. try
  908. {
  909. await DeleteOldPrograms(_programs.Keys.ToList(), progress, cancellationToken).ConfigureAwait(false);
  910. }
  911. finally
  912. {
  913. _refreshSemaphore.Release();
  914. }
  915. }
  916. private Task CleanDatabaseInternal(IProgress<double> progress, CancellationToken cancellationToken)
  917. {
  918. return DeleteOldPrograms(_programs.Keys.ToList(), progress, cancellationToken);
  919. }
  920. private async Task DeleteOldPrograms(List<Guid> currentIdList, IProgress<double> progress, CancellationToken cancellationToken)
  921. {
  922. var list = _itemRepo.GetItemsOfType(typeof(LiveTvProgram)).ToList();
  923. var numComplete = 0;
  924. foreach (var programId in list)
  925. {
  926. cancellationToken.ThrowIfCancellationRequested();
  927. if (!currentIdList.Contains(programId))
  928. {
  929. var program = _libraryManager.GetItemById(programId);
  930. if (program != null)
  931. {
  932. await _libraryManager.DeleteItem(program).ConfigureAwait(false);
  933. }
  934. }
  935. numComplete++;
  936. double percent = numComplete;
  937. percent /= list.Count;
  938. progress.Report(100 * percent);
  939. }
  940. }
  941. private double GetGuideDays(int channelCount)
  942. {
  943. var config = GetConfiguration();
  944. if (config.GuideDays.HasValue)
  945. {
  946. return config.GuideDays.Value;
  947. }
  948. var programsPerDay = channelCount * 48;
  949. const int maxPrograms = 24000;
  950. var days = Math.Round(((double)maxPrograms) / programsPerDay);
  951. // No less than 2, no more than 7
  952. return Math.Max(2, Math.Min(days, 7));
  953. }
  954. private async Task<IEnumerable<Tuple<string, ChannelInfo>>> GetChannels(ILiveTvService service, CancellationToken cancellationToken)
  955. {
  956. var channels = await service.GetChannelsAsync(cancellationToken).ConfigureAwait(false);
  957. return channels.Select(i => new Tuple<string, ChannelInfo>(service.Name, i));
  958. }
  959. public async Task<QueryResult<BaseItem>> GetInternalRecordings(RecordingQuery query, CancellationToken cancellationToken)
  960. {
  961. var tasks = _services.Select(async i =>
  962. {
  963. try
  964. {
  965. var recs = await i.GetRecordingsAsync(cancellationToken).ConfigureAwait(false);
  966. return recs.Select(r => new Tuple<RecordingInfo, ILiveTvService>(r, i));
  967. }
  968. catch (Exception ex)
  969. {
  970. _logger.ErrorException("Error getting recordings", ex);
  971. return new List<Tuple<RecordingInfo, ILiveTvService>>();
  972. }
  973. });
  974. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  975. var recordings = results.SelectMany(i => i.ToList());
  976. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  977. if (user != null && !IsLiveTvEnabled(user))
  978. {
  979. recordings = new List<Tuple<RecordingInfo, ILiveTvService>>();
  980. }
  981. if (!string.IsNullOrEmpty(query.ChannelId))
  982. {
  983. var guid = new Guid(query.ChannelId);
  984. recordings = recordings
  985. .Where(i => _tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId) == guid);
  986. }
  987. if (!string.IsNullOrEmpty(query.Id))
  988. {
  989. var guid = new Guid(query.Id);
  990. recordings = recordings
  991. .Where(i => _tvDtoService.GetInternalRecordingId(i.Item2.Name, i.Item1.Id) == guid);
  992. }
  993. if (!string.IsNullOrEmpty(query.GroupId))
  994. {
  995. var guid = new Guid(query.GroupId);
  996. recordings = recordings.Where(i => GetRecordingGroupIds(i.Item1).Contains(guid));
  997. }
  998. if (query.IsInProgress.HasValue)
  999. {
  1000. var val = query.IsInProgress.Value;
  1001. recordings = recordings.Where(i => (i.Item1.Status == RecordingStatus.InProgress) == val);
  1002. }
  1003. if (query.Status.HasValue)
  1004. {
  1005. var val = query.Status.Value;
  1006. recordings = recordings.Where(i => (i.Item1.Status == val));
  1007. }
  1008. if (!string.IsNullOrEmpty(query.SeriesTimerId))
  1009. {
  1010. var guid = new Guid(query.SeriesTimerId);
  1011. recordings = recordings
  1012. .Where(i => _tvDtoService.GetInternalSeriesTimerId(i.Item2.Name, i.Item1.SeriesTimerId) == guid);
  1013. }
  1014. recordings = recordings.OrderByDescending(i => i.Item1.StartDate);
  1015. IEnumerable<ILiveTvRecording> entities = await GetEntities(recordings, cancellationToken).ConfigureAwait(false);
  1016. if (user != null)
  1017. {
  1018. var currentUser = user;
  1019. entities = entities.Where(i => i.IsParentalAllowed(currentUser));
  1020. }
  1021. var entityList = entities.ToList();
  1022. entities = entityList;
  1023. if (query.StartIndex.HasValue)
  1024. {
  1025. entities = entities.Skip(query.StartIndex.Value);
  1026. }
  1027. if (query.Limit.HasValue)
  1028. {
  1029. entities = entities.Take(query.Limit.Value);
  1030. }
  1031. return new QueryResult<BaseItem>
  1032. {
  1033. Items = entities.Cast<BaseItem>().ToArray(),
  1034. TotalRecordCount = entityList.Count
  1035. };
  1036. }
  1037. public async Task<QueryResult<RecordingInfoDto>> GetRecordings(RecordingQuery query, CancellationToken cancellationToken)
  1038. {
  1039. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  1040. var internalResult = await GetInternalRecordings(query, cancellationToken).ConfigureAwait(false);
  1041. var returnArray = internalResult.Items.Cast<ILiveTvRecording>()
  1042. .Select(i =>
  1043. {
  1044. var service = GetService(i);
  1045. var channel = string.IsNullOrEmpty(i.RecordingInfo.ChannelId) ? null : GetInternalChannel(_tvDtoService.GetInternalChannelId(service.Name, i.RecordingInfo.ChannelId));
  1046. return _tvDtoService.GetRecordingInfoDto(i, channel, service, user);
  1047. })
  1048. .ToArray();
  1049. return new QueryResult<RecordingInfoDto>
  1050. {
  1051. Items = returnArray,
  1052. TotalRecordCount = internalResult.TotalRecordCount
  1053. };
  1054. }
  1055. private Task<ILiveTvRecording[]> GetEntities(IEnumerable<Tuple<RecordingInfo, ILiveTvService>> recordings, CancellationToken cancellationToken)
  1056. {
  1057. var tasks = recordings.Select(i => GetRecording(i.Item1, i.Item2.Name, cancellationToken));
  1058. return Task.WhenAll(tasks);
  1059. }
  1060. public async Task<QueryResult<TimerInfoDto>> GetTimers(TimerQuery query, CancellationToken cancellationToken)
  1061. {
  1062. var tasks = _services.Select(async i =>
  1063. {
  1064. try
  1065. {
  1066. var recs = await i.GetTimersAsync(cancellationToken).ConfigureAwait(false);
  1067. return recs.Select(r => new Tuple<TimerInfo, ILiveTvService>(r, i));
  1068. }
  1069. catch (Exception ex)
  1070. {
  1071. _logger.ErrorException("Error getting recordings", ex);
  1072. return new List<Tuple<TimerInfo, ILiveTvService>>();
  1073. }
  1074. });
  1075. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  1076. var timers = results.SelectMany(i => i.ToList());
  1077. if (!string.IsNullOrEmpty(query.ChannelId))
  1078. {
  1079. var guid = new Guid(query.ChannelId);
  1080. timers = timers.Where(i => guid == _tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId));
  1081. }
  1082. if (!string.IsNullOrEmpty(query.SeriesTimerId))
  1083. {
  1084. var guid = new Guid(query.SeriesTimerId);
  1085. timers = timers
  1086. .Where(i => _tvDtoService.GetInternalSeriesTimerId(i.Item2.Name, i.Item1.SeriesTimerId) == guid);
  1087. }
  1088. var returnList = new List<TimerInfoDto>();
  1089. foreach (var i in timers)
  1090. {
  1091. var program = string.IsNullOrEmpty(i.Item1.ProgramId) ?
  1092. null :
  1093. GetInternalProgram(_tvDtoService.GetInternalProgramId(i.Item2.Name, i.Item1.ProgramId).ToString("N"));
  1094. var channel = string.IsNullOrEmpty(i.Item1.ChannelId) ? null : GetInternalChannel(_tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId));
  1095. returnList.Add(_tvDtoService.GetTimerInfoDto(i.Item1, i.Item2, program, channel));
  1096. }
  1097. var returnArray = returnList
  1098. .OrderBy(i => i.StartDate)
  1099. .ToArray();
  1100. return new QueryResult<TimerInfoDto>
  1101. {
  1102. Items = returnArray,
  1103. TotalRecordCount = returnArray.Length
  1104. };
  1105. }
  1106. public async Task DeleteRecording(string recordingId)
  1107. {
  1108. var recording = await GetRecording(recordingId, CancellationToken.None).ConfigureAwait(false);
  1109. if (recording == null)
  1110. {
  1111. throw new ResourceNotFoundException(string.Format("Recording with Id {0} not found", recordingId));
  1112. }
  1113. var service = GetService(recording.ServiceName);
  1114. await service.DeleteRecordingAsync(recording.ExternalId, CancellationToken.None).ConfigureAwait(false);
  1115. }
  1116. public async Task CancelTimer(string id)
  1117. {
  1118. var timer = await GetTimer(id, CancellationToken.None).ConfigureAwait(false);
  1119. if (timer == null)
  1120. {
  1121. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  1122. }
  1123. var service = GetService(timer.ServiceName);
  1124. await service.CancelTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  1125. }
  1126. public async Task CancelSeriesTimer(string id)
  1127. {
  1128. var timer = await GetSeriesTimer(id, CancellationToken.None).ConfigureAwait(false);
  1129. if (timer == null)
  1130. {
  1131. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  1132. }
  1133. var service = GetService(timer.ServiceName);
  1134. await service.CancelSeriesTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  1135. }
  1136. public async Task<RecordingInfoDto> GetRecording(string id, CancellationToken cancellationToken, User user = null)
  1137. {
  1138. var results = await GetRecordings(new RecordingQuery
  1139. {
  1140. UserId = user == null ? null : user.Id.ToString("N"),
  1141. Id = id
  1142. }, cancellationToken).ConfigureAwait(false);
  1143. return results.Items.FirstOrDefault();
  1144. }
  1145. public async Task<TimerInfoDto> GetTimer(string id, CancellationToken cancellationToken)
  1146. {
  1147. var results = await GetTimers(new TimerQuery(), cancellationToken).ConfigureAwait(false);
  1148. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
  1149. }
  1150. public async Task<SeriesTimerInfoDto> GetSeriesTimer(string id, CancellationToken cancellationToken)
  1151. {
  1152. var results = await GetSeriesTimers(new SeriesTimerQuery(), cancellationToken).ConfigureAwait(false);
  1153. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
  1154. }
  1155. public async Task<QueryResult<SeriesTimerInfoDto>> GetSeriesTimers(SeriesTimerQuery query, CancellationToken cancellationToken)
  1156. {
  1157. var tasks = _services.Select(async i =>
  1158. {
  1159. try
  1160. {
  1161. var recs = await i.GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false);
  1162. return recs.Select(r => new Tuple<SeriesTimerInfo, ILiveTvService>(r, i));
  1163. }
  1164. catch (Exception ex)
  1165. {
  1166. _logger.ErrorException("Error getting recordings", ex);
  1167. return new List<Tuple<SeriesTimerInfo, ILiveTvService>>();
  1168. }
  1169. });
  1170. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  1171. var timers = results.SelectMany(i => i.ToList());
  1172. if (string.Equals(query.SortBy, "Priority", StringComparison.OrdinalIgnoreCase))
  1173. {
  1174. timers = query.SortOrder == SortOrder.Descending ?
  1175. timers.OrderBy(i => i.Item1.Priority).ThenByStringDescending(i => i.Item1.Name) :
  1176. timers.OrderByDescending(i => i.Item1.Priority).ThenByString(i => i.Item1.Name);
  1177. }
  1178. else
  1179. {
  1180. timers = query.SortOrder == SortOrder.Descending ?
  1181. timers.OrderByStringDescending(i => i.Item1.Name) :
  1182. timers.OrderByString(i => i.Item1.Name);
  1183. }
  1184. var returnArray = timers
  1185. .Select(i =>
  1186. {
  1187. string channelName = null;
  1188. if (!string.IsNullOrEmpty(i.Item1.ChannelId))
  1189. {
  1190. var internalChannelId = _tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId);
  1191. var channel = GetInternalChannel(internalChannelId);
  1192. channelName = channel == null ? null : channel.Name;
  1193. }
  1194. return _tvDtoService.GetSeriesTimerInfoDto(i.Item1, i.Item2, channelName);
  1195. })
  1196. .ToArray();
  1197. return new QueryResult<SeriesTimerInfoDto>
  1198. {
  1199. Items = returnArray,
  1200. TotalRecordCount = returnArray.Length
  1201. };
  1202. }
  1203. public async Task<ChannelInfoDto> GetChannel(string id, CancellationToken cancellationToken, User user = null)
  1204. {
  1205. var channel = GetInternalChannel(id);
  1206. var currentProgram = GetCurrentProgram(channel.ExternalId);
  1207. var dto = _tvDtoService.GetChannelInfoDto(channel, currentProgram, user);
  1208. return dto;
  1209. }
  1210. private LiveTvProgram GetCurrentProgram(string externalChannelId)
  1211. {
  1212. var now = DateTime.UtcNow;
  1213. var program = _programs.Values
  1214. .Where(i => string.Equals(externalChannelId, i.ExternalChannelId, StringComparison.OrdinalIgnoreCase))
  1215. .OrderBy(i => i.StartDate)
  1216. .SkipWhile(i => now >= (i.EndDate ?? DateTime.MinValue))
  1217. .FirstOrDefault();
  1218. if (program != null)
  1219. {
  1220. RefreshIfNeeded(program);
  1221. }
  1222. return program;
  1223. }
  1224. private async Task<Tuple<SeriesTimerInfo, ILiveTvService>> GetNewTimerDefaultsInternal(CancellationToken cancellationToken, LiveTvProgram program = null)
  1225. {
  1226. var service = program != null && !string.IsNullOrWhiteSpace(program.ServiceName) ?
  1227. GetService(program) :
  1228. _services.FirstOrDefault();
  1229. ProgramInfo programInfo = null;
  1230. if (program != null)
  1231. {
  1232. programInfo = new ProgramInfo
  1233. {
  1234. Audio = program.Audio,
  1235. ChannelId = program.ExternalChannelId,
  1236. CommunityRating = program.CommunityRating,
  1237. EndDate = program.EndDate ?? DateTime.MinValue,
  1238. EpisodeTitle = program.EpisodeTitle,
  1239. Genres = program.Genres,
  1240. HasImage = program.HasProviderImage,
  1241. Id = program.ExternalId,
  1242. IsHD = program.IsHD,
  1243. IsKids = program.IsKids,
  1244. IsLive = program.IsLive,
  1245. IsMovie = program.IsMovie,
  1246. IsNews = program.IsNews,
  1247. IsPremiere = program.IsPremiere,
  1248. IsRepeat = program.IsRepeat,
  1249. IsSeries = program.IsSeries,
  1250. IsSports = program.IsSports,
  1251. OriginalAirDate = program.PremiereDate,
  1252. Overview = program.Overview,
  1253. StartDate = program.StartDate,
  1254. ImagePath = program.ProviderImagePath,
  1255. ImageUrl = program.ProviderImageUrl,
  1256. Name = program.Name,
  1257. OfficialRating = program.OfficialRating
  1258. };
  1259. }
  1260. var info = await service.GetNewTimerDefaultsAsync(cancellationToken, programInfo).ConfigureAwait(false);
  1261. info.Id = null;
  1262. return new Tuple<SeriesTimerInfo, ILiveTvService>(info, service);
  1263. }
  1264. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(CancellationToken cancellationToken)
  1265. {
  1266. var info = await GetNewTimerDefaultsInternal(cancellationToken).ConfigureAwait(false);
  1267. var obj = _tvDtoService.GetSeriesTimerInfoDto(info.Item1, info.Item2, null);
  1268. return obj;
  1269. }
  1270. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(string programId, CancellationToken cancellationToken)
  1271. {
  1272. var program = GetInternalProgram(programId);
  1273. var programDto = await GetProgram(programId, cancellationToken).ConfigureAwait(false);
  1274. var defaults = await GetNewTimerDefaultsInternal(cancellationToken, program).ConfigureAwait(false);
  1275. var info = _tvDtoService.GetSeriesTimerInfoDto(defaults.Item1, defaults.Item2, null);
  1276. info.Days = new List<DayOfWeek>
  1277. {
  1278. program.StartDate.ToLocalTime().DayOfWeek
  1279. };
  1280. info.DayPattern = _tvDtoService.GetDayPattern(info.Days);
  1281. info.Name = program.Name;
  1282. info.ChannelId = programDto.ChannelId;
  1283. info.ChannelName = programDto.ChannelName;
  1284. info.StartDate = program.StartDate;
  1285. info.Name = program.Name;
  1286. info.Overview = program.Overview;
  1287. info.ProgramId = programDto.Id;
  1288. info.ExternalProgramId = programDto.ExternalId;
  1289. if (program.EndDate.HasValue)
  1290. {
  1291. info.EndDate = program.EndDate.Value;
  1292. }
  1293. return info;
  1294. }
  1295. public async Task CreateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  1296. {
  1297. var service = GetService(timer.ServiceName);
  1298. var info = await _tvDtoService.GetTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  1299. // Set priority from default values
  1300. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  1301. info.Priority = defaultValues.Priority;
  1302. await service.CreateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1303. }
  1304. public async Task CreateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  1305. {
  1306. var service = GetService(timer.ServiceName);
  1307. var info = await _tvDtoService.GetSeriesTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  1308. // Set priority from default values
  1309. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  1310. info.Priority = defaultValues.Priority;
  1311. await service.CreateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1312. }
  1313. public async Task UpdateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  1314. {
  1315. var info = await _tvDtoService.GetTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  1316. var service = GetService(timer.ServiceName);
  1317. await service.UpdateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1318. }
  1319. public async Task UpdateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  1320. {
  1321. var info = await _tvDtoService.GetSeriesTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  1322. var service = GetService(timer.ServiceName);
  1323. await service.UpdateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1324. }
  1325. private IEnumerable<string> GetRecordingGroupNames(RecordingInfo recording)
  1326. {
  1327. var list = new List<string>();
  1328. if (recording.IsSeries)
  1329. {
  1330. list.Add(recording.Name);
  1331. }
  1332. if (recording.IsKids)
  1333. {
  1334. list.Add("Kids");
  1335. }
  1336. if (recording.IsMovie)
  1337. {
  1338. list.Add("Movies");
  1339. }
  1340. if (recording.IsNews)
  1341. {
  1342. list.Add("News");
  1343. }
  1344. if (recording.IsSports)
  1345. {
  1346. list.Add("Sports");
  1347. }
  1348. if (!recording.IsSports && !recording.IsNews && !recording.IsMovie && !recording.IsKids && !recording.IsSeries)
  1349. {
  1350. list.Add("Others");
  1351. }
  1352. return list;
  1353. }
  1354. private List<Guid> GetRecordingGroupIds(RecordingInfo recording)
  1355. {
  1356. return GetRecordingGroupNames(recording).Select(i => i.ToLower()
  1357. .GetMD5())
  1358. .ToList();
  1359. }
  1360. public async Task<QueryResult<RecordingGroupDto>> GetRecordingGroups(RecordingGroupQuery query, CancellationToken cancellationToken)
  1361. {
  1362. var recordingResult = await GetRecordings(new RecordingQuery
  1363. {
  1364. UserId = query.UserId
  1365. }, cancellationToken).ConfigureAwait(false);
  1366. var recordings = recordingResult.Items;
  1367. var groups = new List<RecordingGroupDto>();
  1368. var series = recordings
  1369. .Where(i => i.IsSeries)
  1370. .ToLookup(i => i.Name, StringComparer.OrdinalIgnoreCase)
  1371. .ToList();
  1372. groups.AddRange(series.OrderByString(i => i.Key).Select(i => new RecordingGroupDto
  1373. {
  1374. Name = i.Key,
  1375. RecordingCount = i.Count()
  1376. }));
  1377. groups.Add(new RecordingGroupDto
  1378. {
  1379. Name = "Kids",
  1380. RecordingCount = recordings.Count(i => i.IsKids)
  1381. });
  1382. groups.Add(new RecordingGroupDto
  1383. {
  1384. Name = "Movies",
  1385. RecordingCount = recordings.Count(i => i.IsMovie)
  1386. });
  1387. groups.Add(new RecordingGroupDto
  1388. {
  1389. Name = "News",
  1390. RecordingCount = recordings.Count(i => i.IsNews)
  1391. });
  1392. groups.Add(new RecordingGroupDto
  1393. {
  1394. Name = "Sports",
  1395. RecordingCount = recordings.Count(i => i.IsSports)
  1396. });
  1397. groups.Add(new RecordingGroupDto
  1398. {
  1399. Name = "Others",
  1400. RecordingCount = recordings.Count(i => !i.IsSports && !i.IsNews && !i.IsMovie && !i.IsKids && !i.IsSeries)
  1401. });
  1402. groups = groups
  1403. .Where(i => i.RecordingCount > 0)
  1404. .ToList();
  1405. foreach (var group in groups)
  1406. {
  1407. group.Id = group.Name.ToLower().GetMD5().ToString("N");
  1408. }
  1409. return new QueryResult<RecordingGroupDto>
  1410. {
  1411. Items = groups.ToArray(),
  1412. TotalRecordCount = groups.Count
  1413. };
  1414. }
  1415. class LiveStreamData
  1416. {
  1417. internal MediaSourceInfo Info;
  1418. internal string ItemId;
  1419. internal bool IsChannel;
  1420. }
  1421. public async Task CloseLiveStream(string id, CancellationToken cancellationToken)
  1422. {
  1423. await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  1424. try
  1425. {
  1426. var parts = id.Split(new[] { '_' }, 2);
  1427. var service = _services.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N"), parts[0], StringComparison.OrdinalIgnoreCase));
  1428. if (service == null)
  1429. {
  1430. throw new ArgumentException("Service not found.");
  1431. }
  1432. id = parts[1];
  1433. LiveStreamData data;
  1434. _openStreams.TryRemove(id, out data);
  1435. _logger.Info("Closing live stream from {0}, stream Id: {1}", service.Name, id);
  1436. await service.CloseLiveStream(id, cancellationToken).ConfigureAwait(false);
  1437. }
  1438. catch (Exception ex)
  1439. {
  1440. _logger.ErrorException("Error closing live stream", ex);
  1441. throw;
  1442. }
  1443. finally
  1444. {
  1445. _liveStreamSemaphore.Release();
  1446. }
  1447. }
  1448. public GuideInfo GetGuideInfo()
  1449. {
  1450. var programs = _programs.ToList();
  1451. var startDate = _programs.Count == 0 ? DateTime.MinValue :
  1452. programs.Select(i => i.Value.StartDate).Min();
  1453. var endDate = programs.Count == 0 ? DateTime.MinValue :
  1454. programs.Select(i => i.Value.StartDate).Max();
  1455. return new GuideInfo
  1456. {
  1457. StartDate = startDate,
  1458. EndDate = endDate
  1459. };
  1460. }
  1461. /// <summary>
  1462. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1463. /// </summary>
  1464. public void Dispose()
  1465. {
  1466. Dispose(true);
  1467. }
  1468. private readonly object _disposeLock = new object();
  1469. /// <summary>
  1470. /// Releases unmanaged and - optionally - managed resources.
  1471. /// </summary>
  1472. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1473. protected virtual void Dispose(bool dispose)
  1474. {
  1475. if (dispose)
  1476. {
  1477. lock (_disposeLock)
  1478. {
  1479. foreach (var stream in _openStreams.Values.ToList())
  1480. {
  1481. var task = CloseLiveStream(stream.Info.Id, CancellationToken.None);
  1482. Task.WaitAll(task);
  1483. }
  1484. _openStreams.Clear();
  1485. }
  1486. }
  1487. }
  1488. private async Task<IEnumerable<LiveTvServiceInfo>> GetServiceInfos(CancellationToken cancellationToken)
  1489. {
  1490. var tasks = Services.Select(i => GetServiceInfo(i, cancellationToken));
  1491. return await Task.WhenAll(tasks).ConfigureAwait(false);
  1492. }
  1493. private async Task<LiveTvServiceInfo> GetServiceInfo(ILiveTvService service, CancellationToken cancellationToken)
  1494. {
  1495. var info = new LiveTvServiceInfo
  1496. {
  1497. Name = service.Name
  1498. };
  1499. var tunerIdPrefix = service.GetType().FullName.GetMD5().ToString("N") + "_";
  1500. try
  1501. {
  1502. var statusInfo = await service.GetStatusInfoAsync(cancellationToken).ConfigureAwait(false);
  1503. info.Status = statusInfo.Status;
  1504. info.StatusMessage = statusInfo.StatusMessage;
  1505. info.Version = statusInfo.Version;
  1506. info.HasUpdateAvailable = statusInfo.HasUpdateAvailable;
  1507. info.HomePageUrl = service.HomePageUrl;
  1508. info.Tuners = statusInfo.Tuners.Select(i =>
  1509. {
  1510. string channelName = null;
  1511. if (!string.IsNullOrEmpty(i.ChannelId))
  1512. {
  1513. var internalChannelId = _tvDtoService.GetInternalChannelId(service.Name, i.ChannelId);
  1514. var channel = GetInternalChannel(internalChannelId);
  1515. channelName = channel == null ? null : channel.Name;
  1516. }
  1517. var dto = _tvDtoService.GetTunerInfoDto(service.Name, i, channelName);
  1518. dto.Id = tunerIdPrefix + dto.Id;
  1519. return dto;
  1520. }).ToList();
  1521. }
  1522. catch (Exception ex)
  1523. {
  1524. _logger.ErrorException("Error getting service status info from {0}", ex, service.Name ?? string.Empty);
  1525. info.Status = LiveTvServiceStatus.Unavailable;
  1526. info.StatusMessage = ex.Message;
  1527. }
  1528. return info;
  1529. }
  1530. public async Task<LiveTvInfo> GetLiveTvInfo(CancellationToken cancellationToken)
  1531. {
  1532. var services = await GetServiceInfos(CancellationToken.None).ConfigureAwait(false);
  1533. var servicesList = services.ToList();
  1534. var info = new LiveTvInfo
  1535. {
  1536. Services = servicesList.ToList(),
  1537. IsEnabled = servicesList.Count > 0
  1538. };
  1539. info.EnabledUsers = _userManager.Users
  1540. .Where(IsLiveTvEnabled)
  1541. .Select(i => i.Id.ToString("N"))
  1542. .ToList();
  1543. return info;
  1544. }
  1545. private bool IsLiveTvEnabled(User user)
  1546. {
  1547. return user.Policy.EnableLiveTvAccess && Services.Count > 0;
  1548. }
  1549. public IEnumerable<User> GetEnabledUsers()
  1550. {
  1551. return _userManager.Users
  1552. .Where(IsLiveTvEnabled);
  1553. }
  1554. /// <summary>
  1555. /// Resets the tuner.
  1556. /// </summary>
  1557. /// <param name="id">The identifier.</param>
  1558. /// <param name="cancellationToken">The cancellation token.</param>
  1559. /// <returns>Task.</returns>
  1560. public Task ResetTuner(string id, CancellationToken cancellationToken)
  1561. {
  1562. var parts = id.Split(new[] { '_' }, 2);
  1563. var service = _services.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N"), parts[0], StringComparison.OrdinalIgnoreCase));
  1564. if (service == null)
  1565. {
  1566. throw new ArgumentException("Service not found.");
  1567. }
  1568. return service.ResetTuner(parts[1], cancellationToken);
  1569. }
  1570. public async Task<BaseItemDto> GetLiveTvFolder(string userId, CancellationToken cancellationToken)
  1571. {
  1572. var user = string.IsNullOrEmpty(userId) ? null : _userManager.GetUserById(userId);
  1573. var folder = await GetInternalLiveTvFolder(userId, cancellationToken).ConfigureAwait(false);
  1574. return _dtoService.GetBaseItemDto(folder, new DtoOptions(), user);
  1575. }
  1576. public async Task<Folder> GetInternalLiveTvFolder(string userId, CancellationToken cancellationToken)
  1577. {
  1578. var name = _localization.GetLocalizedString("ViewTypeLiveTV");
  1579. var user = _userManager.GetUserById(userId);
  1580. return await _libraryManager.GetNamedView(user, name, "livetv", "zz_" + name, cancellationToken).ConfigureAwait(false);
  1581. }
  1582. }
  1583. }