LiveTvManager.cs 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002
  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.OriginalAirDate = 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. item.PremiereDate = item.PremiereDate ?? info.OriginalAirDate;
  497. await item.UpdateToRepository(ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
  498. return item;
  499. }
  500. private async Task<ILiveTvRecording> GetRecording(RecordingInfo info, string serviceName, CancellationToken cancellationToken)
  501. {
  502. var isNew = false;
  503. var id = _tvDtoService.GetInternalRecordingId(serviceName, info.Id);
  504. var item = _itemRepo.RetrieveItem(id) as ILiveTvRecording;
  505. if (item == null)
  506. {
  507. if (info.ChannelType == ChannelType.TV)
  508. {
  509. item = new LiveTvVideoRecording
  510. {
  511. Name = info.Name,
  512. Id = id,
  513. DateCreated = DateTime.UtcNow,
  514. DateModified = DateTime.UtcNow,
  515. VideoType = VideoType.VideoFile
  516. };
  517. }
  518. else
  519. {
  520. item = new LiveTvAudioRecording
  521. {
  522. Name = info.Name,
  523. Id = id,
  524. DateCreated = DateTime.UtcNow,
  525. DateModified = DateTime.UtcNow
  526. };
  527. }
  528. isNew = true;
  529. }
  530. item.RecordingInfo = info;
  531. item.ServiceName = serviceName;
  532. var originalPath = item.Path;
  533. if (!string.IsNullOrEmpty(info.Path))
  534. {
  535. item.Path = info.Path;
  536. }
  537. else if (!string.IsNullOrEmpty(info.Url))
  538. {
  539. item.Path = info.Url;
  540. }
  541. var pathChanged = !string.Equals(originalPath, item.Path);
  542. await item.RefreshMetadata(new MetadataRefreshOptions
  543. {
  544. ForceSave = isNew || pathChanged
  545. }, cancellationToken);
  546. _libraryManager.RegisterItem((BaseItem)item);
  547. return item;
  548. }
  549. private LiveTvChannel GetChannel(LiveTvProgram program)
  550. {
  551. var programChannelId = program.ExternalChannelId;
  552. if (string.IsNullOrWhiteSpace(programChannelId)) return null;
  553. var internalProgramChannelId = _tvDtoService.GetInternalChannelId(program.ServiceName, programChannelId);
  554. return GetInternalChannel(internalProgramChannelId);
  555. }
  556. public async Task<ProgramInfoDto> GetProgram(string id, CancellationToken cancellationToken, User user = null)
  557. {
  558. var program = GetInternalProgram(id);
  559. var channel = GetChannel(program);
  560. var dto = _tvDtoService.GetProgramInfoDto(program, channel, user);
  561. await AddRecordingInfo(new[] { dto }, cancellationToken).ConfigureAwait(false);
  562. return dto;
  563. }
  564. public async Task<QueryResult<ProgramInfoDto>> GetPrograms(ProgramQuery query, CancellationToken cancellationToken)
  565. {
  566. IEnumerable<LiveTvProgram> programs = _programs.Values;
  567. if (query.MinEndDate.HasValue)
  568. {
  569. var val = query.MinEndDate.Value;
  570. programs = programs.Where(i => i.EndDate.HasValue && i.EndDate.Value >= val);
  571. }
  572. if (query.MinStartDate.HasValue)
  573. {
  574. var val = query.MinStartDate.Value;
  575. programs = programs.Where(i => i.StartDate >= val);
  576. }
  577. if (query.MaxEndDate.HasValue)
  578. {
  579. var val = query.MaxEndDate.Value;
  580. programs = programs.Where(i => i.EndDate.HasValue && i.EndDate.Value <= val);
  581. }
  582. if (query.MaxStartDate.HasValue)
  583. {
  584. var val = query.MaxStartDate.Value;
  585. programs = programs.Where(i => i.StartDate <= val);
  586. }
  587. if (query.HasAired.HasValue)
  588. {
  589. var val = query.HasAired.Value;
  590. programs = programs.Where(i => i.HasAired == val);
  591. }
  592. if (query.ChannelIds.Length > 0)
  593. {
  594. var guids = query.ChannelIds.Select(i => new Guid(i)).ToList();
  595. programs = programs.Where(i =>
  596. {
  597. var programChannelId = i.ExternalChannelId;
  598. var service = GetService(i);
  599. var internalProgramChannelId = _tvDtoService.GetInternalChannelId(service.Name, programChannelId);
  600. return guids.Contains(internalProgramChannelId);
  601. });
  602. }
  603. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  604. if (user != null)
  605. {
  606. // Avoid implicitly captured closure
  607. var currentUser = user;
  608. programs = programs.Where(i => i.IsVisible(currentUser));
  609. }
  610. // Apply genre filter
  611. if (query.Genres.Length > 0)
  612. {
  613. programs = programs.Where(p => p.Genres.Any(g => query.Genres.Contains(g, StringComparer.OrdinalIgnoreCase)));
  614. }
  615. if (query.IsMovie.HasValue)
  616. {
  617. programs = programs.Where(p => p.IsMovie == query.IsMovie);
  618. }
  619. programs = _libraryManager.Sort(programs, user, query.SortBy, query.SortOrder ?? SortOrder.Ascending)
  620. .Cast<LiveTvProgram>();
  621. var programList = programs.ToList();
  622. IEnumerable<LiveTvProgram> returnPrograms = programList;
  623. if (query.StartIndex.HasValue)
  624. {
  625. returnPrograms = returnPrograms.Skip(query.StartIndex.Value);
  626. }
  627. if (query.Limit.HasValue)
  628. {
  629. returnPrograms = returnPrograms.Take(query.Limit.Value);
  630. }
  631. var returnArray = returnPrograms
  632. .Select(i =>
  633. {
  634. var channel = GetChannel(i);
  635. return _tvDtoService.GetProgramInfoDto(i, channel, user);
  636. })
  637. .ToArray();
  638. RefreshIfNeeded(programList);
  639. await AddRecordingInfo(returnArray, cancellationToken).ConfigureAwait(false);
  640. var result = new QueryResult<ProgramInfoDto>
  641. {
  642. Items = returnArray,
  643. TotalRecordCount = programList.Count
  644. };
  645. return result;
  646. }
  647. public async Task<QueryResult<LiveTvProgram>> GetRecommendedProgramsInternal(RecommendedProgramQuery query, CancellationToken cancellationToken)
  648. {
  649. IEnumerable<LiveTvProgram> programs = _programs.Values;
  650. var user = _userManager.GetUserById(query.UserId);
  651. // Avoid implicitly captured closure
  652. var currentUser = user;
  653. programs = programs.Where(i => i.IsVisible(currentUser));
  654. if (query.IsAiring.HasValue)
  655. {
  656. var val = query.IsAiring.Value;
  657. programs = programs.Where(i => i.IsAiring == val);
  658. }
  659. if (query.HasAired.HasValue)
  660. {
  661. var val = query.HasAired.Value;
  662. programs = programs.Where(i => i.HasAired == val);
  663. }
  664. if (query.IsMovie.HasValue)
  665. {
  666. programs = programs.Where(p => p.IsMovie == query.IsMovie.Value);
  667. }
  668. var programList = programs.ToList();
  669. var genres = programList.SelectMany(i => i.Genres)
  670. .Distinct(StringComparer.OrdinalIgnoreCase)
  671. .Select(i => _libraryManager.GetGenre(i))
  672. .ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);
  673. programs = programList.OrderBy(i => i.HasImage(ImageType.Primary) ? 0 : 1)
  674. .ThenByDescending(i => GetRecommendationScore(i, user.Id, genres))
  675. .ThenBy(i => i.StartDate);
  676. if (query.Limit.HasValue)
  677. {
  678. programs = programs.Take(query.Limit.Value)
  679. .OrderBy(i => i.StartDate);
  680. }
  681. programList = programs.ToList();
  682. RefreshIfNeeded(programList);
  683. var returnArray = programList.ToArray();
  684. var result = new QueryResult<LiveTvProgram>
  685. {
  686. Items = returnArray,
  687. TotalRecordCount = returnArray.Length
  688. };
  689. return result;
  690. }
  691. public async Task<QueryResult<ProgramInfoDto>> GetRecommendedPrograms(RecommendedProgramQuery query, CancellationToken cancellationToken)
  692. {
  693. var internalResult = await GetRecommendedProgramsInternal(query, cancellationToken).ConfigureAwait(false);
  694. var user = _userManager.GetUserById(query.UserId);
  695. var returnArray = internalResult.Items
  696. .Select(i =>
  697. {
  698. var channel = GetChannel(i);
  699. return _tvDtoService.GetProgramInfoDto(i, channel, user);
  700. })
  701. .ToArray();
  702. await AddRecordingInfo(returnArray, cancellationToken).ConfigureAwait(false);
  703. var result = new QueryResult<ProgramInfoDto>
  704. {
  705. Items = returnArray,
  706. TotalRecordCount = internalResult.TotalRecordCount
  707. };
  708. return result;
  709. }
  710. private int GetRecommendationScore(LiveTvProgram program, Guid userId, Dictionary<string, Genre> genres)
  711. {
  712. var score = 0;
  713. if (program.IsLive)
  714. {
  715. score++;
  716. }
  717. if (program.IsSeries && !program.IsRepeat)
  718. {
  719. score++;
  720. }
  721. var internalChannelId = _tvDtoService.GetInternalChannelId(program.ServiceName, program.ExternalChannelId);
  722. var channel = GetInternalChannel(internalChannelId);
  723. var channelUserdata = _userDataManager.GetUserData(userId, channel.GetUserDataKey());
  724. if ((channelUserdata.Likes ?? false))
  725. {
  726. score += 2;
  727. }
  728. else if (!(channelUserdata.Likes ?? true))
  729. {
  730. score -= 2;
  731. }
  732. if (channelUserdata.IsFavorite)
  733. {
  734. score += 3;
  735. }
  736. score += GetGenreScore(program.Genres, userId, genres);
  737. return score;
  738. }
  739. private int GetGenreScore(IEnumerable<string> programGenres, Guid userId, Dictionary<string, Genre> genres)
  740. {
  741. return programGenres.Select(i =>
  742. {
  743. var score = 0;
  744. Genre genre;
  745. if (genres.TryGetValue(i, out genre))
  746. {
  747. var genreUserdata = _userDataManager.GetUserData(userId, genre.GetUserDataKey());
  748. if ((genreUserdata.Likes ?? false))
  749. {
  750. score++;
  751. }
  752. else if (!(genreUserdata.Likes ?? true))
  753. {
  754. score--;
  755. }
  756. if (genreUserdata.IsFavorite)
  757. {
  758. score += 2;
  759. }
  760. }
  761. return score;
  762. }).Sum();
  763. }
  764. private async Task AddRecordingInfo(IEnumerable<ProgramInfoDto> programs, CancellationToken cancellationToken)
  765. {
  766. var timers = new Dictionary<string, List<TimerInfo>>();
  767. foreach (var program in programs)
  768. {
  769. List<TimerInfo> timerList;
  770. if (!timers.TryGetValue(program.ServiceName, out timerList))
  771. {
  772. var tempTimers = await GetService(program.ServiceName).GetTimersAsync(cancellationToken).ConfigureAwait(false);
  773. timers[program.ServiceName] = timerList = tempTimers.ToList();
  774. }
  775. var timer = timerList.FirstOrDefault(i => string.Equals(i.ProgramId, program.ExternalId, StringComparison.OrdinalIgnoreCase));
  776. if (timer != null)
  777. {
  778. program.TimerId = _tvDtoService.GetInternalTimerId(program.ServiceName, timer.Id)
  779. .ToString("N");
  780. if (!string.IsNullOrEmpty(timer.SeriesTimerId))
  781. {
  782. program.SeriesTimerId = _tvDtoService.GetInternalSeriesTimerId(program.ServiceName, timer.SeriesTimerId)
  783. .ToString("N");
  784. }
  785. }
  786. }
  787. }
  788. internal async Task RefreshChannels(IProgress<double> progress, CancellationToken cancellationToken)
  789. {
  790. await _refreshSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  791. try
  792. {
  793. var innerProgress = new ActionableProgress<double>();
  794. innerProgress.RegisterAction(p => progress.Report(p * .9));
  795. await RefreshChannelsInternal(innerProgress, cancellationToken).ConfigureAwait(false);
  796. innerProgress = new ActionableProgress<double>();
  797. innerProgress.RegisterAction(p => progress.Report(90 + (p * .1)));
  798. await CleanDatabaseInternal(progress, cancellationToken).ConfigureAwait(false);
  799. }
  800. finally
  801. {
  802. _refreshSemaphore.Release();
  803. }
  804. }
  805. private async Task RefreshChannelsInternal(IProgress<double> progress, CancellationToken cancellationToken)
  806. {
  807. var numComplete = 0;
  808. double progressPerService = _services.Count == 0
  809. ? 0
  810. : 1 / _services.Count;
  811. foreach (var service in _services)
  812. {
  813. cancellationToken.ThrowIfCancellationRequested();
  814. try
  815. {
  816. var innerProgress = new ActionableProgress<double>();
  817. innerProgress.RegisterAction(p => progress.Report(p * progressPerService));
  818. await RefreshChannelsInternal(service, innerProgress, cancellationToken).ConfigureAwait(false);
  819. }
  820. catch (OperationCanceledException)
  821. {
  822. throw;
  823. }
  824. catch (Exception ex)
  825. {
  826. _logger.ErrorException("Error refreshing channels for service", ex);
  827. }
  828. numComplete++;
  829. double percent = numComplete;
  830. percent /= _services.Count;
  831. progress.Report(100 * percent);
  832. }
  833. progress.Report(100);
  834. }
  835. private async Task RefreshChannelsInternal(ILiveTvService service, IProgress<double> progress, CancellationToken cancellationToken)
  836. {
  837. progress.Report(10);
  838. var allChannels = await GetChannels(service, cancellationToken).ConfigureAwait(false);
  839. var allChannelsList = allChannels.ToList();
  840. var list = new List<LiveTvChannel>();
  841. var numComplete = 0;
  842. foreach (var channelInfo in allChannelsList)
  843. {
  844. cancellationToken.ThrowIfCancellationRequested();
  845. try
  846. {
  847. var item = await GetChannel(channelInfo.Item2, channelInfo.Item1, cancellationToken).ConfigureAwait(false);
  848. list.Add(item);
  849. _libraryManager.RegisterItem(item);
  850. }
  851. catch (OperationCanceledException)
  852. {
  853. throw;
  854. }
  855. catch (Exception ex)
  856. {
  857. _logger.ErrorException("Error getting channel information for {0}", ex, channelInfo.Item2.Name);
  858. }
  859. numComplete++;
  860. double percent = numComplete;
  861. percent /= allChannelsList.Count;
  862. progress.Report(5 * percent + 10);
  863. }
  864. _channelIdList = list.Select(i => i.Id).ToList();
  865. progress.Report(15);
  866. numComplete = 0;
  867. var programs = new List<LiveTvProgram>();
  868. var guideDays = GetGuideDays(list.Count);
  869. cancellationToken.ThrowIfCancellationRequested();
  870. foreach (var item in list)
  871. {
  872. cancellationToken.ThrowIfCancellationRequested();
  873. // Avoid implicitly captured closure
  874. var currentChannel = item;
  875. try
  876. {
  877. var start = DateTime.UtcNow.AddHours(-1);
  878. var end = start.AddDays(guideDays);
  879. var channelPrograms = await service.GetProgramsAsync(currentChannel.ExternalId, start, end, cancellationToken).ConfigureAwait(false);
  880. foreach (var program in channelPrograms)
  881. {
  882. programs.Add(await GetProgram(program, currentChannel.ChannelType, service.Name, cancellationToken).ConfigureAwait(false));
  883. }
  884. }
  885. catch (OperationCanceledException)
  886. {
  887. throw;
  888. }
  889. catch (Exception ex)
  890. {
  891. _logger.ErrorException("Error getting programs for channel {0}", ex, currentChannel.Name);
  892. }
  893. numComplete++;
  894. double percent = numComplete;
  895. percent /= allChannelsList.Count;
  896. progress.Report(80 * percent + 10);
  897. }
  898. _programs = programs.ToDictionary(i => i.Id);
  899. _refreshedPrograms.Clear();
  900. progress.Report(90);
  901. // Load these now which will prefetch metadata
  902. await GetRecordings(new RecordingQuery(), cancellationToken).ConfigureAwait(false);
  903. progress.Report(100);
  904. }
  905. public async Task CleanDatabase(IProgress<double> progress, CancellationToken cancellationToken)
  906. {
  907. await _refreshSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  908. try
  909. {
  910. await DeleteOldPrograms(_programs.Keys.ToList(), progress, cancellationToken).ConfigureAwait(false);
  911. }
  912. finally
  913. {
  914. _refreshSemaphore.Release();
  915. }
  916. }
  917. private Task CleanDatabaseInternal(IProgress<double> progress, CancellationToken cancellationToken)
  918. {
  919. return DeleteOldPrograms(_programs.Keys.ToList(), progress, cancellationToken);
  920. }
  921. private async Task DeleteOldPrograms(List<Guid> currentIdList, IProgress<double> progress, CancellationToken cancellationToken)
  922. {
  923. var list = _itemRepo.GetItemsOfType(typeof(LiveTvProgram)).ToList();
  924. var numComplete = 0;
  925. foreach (var programId in list)
  926. {
  927. cancellationToken.ThrowIfCancellationRequested();
  928. if (!currentIdList.Contains(programId))
  929. {
  930. var program = _libraryManager.GetItemById(programId);
  931. if (program != null)
  932. {
  933. await _libraryManager.DeleteItem(program).ConfigureAwait(false);
  934. }
  935. }
  936. numComplete++;
  937. double percent = numComplete;
  938. percent /= list.Count;
  939. progress.Report(100 * percent);
  940. }
  941. }
  942. private double GetGuideDays(int channelCount)
  943. {
  944. var config = GetConfiguration();
  945. if (config.GuideDays.HasValue)
  946. {
  947. return config.GuideDays.Value;
  948. }
  949. var programsPerDay = channelCount * 48;
  950. const int maxPrograms = 24000;
  951. var days = Math.Round(((double)maxPrograms) / programsPerDay);
  952. // No less than 2, no more than 7
  953. return Math.Max(2, Math.Min(days, 7));
  954. }
  955. private async Task<IEnumerable<Tuple<string, ChannelInfo>>> GetChannels(ILiveTvService service, CancellationToken cancellationToken)
  956. {
  957. var channels = await service.GetChannelsAsync(cancellationToken).ConfigureAwait(false);
  958. return channels.Select(i => new Tuple<string, ChannelInfo>(service.Name, i));
  959. }
  960. public async Task<QueryResult<BaseItem>> GetInternalRecordings(RecordingQuery query, CancellationToken cancellationToken)
  961. {
  962. var tasks = _services.Select(async i =>
  963. {
  964. try
  965. {
  966. var recs = await i.GetRecordingsAsync(cancellationToken).ConfigureAwait(false);
  967. return recs.Select(r => new Tuple<RecordingInfo, ILiveTvService>(r, i));
  968. }
  969. catch (Exception ex)
  970. {
  971. _logger.ErrorException("Error getting recordings", ex);
  972. return new List<Tuple<RecordingInfo, ILiveTvService>>();
  973. }
  974. });
  975. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  976. var recordings = results.SelectMany(i => i.ToList());
  977. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  978. if (user != null && !IsLiveTvEnabled(user))
  979. {
  980. recordings = new List<Tuple<RecordingInfo, ILiveTvService>>();
  981. }
  982. if (!string.IsNullOrEmpty(query.ChannelId))
  983. {
  984. var guid = new Guid(query.ChannelId);
  985. recordings = recordings
  986. .Where(i => _tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId) == guid);
  987. }
  988. if (!string.IsNullOrEmpty(query.Id))
  989. {
  990. var guid = new Guid(query.Id);
  991. recordings = recordings
  992. .Where(i => _tvDtoService.GetInternalRecordingId(i.Item2.Name, i.Item1.Id) == guid);
  993. }
  994. if (!string.IsNullOrEmpty(query.GroupId))
  995. {
  996. var guid = new Guid(query.GroupId);
  997. recordings = recordings.Where(i => GetRecordingGroupIds(i.Item1).Contains(guid));
  998. }
  999. if (query.IsInProgress.HasValue)
  1000. {
  1001. var val = query.IsInProgress.Value;
  1002. recordings = recordings.Where(i => (i.Item1.Status == RecordingStatus.InProgress) == val);
  1003. }
  1004. if (query.Status.HasValue)
  1005. {
  1006. var val = query.Status.Value;
  1007. recordings = recordings.Where(i => (i.Item1.Status == val));
  1008. }
  1009. if (!string.IsNullOrEmpty(query.SeriesTimerId))
  1010. {
  1011. var guid = new Guid(query.SeriesTimerId);
  1012. recordings = recordings
  1013. .Where(i => _tvDtoService.GetInternalSeriesTimerId(i.Item2.Name, i.Item1.SeriesTimerId) == guid);
  1014. }
  1015. recordings = recordings.OrderByDescending(i => i.Item1.StartDate);
  1016. IEnumerable<ILiveTvRecording> entities = await GetEntities(recordings, cancellationToken).ConfigureAwait(false);
  1017. if (user != null)
  1018. {
  1019. var currentUser = user;
  1020. entities = entities.Where(i => i.IsParentalAllowed(currentUser));
  1021. }
  1022. var entityList = entities.ToList();
  1023. entities = entityList;
  1024. if (query.StartIndex.HasValue)
  1025. {
  1026. entities = entities.Skip(query.StartIndex.Value);
  1027. }
  1028. if (query.Limit.HasValue)
  1029. {
  1030. entities = entities.Take(query.Limit.Value);
  1031. }
  1032. return new QueryResult<BaseItem>
  1033. {
  1034. Items = entities.Cast<BaseItem>().ToArray(),
  1035. TotalRecordCount = entityList.Count
  1036. };
  1037. }
  1038. public async Task<QueryResult<RecordingInfoDto>> GetRecordings(RecordingQuery query, CancellationToken cancellationToken)
  1039. {
  1040. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  1041. var internalResult = await GetInternalRecordings(query, cancellationToken).ConfigureAwait(false);
  1042. var returnArray = internalResult.Items.Cast<ILiveTvRecording>()
  1043. .Select(i =>
  1044. {
  1045. var service = GetService(i);
  1046. var channel = string.IsNullOrEmpty(i.RecordingInfo.ChannelId) ? null : GetInternalChannel(_tvDtoService.GetInternalChannelId(service.Name, i.RecordingInfo.ChannelId));
  1047. return _tvDtoService.GetRecordingInfoDto(i, channel, service, user);
  1048. })
  1049. .ToArray();
  1050. return new QueryResult<RecordingInfoDto>
  1051. {
  1052. Items = returnArray,
  1053. TotalRecordCount = internalResult.TotalRecordCount
  1054. };
  1055. }
  1056. private Task<ILiveTvRecording[]> GetEntities(IEnumerable<Tuple<RecordingInfo, ILiveTvService>> recordings, CancellationToken cancellationToken)
  1057. {
  1058. var tasks = recordings.Select(i => GetRecording(i.Item1, i.Item2.Name, cancellationToken));
  1059. return Task.WhenAll(tasks);
  1060. }
  1061. public async Task<QueryResult<TimerInfoDto>> GetTimers(TimerQuery query, CancellationToken cancellationToken)
  1062. {
  1063. var tasks = _services.Select(async i =>
  1064. {
  1065. try
  1066. {
  1067. var recs = await i.GetTimersAsync(cancellationToken).ConfigureAwait(false);
  1068. return recs.Select(r => new Tuple<TimerInfo, ILiveTvService>(r, i));
  1069. }
  1070. catch (Exception ex)
  1071. {
  1072. _logger.ErrorException("Error getting recordings", ex);
  1073. return new List<Tuple<TimerInfo, ILiveTvService>>();
  1074. }
  1075. });
  1076. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  1077. var timers = results.SelectMany(i => i.ToList());
  1078. if (!string.IsNullOrEmpty(query.ChannelId))
  1079. {
  1080. var guid = new Guid(query.ChannelId);
  1081. timers = timers.Where(i => guid == _tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId));
  1082. }
  1083. if (!string.IsNullOrEmpty(query.SeriesTimerId))
  1084. {
  1085. var guid = new Guid(query.SeriesTimerId);
  1086. timers = timers
  1087. .Where(i => _tvDtoService.GetInternalSeriesTimerId(i.Item2.Name, i.Item1.SeriesTimerId) == guid);
  1088. }
  1089. var returnList = new List<TimerInfoDto>();
  1090. foreach (var i in timers)
  1091. {
  1092. var program = string.IsNullOrEmpty(i.Item1.ProgramId) ?
  1093. null :
  1094. GetInternalProgram(_tvDtoService.GetInternalProgramId(i.Item2.Name, i.Item1.ProgramId).ToString("N"));
  1095. var channel = string.IsNullOrEmpty(i.Item1.ChannelId) ? null : GetInternalChannel(_tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId));
  1096. returnList.Add(_tvDtoService.GetTimerInfoDto(i.Item1, i.Item2, program, channel));
  1097. }
  1098. var returnArray = returnList
  1099. .OrderBy(i => i.StartDate)
  1100. .ToArray();
  1101. return new QueryResult<TimerInfoDto>
  1102. {
  1103. Items = returnArray,
  1104. TotalRecordCount = returnArray.Length
  1105. };
  1106. }
  1107. public async Task DeleteRecording(string recordingId)
  1108. {
  1109. var recording = await GetRecording(recordingId, CancellationToken.None).ConfigureAwait(false);
  1110. if (recording == null)
  1111. {
  1112. throw new ResourceNotFoundException(string.Format("Recording with Id {0} not found", recordingId));
  1113. }
  1114. var service = GetService(recording.ServiceName);
  1115. await service.DeleteRecordingAsync(recording.ExternalId, CancellationToken.None).ConfigureAwait(false);
  1116. }
  1117. public async Task CancelTimer(string id)
  1118. {
  1119. var timer = await GetTimer(id, CancellationToken.None).ConfigureAwait(false);
  1120. if (timer == null)
  1121. {
  1122. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  1123. }
  1124. var service = GetService(timer.ServiceName);
  1125. await service.CancelTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  1126. }
  1127. public async Task CancelSeriesTimer(string id)
  1128. {
  1129. var timer = await GetSeriesTimer(id, CancellationToken.None).ConfigureAwait(false);
  1130. if (timer == null)
  1131. {
  1132. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  1133. }
  1134. var service = GetService(timer.ServiceName);
  1135. await service.CancelSeriesTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  1136. }
  1137. public async Task<RecordingInfoDto> GetRecording(string id, CancellationToken cancellationToken, User user = null)
  1138. {
  1139. var results = await GetRecordings(new RecordingQuery
  1140. {
  1141. UserId = user == null ? null : user.Id.ToString("N"),
  1142. Id = id
  1143. }, cancellationToken).ConfigureAwait(false);
  1144. return results.Items.FirstOrDefault();
  1145. }
  1146. public async Task<TimerInfoDto> GetTimer(string id, CancellationToken cancellationToken)
  1147. {
  1148. var results = await GetTimers(new TimerQuery(), cancellationToken).ConfigureAwait(false);
  1149. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
  1150. }
  1151. public async Task<SeriesTimerInfoDto> GetSeriesTimer(string id, CancellationToken cancellationToken)
  1152. {
  1153. var results = await GetSeriesTimers(new SeriesTimerQuery(), cancellationToken).ConfigureAwait(false);
  1154. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
  1155. }
  1156. public async Task<QueryResult<SeriesTimerInfoDto>> GetSeriesTimers(SeriesTimerQuery query, CancellationToken cancellationToken)
  1157. {
  1158. var tasks = _services.Select(async i =>
  1159. {
  1160. try
  1161. {
  1162. var recs = await i.GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false);
  1163. return recs.Select(r => new Tuple<SeriesTimerInfo, ILiveTvService>(r, i));
  1164. }
  1165. catch (Exception ex)
  1166. {
  1167. _logger.ErrorException("Error getting recordings", ex);
  1168. return new List<Tuple<SeriesTimerInfo, ILiveTvService>>();
  1169. }
  1170. });
  1171. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  1172. var timers = results.SelectMany(i => i.ToList());
  1173. if (string.Equals(query.SortBy, "Priority", StringComparison.OrdinalIgnoreCase))
  1174. {
  1175. timers = query.SortOrder == SortOrder.Descending ?
  1176. timers.OrderBy(i => i.Item1.Priority).ThenByStringDescending(i => i.Item1.Name) :
  1177. timers.OrderByDescending(i => i.Item1.Priority).ThenByString(i => i.Item1.Name);
  1178. }
  1179. else
  1180. {
  1181. timers = query.SortOrder == SortOrder.Descending ?
  1182. timers.OrderByStringDescending(i => i.Item1.Name) :
  1183. timers.OrderByString(i => i.Item1.Name);
  1184. }
  1185. var returnArray = timers
  1186. .Select(i =>
  1187. {
  1188. string channelName = null;
  1189. if (!string.IsNullOrEmpty(i.Item1.ChannelId))
  1190. {
  1191. var internalChannelId = _tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId);
  1192. var channel = GetInternalChannel(internalChannelId);
  1193. channelName = channel == null ? null : channel.Name;
  1194. }
  1195. return _tvDtoService.GetSeriesTimerInfoDto(i.Item1, i.Item2, channelName);
  1196. })
  1197. .ToArray();
  1198. return new QueryResult<SeriesTimerInfoDto>
  1199. {
  1200. Items = returnArray,
  1201. TotalRecordCount = returnArray.Length
  1202. };
  1203. }
  1204. public async Task<ChannelInfoDto> GetChannel(string id, CancellationToken cancellationToken, User user = null)
  1205. {
  1206. var channel = GetInternalChannel(id);
  1207. var currentProgram = GetCurrentProgram(channel.ExternalId);
  1208. var dto = _tvDtoService.GetChannelInfoDto(channel, currentProgram, user);
  1209. return dto;
  1210. }
  1211. private LiveTvProgram GetCurrentProgram(string externalChannelId)
  1212. {
  1213. var now = DateTime.UtcNow;
  1214. var program = _programs.Values
  1215. .Where(i => string.Equals(externalChannelId, i.ExternalChannelId, StringComparison.OrdinalIgnoreCase))
  1216. .OrderBy(i => i.StartDate)
  1217. .SkipWhile(i => now >= (i.EndDate ?? DateTime.MinValue))
  1218. .FirstOrDefault();
  1219. if (program != null)
  1220. {
  1221. RefreshIfNeeded(program);
  1222. }
  1223. return program;
  1224. }
  1225. private async Task<Tuple<SeriesTimerInfo, ILiveTvService>> GetNewTimerDefaultsInternal(CancellationToken cancellationToken, LiveTvProgram program = null)
  1226. {
  1227. var service = program != null && !string.IsNullOrWhiteSpace(program.ServiceName) ?
  1228. GetService(program) :
  1229. _services.FirstOrDefault();
  1230. ProgramInfo programInfo = null;
  1231. if (program != null)
  1232. {
  1233. programInfo = new ProgramInfo
  1234. {
  1235. Audio = program.Audio,
  1236. ChannelId = program.ExternalChannelId,
  1237. CommunityRating = program.CommunityRating,
  1238. EndDate = program.EndDate ?? DateTime.MinValue,
  1239. EpisodeTitle = program.EpisodeTitle,
  1240. Genres = program.Genres,
  1241. HasImage = program.HasProviderImage,
  1242. Id = program.ExternalId,
  1243. IsHD = program.IsHD,
  1244. IsKids = program.IsKids,
  1245. IsLive = program.IsLive,
  1246. IsMovie = program.IsMovie,
  1247. IsNews = program.IsNews,
  1248. IsPremiere = program.IsPremiere,
  1249. IsRepeat = program.IsRepeat,
  1250. IsSeries = program.IsSeries,
  1251. IsSports = program.IsSports,
  1252. OriginalAirDate = program.PremiereDate,
  1253. Overview = program.Overview,
  1254. StartDate = program.StartDate,
  1255. ImagePath = program.ProviderImagePath,
  1256. ImageUrl = program.ProviderImageUrl,
  1257. Name = program.Name,
  1258. OfficialRating = program.OfficialRating
  1259. };
  1260. }
  1261. var info = await service.GetNewTimerDefaultsAsync(cancellationToken, programInfo).ConfigureAwait(false);
  1262. info.Id = null;
  1263. return new Tuple<SeriesTimerInfo, ILiveTvService>(info, service);
  1264. }
  1265. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(CancellationToken cancellationToken)
  1266. {
  1267. var info = await GetNewTimerDefaultsInternal(cancellationToken).ConfigureAwait(false);
  1268. var obj = _tvDtoService.GetSeriesTimerInfoDto(info.Item1, info.Item2, null);
  1269. return obj;
  1270. }
  1271. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(string programId, CancellationToken cancellationToken)
  1272. {
  1273. var program = GetInternalProgram(programId);
  1274. var programDto = await GetProgram(programId, cancellationToken).ConfigureAwait(false);
  1275. var defaults = await GetNewTimerDefaultsInternal(cancellationToken, program).ConfigureAwait(false);
  1276. var info = _tvDtoService.GetSeriesTimerInfoDto(defaults.Item1, defaults.Item2, null);
  1277. info.Days = new List<DayOfWeek>
  1278. {
  1279. program.StartDate.ToLocalTime().DayOfWeek
  1280. };
  1281. info.DayPattern = _tvDtoService.GetDayPattern(info.Days);
  1282. info.Name = program.Name;
  1283. info.ChannelId = programDto.ChannelId;
  1284. info.ChannelName = programDto.ChannelName;
  1285. info.StartDate = program.StartDate;
  1286. info.Name = program.Name;
  1287. info.Overview = program.Overview;
  1288. info.ProgramId = programDto.Id;
  1289. info.ExternalProgramId = programDto.ExternalId;
  1290. if (program.EndDate.HasValue)
  1291. {
  1292. info.EndDate = program.EndDate.Value;
  1293. }
  1294. return info;
  1295. }
  1296. public async Task CreateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  1297. {
  1298. var service = GetService(timer.ServiceName);
  1299. var info = await _tvDtoService.GetTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  1300. // Set priority from default values
  1301. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  1302. info.Priority = defaultValues.Priority;
  1303. await service.CreateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1304. }
  1305. public async Task CreateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  1306. {
  1307. var service = GetService(timer.ServiceName);
  1308. var info = await _tvDtoService.GetSeriesTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  1309. // Set priority from default values
  1310. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  1311. info.Priority = defaultValues.Priority;
  1312. await service.CreateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1313. }
  1314. public async Task UpdateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  1315. {
  1316. var info = await _tvDtoService.GetTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  1317. var service = GetService(timer.ServiceName);
  1318. await service.UpdateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1319. }
  1320. public async Task UpdateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  1321. {
  1322. var info = await _tvDtoService.GetSeriesTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  1323. var service = GetService(timer.ServiceName);
  1324. await service.UpdateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1325. }
  1326. private IEnumerable<string> GetRecordingGroupNames(RecordingInfo recording)
  1327. {
  1328. var list = new List<string>();
  1329. if (recording.IsSeries)
  1330. {
  1331. list.Add(recording.Name);
  1332. }
  1333. if (recording.IsKids)
  1334. {
  1335. list.Add("Kids");
  1336. }
  1337. if (recording.IsMovie)
  1338. {
  1339. list.Add("Movies");
  1340. }
  1341. if (recording.IsNews)
  1342. {
  1343. list.Add("News");
  1344. }
  1345. if (recording.IsSports)
  1346. {
  1347. list.Add("Sports");
  1348. }
  1349. if (!recording.IsSports && !recording.IsNews && !recording.IsMovie && !recording.IsKids && !recording.IsSeries)
  1350. {
  1351. list.Add("Others");
  1352. }
  1353. return list;
  1354. }
  1355. private List<Guid> GetRecordingGroupIds(RecordingInfo recording)
  1356. {
  1357. return GetRecordingGroupNames(recording).Select(i => i.ToLower()
  1358. .GetMD5())
  1359. .ToList();
  1360. }
  1361. public async Task<QueryResult<RecordingGroupDto>> GetRecordingGroups(RecordingGroupQuery query, CancellationToken cancellationToken)
  1362. {
  1363. var recordingResult = await GetRecordings(new RecordingQuery
  1364. {
  1365. UserId = query.UserId
  1366. }, cancellationToken).ConfigureAwait(false);
  1367. var recordings = recordingResult.Items;
  1368. var groups = new List<RecordingGroupDto>();
  1369. var series = recordings
  1370. .Where(i => i.IsSeries)
  1371. .ToLookup(i => i.Name, StringComparer.OrdinalIgnoreCase)
  1372. .ToList();
  1373. groups.AddRange(series.OrderByString(i => i.Key).Select(i => new RecordingGroupDto
  1374. {
  1375. Name = i.Key,
  1376. RecordingCount = i.Count()
  1377. }));
  1378. groups.Add(new RecordingGroupDto
  1379. {
  1380. Name = "Kids",
  1381. RecordingCount = recordings.Count(i => i.IsKids)
  1382. });
  1383. groups.Add(new RecordingGroupDto
  1384. {
  1385. Name = "Movies",
  1386. RecordingCount = recordings.Count(i => i.IsMovie)
  1387. });
  1388. groups.Add(new RecordingGroupDto
  1389. {
  1390. Name = "News",
  1391. RecordingCount = recordings.Count(i => i.IsNews)
  1392. });
  1393. groups.Add(new RecordingGroupDto
  1394. {
  1395. Name = "Sports",
  1396. RecordingCount = recordings.Count(i => i.IsSports)
  1397. });
  1398. groups.Add(new RecordingGroupDto
  1399. {
  1400. Name = "Others",
  1401. RecordingCount = recordings.Count(i => !i.IsSports && !i.IsNews && !i.IsMovie && !i.IsKids && !i.IsSeries)
  1402. });
  1403. groups = groups
  1404. .Where(i => i.RecordingCount > 0)
  1405. .ToList();
  1406. foreach (var group in groups)
  1407. {
  1408. group.Id = group.Name.ToLower().GetMD5().ToString("N");
  1409. }
  1410. return new QueryResult<RecordingGroupDto>
  1411. {
  1412. Items = groups.ToArray(),
  1413. TotalRecordCount = groups.Count
  1414. };
  1415. }
  1416. class LiveStreamData
  1417. {
  1418. internal MediaSourceInfo Info;
  1419. internal string ItemId;
  1420. internal bool IsChannel;
  1421. }
  1422. public async Task CloseLiveStream(string id, CancellationToken cancellationToken)
  1423. {
  1424. await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  1425. try
  1426. {
  1427. var parts = id.Split(new[] { '_' }, 2);
  1428. var service = _services.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N"), parts[0], StringComparison.OrdinalIgnoreCase));
  1429. if (service == null)
  1430. {
  1431. throw new ArgumentException("Service not found.");
  1432. }
  1433. id = parts[1];
  1434. LiveStreamData data;
  1435. _openStreams.TryRemove(id, out data);
  1436. _logger.Info("Closing live stream from {0}, stream Id: {1}", service.Name, id);
  1437. await service.CloseLiveStream(id, cancellationToken).ConfigureAwait(false);
  1438. }
  1439. catch (Exception ex)
  1440. {
  1441. _logger.ErrorException("Error closing live stream", ex);
  1442. throw;
  1443. }
  1444. finally
  1445. {
  1446. _liveStreamSemaphore.Release();
  1447. }
  1448. }
  1449. public GuideInfo GetGuideInfo()
  1450. {
  1451. var programs = _programs.ToList();
  1452. var startDate = _programs.Count == 0 ? DateTime.MinValue :
  1453. programs.Select(i => i.Value.StartDate).Min();
  1454. var endDate = programs.Count == 0 ? DateTime.MinValue :
  1455. programs.Select(i => i.Value.StartDate).Max();
  1456. return new GuideInfo
  1457. {
  1458. StartDate = startDate,
  1459. EndDate = endDate
  1460. };
  1461. }
  1462. /// <summary>
  1463. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1464. /// </summary>
  1465. public void Dispose()
  1466. {
  1467. Dispose(true);
  1468. }
  1469. private readonly object _disposeLock = new object();
  1470. /// <summary>
  1471. /// Releases unmanaged and - optionally - managed resources.
  1472. /// </summary>
  1473. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1474. protected virtual void Dispose(bool dispose)
  1475. {
  1476. if (dispose)
  1477. {
  1478. lock (_disposeLock)
  1479. {
  1480. foreach (var stream in _openStreams.Values.ToList())
  1481. {
  1482. var task = CloseLiveStream(stream.Info.Id, CancellationToken.None);
  1483. Task.WaitAll(task);
  1484. }
  1485. _openStreams.Clear();
  1486. }
  1487. }
  1488. }
  1489. private async Task<IEnumerable<LiveTvServiceInfo>> GetServiceInfos(CancellationToken cancellationToken)
  1490. {
  1491. var tasks = Services.Select(i => GetServiceInfo(i, cancellationToken));
  1492. return await Task.WhenAll(tasks).ConfigureAwait(false);
  1493. }
  1494. private async Task<LiveTvServiceInfo> GetServiceInfo(ILiveTvService service, CancellationToken cancellationToken)
  1495. {
  1496. var info = new LiveTvServiceInfo
  1497. {
  1498. Name = service.Name
  1499. };
  1500. var tunerIdPrefix = service.GetType().FullName.GetMD5().ToString("N") + "_";
  1501. try
  1502. {
  1503. var statusInfo = await service.GetStatusInfoAsync(cancellationToken).ConfigureAwait(false);
  1504. info.Status = statusInfo.Status;
  1505. info.StatusMessage = statusInfo.StatusMessage;
  1506. info.Version = statusInfo.Version;
  1507. info.HasUpdateAvailable = statusInfo.HasUpdateAvailable;
  1508. info.HomePageUrl = service.HomePageUrl;
  1509. info.Tuners = statusInfo.Tuners.Select(i =>
  1510. {
  1511. string channelName = null;
  1512. if (!string.IsNullOrEmpty(i.ChannelId))
  1513. {
  1514. var internalChannelId = _tvDtoService.GetInternalChannelId(service.Name, i.ChannelId);
  1515. var channel = GetInternalChannel(internalChannelId);
  1516. channelName = channel == null ? null : channel.Name;
  1517. }
  1518. var dto = _tvDtoService.GetTunerInfoDto(service.Name, i, channelName);
  1519. dto.Id = tunerIdPrefix + dto.Id;
  1520. return dto;
  1521. }).ToList();
  1522. }
  1523. catch (Exception ex)
  1524. {
  1525. _logger.ErrorException("Error getting service status info from {0}", ex, service.Name ?? string.Empty);
  1526. info.Status = LiveTvServiceStatus.Unavailable;
  1527. info.StatusMessage = ex.Message;
  1528. }
  1529. return info;
  1530. }
  1531. public async Task<LiveTvInfo> GetLiveTvInfo(CancellationToken cancellationToken)
  1532. {
  1533. var services = await GetServiceInfos(CancellationToken.None).ConfigureAwait(false);
  1534. var servicesList = services.ToList();
  1535. var info = new LiveTvInfo
  1536. {
  1537. Services = servicesList.ToList(),
  1538. IsEnabled = servicesList.Count > 0
  1539. };
  1540. info.EnabledUsers = _userManager.Users
  1541. .Where(IsLiveTvEnabled)
  1542. .Select(i => i.Id.ToString("N"))
  1543. .ToList();
  1544. return info;
  1545. }
  1546. private bool IsLiveTvEnabled(User user)
  1547. {
  1548. return user.Policy.EnableLiveTvAccess && Services.Count > 0;
  1549. }
  1550. public IEnumerable<User> GetEnabledUsers()
  1551. {
  1552. return _userManager.Users
  1553. .Where(IsLiveTvEnabled);
  1554. }
  1555. /// <summary>
  1556. /// Resets the tuner.
  1557. /// </summary>
  1558. /// <param name="id">The identifier.</param>
  1559. /// <param name="cancellationToken">The cancellation token.</param>
  1560. /// <returns>Task.</returns>
  1561. public Task ResetTuner(string id, CancellationToken cancellationToken)
  1562. {
  1563. var parts = id.Split(new[] { '_' }, 2);
  1564. var service = _services.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N"), parts[0], StringComparison.OrdinalIgnoreCase));
  1565. if (service == null)
  1566. {
  1567. throw new ArgumentException("Service not found.");
  1568. }
  1569. return service.ResetTuner(parts[1], cancellationToken);
  1570. }
  1571. public async Task<BaseItemDto> GetLiveTvFolder(string userId, CancellationToken cancellationToken)
  1572. {
  1573. var user = string.IsNullOrEmpty(userId) ? null : _userManager.GetUserById(userId);
  1574. var folder = await GetInternalLiveTvFolder(userId, cancellationToken).ConfigureAwait(false);
  1575. return _dtoService.GetBaseItemDto(folder, new DtoOptions(), user);
  1576. }
  1577. public async Task<Folder> GetInternalLiveTvFolder(string userId, CancellationToken cancellationToken)
  1578. {
  1579. var name = _localization.GetLocalizedString("ViewTypeLiveTV");
  1580. var user = _userManager.GetUserById(userId);
  1581. return await _libraryManager.GetNamedView(user, name, "livetv", "zz_" + name, cancellationToken).ConfigureAwait(false);
  1582. }
  1583. }
  1584. }