LiveTvManager.cs 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019
  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. .Distinct(StringComparer.OrdinalIgnoreCase)
  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. foreach (var program in _programs.Values
  808. .Where(i => (i.StartDate - DateTime.UtcNow).TotalDays <= 1)
  809. .ToList())
  810. {
  811. RefreshIfNeeded(program);
  812. }
  813. }
  814. finally
  815. {
  816. _refreshSemaphore.Release();
  817. }
  818. }
  819. private async Task RefreshChannelsInternal(IProgress<double> progress, CancellationToken cancellationToken)
  820. {
  821. var numComplete = 0;
  822. double progressPerService = _services.Count == 0
  823. ? 0
  824. : 1 / _services.Count;
  825. foreach (var service in _services)
  826. {
  827. cancellationToken.ThrowIfCancellationRequested();
  828. try
  829. {
  830. var innerProgress = new ActionableProgress<double>();
  831. innerProgress.RegisterAction(p => progress.Report(p * progressPerService));
  832. await RefreshChannelsInternal(service, innerProgress, cancellationToken).ConfigureAwait(false);
  833. }
  834. catch (OperationCanceledException)
  835. {
  836. throw;
  837. }
  838. catch (Exception ex)
  839. {
  840. _logger.ErrorException("Error refreshing channels for service", ex);
  841. }
  842. numComplete++;
  843. double percent = numComplete;
  844. percent /= _services.Count;
  845. progress.Report(100 * percent);
  846. }
  847. progress.Report(100);
  848. }
  849. private async Task RefreshChannelsInternal(ILiveTvService service, IProgress<double> progress, CancellationToken cancellationToken)
  850. {
  851. progress.Report(10);
  852. var allChannels = await GetChannels(service, cancellationToken).ConfigureAwait(false);
  853. var allChannelsList = allChannels.ToList();
  854. var list = new List<LiveTvChannel>();
  855. var numComplete = 0;
  856. foreach (var channelInfo in allChannelsList)
  857. {
  858. cancellationToken.ThrowIfCancellationRequested();
  859. try
  860. {
  861. var item = await GetChannel(channelInfo.Item2, channelInfo.Item1, cancellationToken).ConfigureAwait(false);
  862. list.Add(item);
  863. _libraryManager.RegisterItem(item);
  864. }
  865. catch (OperationCanceledException)
  866. {
  867. throw;
  868. }
  869. catch (Exception ex)
  870. {
  871. _logger.ErrorException("Error getting channel information for {0}", ex, channelInfo.Item2.Name);
  872. }
  873. numComplete++;
  874. double percent = numComplete;
  875. percent /= allChannelsList.Count;
  876. progress.Report(5 * percent + 10);
  877. }
  878. _channelIdList = list.Select(i => i.Id).ToList();
  879. progress.Report(15);
  880. numComplete = 0;
  881. var programs = new List<LiveTvProgram>();
  882. var guideDays = GetGuideDays(list.Count);
  883. cancellationToken.ThrowIfCancellationRequested();
  884. foreach (var item in list)
  885. {
  886. cancellationToken.ThrowIfCancellationRequested();
  887. // Avoid implicitly captured closure
  888. var currentChannel = item;
  889. try
  890. {
  891. var start = DateTime.UtcNow.AddHours(-1);
  892. var end = start.AddDays(guideDays);
  893. var channelPrograms = await service.GetProgramsAsync(currentChannel.ExternalId, start, end, cancellationToken).ConfigureAwait(false);
  894. foreach (var program in channelPrograms)
  895. {
  896. programs.Add(await GetProgram(program, currentChannel.ChannelType, service.Name, cancellationToken).ConfigureAwait(false));
  897. }
  898. }
  899. catch (OperationCanceledException)
  900. {
  901. throw;
  902. }
  903. catch (Exception ex)
  904. {
  905. _logger.ErrorException("Error getting programs for channel {0}", ex, currentChannel.Name);
  906. }
  907. numComplete++;
  908. double percent = numComplete;
  909. percent /= allChannelsList.Count;
  910. progress.Report(80 * percent + 10);
  911. }
  912. _programs = programs.ToDictionary(i => i.Id);
  913. _refreshedPrograms.Clear();
  914. progress.Report(90);
  915. // Load these now which will prefetch metadata
  916. await GetRecordings(new RecordingQuery(), cancellationToken).ConfigureAwait(false);
  917. progress.Report(100);
  918. }
  919. public async Task CleanDatabase(IProgress<double> progress, CancellationToken cancellationToken)
  920. {
  921. await _refreshSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  922. try
  923. {
  924. await DeleteOldPrograms(_programs.Keys.ToList(), progress, cancellationToken).ConfigureAwait(false);
  925. }
  926. finally
  927. {
  928. _refreshSemaphore.Release();
  929. }
  930. }
  931. private Task CleanDatabaseInternal(IProgress<double> progress, CancellationToken cancellationToken)
  932. {
  933. return DeleteOldPrograms(_programs.Keys.ToList(), progress, cancellationToken);
  934. }
  935. private async Task DeleteOldPrograms(List<Guid> currentIdList, IProgress<double> progress, CancellationToken cancellationToken)
  936. {
  937. var list = _itemRepo.GetItemsOfType(typeof(LiveTvProgram)).ToList();
  938. var numComplete = 0;
  939. foreach (var programId in list)
  940. {
  941. cancellationToken.ThrowIfCancellationRequested();
  942. if (!currentIdList.Contains(programId))
  943. {
  944. var program = _libraryManager.GetItemById(programId);
  945. if (program != null)
  946. {
  947. await _libraryManager.DeleteItem(program).ConfigureAwait(false);
  948. }
  949. }
  950. numComplete++;
  951. double percent = numComplete;
  952. percent /= list.Count;
  953. progress.Report(100 * percent);
  954. }
  955. }
  956. private double GetGuideDays(int channelCount)
  957. {
  958. var config = GetConfiguration();
  959. if (config.GuideDays.HasValue)
  960. {
  961. return config.GuideDays.Value;
  962. }
  963. var programsPerDay = channelCount * 48;
  964. const int maxPrograms = 24000;
  965. var days = Math.Round(((double)maxPrograms) / programsPerDay);
  966. // No less than 2, no more than 7
  967. return Math.Max(2, Math.Min(days, 7));
  968. }
  969. private async Task<IEnumerable<Tuple<string, ChannelInfo>>> GetChannels(ILiveTvService service, CancellationToken cancellationToken)
  970. {
  971. var channels = await service.GetChannelsAsync(cancellationToken).ConfigureAwait(false);
  972. return channels.Select(i => new Tuple<string, ChannelInfo>(service.Name, i));
  973. }
  974. public async Task<QueryResult<BaseItem>> GetInternalRecordings(RecordingQuery query, CancellationToken cancellationToken)
  975. {
  976. var tasks = _services.Select(async i =>
  977. {
  978. try
  979. {
  980. var recs = await i.GetRecordingsAsync(cancellationToken).ConfigureAwait(false);
  981. return recs.Select(r => new Tuple<RecordingInfo, ILiveTvService>(r, i));
  982. }
  983. catch (Exception ex)
  984. {
  985. _logger.ErrorException("Error getting recordings", ex);
  986. return new List<Tuple<RecordingInfo, ILiveTvService>>();
  987. }
  988. });
  989. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  990. var recordings = results.SelectMany(i => i.ToList());
  991. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  992. if (user != null && !IsLiveTvEnabled(user))
  993. {
  994. recordings = new List<Tuple<RecordingInfo, ILiveTvService>>();
  995. }
  996. if (!string.IsNullOrEmpty(query.ChannelId))
  997. {
  998. var guid = new Guid(query.ChannelId);
  999. recordings = recordings
  1000. .Where(i => _tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId) == guid);
  1001. }
  1002. if (!string.IsNullOrEmpty(query.Id))
  1003. {
  1004. var guid = new Guid(query.Id);
  1005. recordings = recordings
  1006. .Where(i => _tvDtoService.GetInternalRecordingId(i.Item2.Name, i.Item1.Id) == guid);
  1007. }
  1008. if (!string.IsNullOrEmpty(query.GroupId))
  1009. {
  1010. var guid = new Guid(query.GroupId);
  1011. recordings = recordings.Where(i => GetRecordingGroupIds(i.Item1).Contains(guid));
  1012. }
  1013. if (query.IsInProgress.HasValue)
  1014. {
  1015. var val = query.IsInProgress.Value;
  1016. recordings = recordings.Where(i => (i.Item1.Status == RecordingStatus.InProgress) == val);
  1017. }
  1018. if (query.Status.HasValue)
  1019. {
  1020. var val = query.Status.Value;
  1021. recordings = recordings.Where(i => (i.Item1.Status == val));
  1022. }
  1023. if (!string.IsNullOrEmpty(query.SeriesTimerId))
  1024. {
  1025. var guid = new Guid(query.SeriesTimerId);
  1026. recordings = recordings
  1027. .Where(i => _tvDtoService.GetInternalSeriesTimerId(i.Item2.Name, i.Item1.SeriesTimerId) == guid);
  1028. }
  1029. recordings = recordings.OrderByDescending(i => i.Item1.StartDate);
  1030. IEnumerable<ILiveTvRecording> entities = await GetEntities(recordings, cancellationToken).ConfigureAwait(false);
  1031. if (user != null)
  1032. {
  1033. var currentUser = user;
  1034. entities = entities.Where(i => i.IsParentalAllowed(currentUser));
  1035. }
  1036. var entityList = entities.ToList();
  1037. entities = entityList;
  1038. if (query.StartIndex.HasValue)
  1039. {
  1040. entities = entities.Skip(query.StartIndex.Value);
  1041. }
  1042. if (query.Limit.HasValue)
  1043. {
  1044. entities = entities.Take(query.Limit.Value);
  1045. }
  1046. return new QueryResult<BaseItem>
  1047. {
  1048. Items = entities.Cast<BaseItem>().ToArray(),
  1049. TotalRecordCount = entityList.Count
  1050. };
  1051. }
  1052. public async Task<QueryResult<RecordingInfoDto>> GetRecordings(RecordingQuery query, CancellationToken cancellationToken)
  1053. {
  1054. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  1055. var internalResult = await GetInternalRecordings(query, cancellationToken).ConfigureAwait(false);
  1056. var returnArray = internalResult.Items.Cast<ILiveTvRecording>()
  1057. .Select(i =>
  1058. {
  1059. var service = GetService(i);
  1060. var channel = string.IsNullOrEmpty(i.RecordingInfo.ChannelId) ? null : GetInternalChannel(_tvDtoService.GetInternalChannelId(service.Name, i.RecordingInfo.ChannelId));
  1061. return _tvDtoService.GetRecordingInfoDto(i, channel, service, user);
  1062. })
  1063. .ToArray();
  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 recording = await GetRecording(recordingId, CancellationToken.None).ConfigureAwait(false);
  1124. if (recording == null)
  1125. {
  1126. throw new ResourceNotFoundException(string.Format("Recording with Id {0} not found", recordingId));
  1127. }
  1128. var service = GetService(recording.ServiceName);
  1129. await service.DeleteRecordingAsync(recording.ExternalId, CancellationToken.None).ConfigureAwait(false);
  1130. }
  1131. public async Task CancelTimer(string id)
  1132. {
  1133. var timer = await GetTimer(id, CancellationToken.None).ConfigureAwait(false);
  1134. if (timer == null)
  1135. {
  1136. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  1137. }
  1138. var service = GetService(timer.ServiceName);
  1139. await service.CancelTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  1140. }
  1141. public async Task CancelSeriesTimer(string id)
  1142. {
  1143. var timer = await GetSeriesTimer(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.CancelSeriesTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  1150. }
  1151. public async Task<RecordingInfoDto> GetRecording(string id, CancellationToken cancellationToken, User user = null)
  1152. {
  1153. var results = await GetRecordings(new RecordingQuery
  1154. {
  1155. UserId = user == null ? null : user.Id.ToString("N"),
  1156. Id = id
  1157. }, cancellationToken).ConfigureAwait(false);
  1158. return results.Items.FirstOrDefault();
  1159. }
  1160. public async Task<TimerInfoDto> GetTimer(string id, CancellationToken cancellationToken)
  1161. {
  1162. var results = await GetTimers(new TimerQuery(), cancellationToken).ConfigureAwait(false);
  1163. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
  1164. }
  1165. public async Task<SeriesTimerInfoDto> GetSeriesTimer(string id, CancellationToken cancellationToken)
  1166. {
  1167. var results = await GetSeriesTimers(new SeriesTimerQuery(), cancellationToken).ConfigureAwait(false);
  1168. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
  1169. }
  1170. public async Task<QueryResult<SeriesTimerInfoDto>> GetSeriesTimers(SeriesTimerQuery query, CancellationToken cancellationToken)
  1171. {
  1172. var tasks = _services.Select(async i =>
  1173. {
  1174. try
  1175. {
  1176. var recs = await i.GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false);
  1177. return recs.Select(r => new Tuple<SeriesTimerInfo, ILiveTvService>(r, i));
  1178. }
  1179. catch (Exception ex)
  1180. {
  1181. _logger.ErrorException("Error getting recordings", ex);
  1182. return new List<Tuple<SeriesTimerInfo, ILiveTvService>>();
  1183. }
  1184. });
  1185. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  1186. var timers = results.SelectMany(i => i.ToList());
  1187. if (string.Equals(query.SortBy, "Priority", StringComparison.OrdinalIgnoreCase))
  1188. {
  1189. timers = query.SortOrder == SortOrder.Descending ?
  1190. timers.OrderBy(i => i.Item1.Priority).ThenByStringDescending(i => i.Item1.Name) :
  1191. timers.OrderByDescending(i => i.Item1.Priority).ThenByString(i => i.Item1.Name);
  1192. }
  1193. else
  1194. {
  1195. timers = query.SortOrder == SortOrder.Descending ?
  1196. timers.OrderByStringDescending(i => i.Item1.Name) :
  1197. timers.OrderByString(i => i.Item1.Name);
  1198. }
  1199. var returnArray = timers
  1200. .Select(i =>
  1201. {
  1202. string channelName = null;
  1203. if (!string.IsNullOrEmpty(i.Item1.ChannelId))
  1204. {
  1205. var internalChannelId = _tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId);
  1206. var channel = GetInternalChannel(internalChannelId);
  1207. channelName = channel == null ? null : channel.Name;
  1208. }
  1209. return _tvDtoService.GetSeriesTimerInfoDto(i.Item1, i.Item2, channelName);
  1210. })
  1211. .ToArray();
  1212. return new QueryResult<SeriesTimerInfoDto>
  1213. {
  1214. Items = returnArray,
  1215. TotalRecordCount = returnArray.Length
  1216. };
  1217. }
  1218. public async Task<ChannelInfoDto> GetChannel(string id, CancellationToken cancellationToken, User user = null)
  1219. {
  1220. var channel = GetInternalChannel(id);
  1221. var currentProgram = GetCurrentProgram(channel.ExternalId);
  1222. var dto = _tvDtoService.GetChannelInfoDto(channel, currentProgram, user);
  1223. return dto;
  1224. }
  1225. private LiveTvProgram GetCurrentProgram(string externalChannelId)
  1226. {
  1227. var now = DateTime.UtcNow;
  1228. var program = _programs.Values
  1229. .Where(i => string.Equals(externalChannelId, i.ExternalChannelId, StringComparison.OrdinalIgnoreCase))
  1230. .OrderBy(i => i.StartDate)
  1231. .SkipWhile(i => now >= (i.EndDate ?? DateTime.MinValue))
  1232. .FirstOrDefault();
  1233. if (program != null)
  1234. {
  1235. RefreshIfNeeded(program);
  1236. }
  1237. return program;
  1238. }
  1239. private async Task<Tuple<SeriesTimerInfo, ILiveTvService>> GetNewTimerDefaultsInternal(CancellationToken cancellationToken, LiveTvProgram program = null)
  1240. {
  1241. var service = program != null && !string.IsNullOrWhiteSpace(program.ServiceName) ?
  1242. GetService(program) :
  1243. _services.FirstOrDefault();
  1244. ProgramInfo programInfo = null;
  1245. if (program != null)
  1246. {
  1247. programInfo = new ProgramInfo
  1248. {
  1249. Audio = program.Audio,
  1250. ChannelId = program.ExternalChannelId,
  1251. CommunityRating = program.CommunityRating,
  1252. EndDate = program.EndDate ?? DateTime.MinValue,
  1253. EpisodeTitle = program.EpisodeTitle,
  1254. Genres = program.Genres,
  1255. HasImage = program.HasProviderImage,
  1256. Id = program.ExternalId,
  1257. IsHD = program.IsHD,
  1258. IsKids = program.IsKids,
  1259. IsLive = program.IsLive,
  1260. IsMovie = program.IsMovie,
  1261. IsNews = program.IsNews,
  1262. IsPremiere = program.IsPremiere,
  1263. IsRepeat = program.IsRepeat,
  1264. IsSeries = program.IsSeries,
  1265. IsSports = program.IsSports,
  1266. OriginalAirDate = program.PremiereDate,
  1267. Overview = program.Overview,
  1268. StartDate = program.StartDate,
  1269. ImagePath = program.ProviderImagePath,
  1270. ImageUrl = program.ProviderImageUrl,
  1271. Name = program.Name,
  1272. OfficialRating = program.OfficialRating
  1273. };
  1274. }
  1275. var info = await service.GetNewTimerDefaultsAsync(cancellationToken, programInfo).ConfigureAwait(false);
  1276. info.Id = null;
  1277. return new Tuple<SeriesTimerInfo, ILiveTvService>(info, service);
  1278. }
  1279. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(CancellationToken cancellationToken)
  1280. {
  1281. var info = await GetNewTimerDefaultsInternal(cancellationToken).ConfigureAwait(false);
  1282. var obj = _tvDtoService.GetSeriesTimerInfoDto(info.Item1, info.Item2, null);
  1283. return obj;
  1284. }
  1285. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(string programId, CancellationToken cancellationToken)
  1286. {
  1287. var program = GetInternalProgram(programId);
  1288. var programDto = await GetProgram(programId, cancellationToken).ConfigureAwait(false);
  1289. var defaults = await GetNewTimerDefaultsInternal(cancellationToken, program).ConfigureAwait(false);
  1290. var info = _tvDtoService.GetSeriesTimerInfoDto(defaults.Item1, defaults.Item2, null);
  1291. info.Days = new List<DayOfWeek>
  1292. {
  1293. program.StartDate.ToLocalTime().DayOfWeek
  1294. };
  1295. info.DayPattern = _tvDtoService.GetDayPattern(info.Days);
  1296. info.Name = program.Name;
  1297. info.ChannelId = programDto.ChannelId;
  1298. info.ChannelName = programDto.ChannelName;
  1299. info.StartDate = program.StartDate;
  1300. info.Name = program.Name;
  1301. info.Overview = program.Overview;
  1302. info.ProgramId = programDto.Id;
  1303. info.ExternalProgramId = programDto.ExternalId;
  1304. if (program.EndDate.HasValue)
  1305. {
  1306. info.EndDate = program.EndDate.Value;
  1307. }
  1308. return info;
  1309. }
  1310. public async Task CreateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  1311. {
  1312. var service = GetService(timer.ServiceName);
  1313. var info = await _tvDtoService.GetTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  1314. // Set priority from default values
  1315. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  1316. info.Priority = defaultValues.Priority;
  1317. await service.CreateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1318. }
  1319. public async Task CreateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  1320. {
  1321. var service = GetService(timer.ServiceName);
  1322. var info = await _tvDtoService.GetSeriesTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  1323. // Set priority from default values
  1324. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  1325. info.Priority = defaultValues.Priority;
  1326. await service.CreateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1327. }
  1328. public async Task UpdateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  1329. {
  1330. var info = await _tvDtoService.GetTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  1331. var service = GetService(timer.ServiceName);
  1332. await service.UpdateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1333. }
  1334. public async Task UpdateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  1335. {
  1336. var info = await _tvDtoService.GetSeriesTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  1337. var service = GetService(timer.ServiceName);
  1338. await service.UpdateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1339. }
  1340. private IEnumerable<string> GetRecordingGroupNames(RecordingInfo recording)
  1341. {
  1342. var list = new List<string>();
  1343. if (recording.IsSeries)
  1344. {
  1345. list.Add(recording.Name);
  1346. }
  1347. if (recording.IsKids)
  1348. {
  1349. list.Add("Kids");
  1350. }
  1351. if (recording.IsMovie)
  1352. {
  1353. list.Add("Movies");
  1354. }
  1355. if (recording.IsNews)
  1356. {
  1357. list.Add("News");
  1358. }
  1359. if (recording.IsSports)
  1360. {
  1361. list.Add("Sports");
  1362. }
  1363. if (!recording.IsSports && !recording.IsNews && !recording.IsMovie && !recording.IsKids && !recording.IsSeries)
  1364. {
  1365. list.Add("Others");
  1366. }
  1367. return list;
  1368. }
  1369. private List<Guid> GetRecordingGroupIds(RecordingInfo recording)
  1370. {
  1371. return GetRecordingGroupNames(recording).Select(i => i.ToLower()
  1372. .GetMD5())
  1373. .ToList();
  1374. }
  1375. public async Task<QueryResult<RecordingGroupDto>> GetRecordingGroups(RecordingGroupQuery query, CancellationToken cancellationToken)
  1376. {
  1377. var recordingResult = await GetRecordings(new RecordingQuery
  1378. {
  1379. UserId = query.UserId
  1380. }, cancellationToken).ConfigureAwait(false);
  1381. var recordings = recordingResult.Items;
  1382. var groups = new List<RecordingGroupDto>();
  1383. var series = recordings
  1384. .Where(i => i.IsSeries)
  1385. .ToLookup(i => i.Name, StringComparer.OrdinalIgnoreCase)
  1386. .ToList();
  1387. groups.AddRange(series.OrderByString(i => i.Key).Select(i => new RecordingGroupDto
  1388. {
  1389. Name = i.Key,
  1390. RecordingCount = i.Count()
  1391. }));
  1392. groups.Add(new RecordingGroupDto
  1393. {
  1394. Name = "Kids",
  1395. RecordingCount = recordings.Count(i => i.IsKids)
  1396. });
  1397. groups.Add(new RecordingGroupDto
  1398. {
  1399. Name = "Movies",
  1400. RecordingCount = recordings.Count(i => i.IsMovie)
  1401. });
  1402. groups.Add(new RecordingGroupDto
  1403. {
  1404. Name = "News",
  1405. RecordingCount = recordings.Count(i => i.IsNews)
  1406. });
  1407. groups.Add(new RecordingGroupDto
  1408. {
  1409. Name = "Sports",
  1410. RecordingCount = recordings.Count(i => i.IsSports)
  1411. });
  1412. groups.Add(new RecordingGroupDto
  1413. {
  1414. Name = "Others",
  1415. RecordingCount = recordings.Count(i => !i.IsSports && !i.IsNews && !i.IsMovie && !i.IsKids && !i.IsSeries)
  1416. });
  1417. groups = groups
  1418. .Where(i => i.RecordingCount > 0)
  1419. .ToList();
  1420. foreach (var group in groups)
  1421. {
  1422. group.Id = group.Name.ToLower().GetMD5().ToString("N");
  1423. }
  1424. return new QueryResult<RecordingGroupDto>
  1425. {
  1426. Items = groups.ToArray(),
  1427. TotalRecordCount = groups.Count
  1428. };
  1429. }
  1430. class LiveStreamData
  1431. {
  1432. internal MediaSourceInfo Info;
  1433. internal string ItemId;
  1434. internal bool IsChannel;
  1435. }
  1436. public async Task CloseLiveStream(string id, CancellationToken cancellationToken)
  1437. {
  1438. await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  1439. try
  1440. {
  1441. var parts = id.Split(new[] { '_' }, 2);
  1442. var service = _services.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N"), parts[0], StringComparison.OrdinalIgnoreCase));
  1443. if (service == null)
  1444. {
  1445. throw new ArgumentException("Service not found.");
  1446. }
  1447. id = parts[1];
  1448. LiveStreamData data;
  1449. _openStreams.TryRemove(id, out data);
  1450. _logger.Info("Closing live stream from {0}, stream Id: {1}", service.Name, id);
  1451. await service.CloseLiveStream(id, cancellationToken).ConfigureAwait(false);
  1452. }
  1453. catch (Exception ex)
  1454. {
  1455. _logger.ErrorException("Error closing live stream", ex);
  1456. throw;
  1457. }
  1458. finally
  1459. {
  1460. _liveStreamSemaphore.Release();
  1461. }
  1462. }
  1463. public GuideInfo GetGuideInfo()
  1464. {
  1465. var programs = _programs.ToList();
  1466. var startDate = _programs.Count == 0 ? DateTime.MinValue :
  1467. programs.Select(i => i.Value.StartDate).Min();
  1468. var endDate = programs.Count == 0 ? DateTime.MinValue :
  1469. programs.Select(i => i.Value.StartDate).Max();
  1470. return new GuideInfo
  1471. {
  1472. StartDate = startDate,
  1473. EndDate = endDate
  1474. };
  1475. }
  1476. /// <summary>
  1477. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1478. /// </summary>
  1479. public void Dispose()
  1480. {
  1481. Dispose(true);
  1482. }
  1483. private readonly object _disposeLock = new object();
  1484. /// <summary>
  1485. /// Releases unmanaged and - optionally - managed resources.
  1486. /// </summary>
  1487. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1488. protected virtual void Dispose(bool dispose)
  1489. {
  1490. if (dispose)
  1491. {
  1492. lock (_disposeLock)
  1493. {
  1494. foreach (var stream in _openStreams.Values.ToList())
  1495. {
  1496. var task = CloseLiveStream(stream.Info.Id, CancellationToken.None);
  1497. Task.WaitAll(task);
  1498. }
  1499. _openStreams.Clear();
  1500. }
  1501. }
  1502. }
  1503. private async Task<IEnumerable<LiveTvServiceInfo>> GetServiceInfos(CancellationToken cancellationToken)
  1504. {
  1505. var tasks = Services.Select(i => GetServiceInfo(i, cancellationToken));
  1506. return await Task.WhenAll(tasks).ConfigureAwait(false);
  1507. }
  1508. private async Task<LiveTvServiceInfo> GetServiceInfo(ILiveTvService service, CancellationToken cancellationToken)
  1509. {
  1510. var info = new LiveTvServiceInfo
  1511. {
  1512. Name = service.Name
  1513. };
  1514. var tunerIdPrefix = service.GetType().FullName.GetMD5().ToString("N") + "_";
  1515. try
  1516. {
  1517. var statusInfo = await service.GetStatusInfoAsync(cancellationToken).ConfigureAwait(false);
  1518. info.Status = statusInfo.Status;
  1519. info.StatusMessage = statusInfo.StatusMessage;
  1520. info.Version = statusInfo.Version;
  1521. info.HasUpdateAvailable = statusInfo.HasUpdateAvailable;
  1522. info.HomePageUrl = service.HomePageUrl;
  1523. info.Tuners = statusInfo.Tuners.Select(i =>
  1524. {
  1525. string channelName = null;
  1526. if (!string.IsNullOrEmpty(i.ChannelId))
  1527. {
  1528. var internalChannelId = _tvDtoService.GetInternalChannelId(service.Name, i.ChannelId);
  1529. var channel = GetInternalChannel(internalChannelId);
  1530. channelName = channel == null ? null : channel.Name;
  1531. }
  1532. var dto = _tvDtoService.GetTunerInfoDto(service.Name, i, channelName);
  1533. dto.Id = tunerIdPrefix + dto.Id;
  1534. return dto;
  1535. }).ToList();
  1536. }
  1537. catch (Exception ex)
  1538. {
  1539. _logger.ErrorException("Error getting service status info from {0}", ex, service.Name ?? string.Empty);
  1540. info.Status = LiveTvServiceStatus.Unavailable;
  1541. info.StatusMessage = ex.Message;
  1542. }
  1543. return info;
  1544. }
  1545. public async Task<LiveTvInfo> GetLiveTvInfo(CancellationToken cancellationToken)
  1546. {
  1547. var services = await GetServiceInfos(CancellationToken.None).ConfigureAwait(false);
  1548. var servicesList = services.ToList();
  1549. var info = new LiveTvInfo
  1550. {
  1551. Services = servicesList.ToList(),
  1552. IsEnabled = servicesList.Count > 0
  1553. };
  1554. info.EnabledUsers = _userManager.Users
  1555. .Where(IsLiveTvEnabled)
  1556. .Select(i => i.Id.ToString("N"))
  1557. .ToList();
  1558. return info;
  1559. }
  1560. private bool IsLiveTvEnabled(User user)
  1561. {
  1562. return user.Policy.EnableLiveTvAccess && Services.Count > 0;
  1563. }
  1564. public IEnumerable<User> GetEnabledUsers()
  1565. {
  1566. return _userManager.Users
  1567. .Where(IsLiveTvEnabled);
  1568. }
  1569. /// <summary>
  1570. /// Resets the tuner.
  1571. /// </summary>
  1572. /// <param name="id">The identifier.</param>
  1573. /// <param name="cancellationToken">The cancellation token.</param>
  1574. /// <returns>Task.</returns>
  1575. public Task ResetTuner(string id, CancellationToken cancellationToken)
  1576. {
  1577. var parts = id.Split(new[] { '_' }, 2);
  1578. var service = _services.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N"), parts[0], StringComparison.OrdinalIgnoreCase));
  1579. if (service == null)
  1580. {
  1581. throw new ArgumentException("Service not found.");
  1582. }
  1583. return service.ResetTuner(parts[1], cancellationToken);
  1584. }
  1585. public async Task<BaseItemDto> GetLiveTvFolder(string userId, CancellationToken cancellationToken)
  1586. {
  1587. var user = string.IsNullOrEmpty(userId) ? null : _userManager.GetUserById(userId);
  1588. var folder = await GetInternalLiveTvFolder(userId, cancellationToken).ConfigureAwait(false);
  1589. return _dtoService.GetBaseItemDto(folder, new DtoOptions(), user);
  1590. }
  1591. public async Task<Folder> GetInternalLiveTvFolder(string userId, CancellationToken cancellationToken)
  1592. {
  1593. var name = _localization.GetLocalizedString("ViewTypeLiveTV");
  1594. var user = _userManager.GetUserById(userId);
  1595. return await _libraryManager.GetNamedView(user, name, "livetv", "zz_" + name, cancellationToken).ConfigureAwait(false);
  1596. }
  1597. }
  1598. }