LiveTvManager.cs 72 KB

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