LiveTvManager.cs 71 KB

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