LiveTvManager.cs 72 KB

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