LiveTvManager.cs 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.ScheduledTasks;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Drawing;
  6. using MediaBrowser.Controller.Dto;
  7. using MediaBrowser.Controller.Entities;
  8. using MediaBrowser.Controller.Library;
  9. using MediaBrowser.Controller.LiveTv;
  10. using MediaBrowser.Controller.MediaInfo;
  11. using MediaBrowser.Controller.Persistence;
  12. using MediaBrowser.Controller.Sorting;
  13. using MediaBrowser.Model.Entities;
  14. using MediaBrowser.Model.LiveTv;
  15. using MediaBrowser.Model.Logging;
  16. using MediaBrowser.Model.Querying;
  17. using System;
  18. using System.Collections.Concurrent;
  19. using System.Collections.Generic;
  20. using System.IO;
  21. using System.Linq;
  22. using System.Threading;
  23. using System.Threading.Tasks;
  24. namespace MediaBrowser.Server.Implementations.LiveTv
  25. {
  26. /// <summary>
  27. /// Class LiveTvManager
  28. /// </summary>
  29. public class LiveTvManager : ILiveTvManager, IDisposable
  30. {
  31. private readonly IServerConfigurationManager _config;
  32. private readonly IFileSystem _fileSystem;
  33. private readonly ILogger _logger;
  34. private readonly IItemRepository _itemRepo;
  35. private readonly IUserManager _userManager;
  36. private readonly IUserDataManager _userDataManager;
  37. private readonly ILibraryManager _libraryManager;
  38. private readonly IMediaEncoder _mediaEncoder;
  39. private readonly ITaskManager _taskManager;
  40. private readonly LiveTvDtoService _tvDtoService;
  41. private readonly List<ILiveTvService> _services = new List<ILiveTvService>();
  42. private readonly ConcurrentDictionary<string, LiveStreamInfo> _openStreams =
  43. new ConcurrentDictionary<string, LiveStreamInfo>();
  44. private List<Guid> _channelIdList = new List<Guid>();
  45. private Dictionary<Guid, LiveTvProgram> _programs = new Dictionary<Guid, LiveTvProgram>();
  46. public LiveTvManager(IServerConfigurationManager config, IFileSystem fileSystem, ILogger logger, IItemRepository itemRepo, IImageProcessor imageProcessor, IUserDataManager userDataManager, IDtoService dtoService, IUserManager userManager, ILibraryManager libraryManager, IMediaEncoder mediaEncoder, ITaskManager taskManager)
  47. {
  48. _config = config;
  49. _fileSystem = fileSystem;
  50. _logger = logger;
  51. _itemRepo = itemRepo;
  52. _userManager = userManager;
  53. _libraryManager = libraryManager;
  54. _mediaEncoder = mediaEncoder;
  55. _taskManager = taskManager;
  56. _userDataManager = userDataManager;
  57. _tvDtoService = new LiveTvDtoService(dtoService, userDataManager, imageProcessor, logger, _itemRepo);
  58. }
  59. /// <summary>
  60. /// Gets the services.
  61. /// </summary>
  62. /// <value>The services.</value>
  63. public IReadOnlyList<ILiveTvService> Services
  64. {
  65. get { return _services; }
  66. }
  67. public ILiveTvService ActiveService { get; private set; }
  68. /// <summary>
  69. /// Adds the parts.
  70. /// </summary>
  71. /// <param name="services">The services.</param>
  72. public void AddParts(IEnumerable<ILiveTvService> services)
  73. {
  74. _services.AddRange(services);
  75. SetActiveService(_services.FirstOrDefault());
  76. }
  77. private void SetActiveService(ILiveTvService service)
  78. {
  79. if (ActiveService != null)
  80. {
  81. ActiveService.DataSourceChanged -= service_DataSourceChanged;
  82. }
  83. ActiveService = service;
  84. if (service != null)
  85. {
  86. service.DataSourceChanged += service_DataSourceChanged;
  87. }
  88. }
  89. void service_DataSourceChanged(object sender, EventArgs e)
  90. {
  91. _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
  92. }
  93. public Task<QueryResult<ChannelInfoDto>> GetChannels(ChannelQuery query, CancellationToken cancellationToken)
  94. {
  95. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(new Guid(query.UserId));
  96. var channels = _channelIdList.Select(_libraryManager.GetItemById)
  97. .Where(i => i != null)
  98. .OfType<LiveTvChannel>();
  99. if (user != null)
  100. {
  101. // Avoid implicitly captured closure
  102. var currentUser = user;
  103. channels = channels
  104. .Where(i => i.IsParentalAllowed(currentUser))
  105. .OrderBy(i =>
  106. {
  107. double number = 0;
  108. if (!string.IsNullOrEmpty(i.Number))
  109. {
  110. double.TryParse(i.Number, out number);
  111. }
  112. return number;
  113. });
  114. }
  115. channels = channels.OrderBy(i =>
  116. {
  117. double number = 0;
  118. if (!string.IsNullOrEmpty(i.Number))
  119. {
  120. double.TryParse(i.Number, out number);
  121. }
  122. return number;
  123. }).ThenBy(i => i.Name);
  124. var allChannels = channels.ToList();
  125. IEnumerable<LiveTvChannel> allEnumerable = allChannels;
  126. if (query.StartIndex.HasValue)
  127. {
  128. allEnumerable = allEnumerable.Skip(query.StartIndex.Value);
  129. }
  130. if (query.Limit.HasValue)
  131. {
  132. allEnumerable = allEnumerable.Take(query.Limit.Value);
  133. }
  134. var returnChannels = allEnumerable
  135. .Select(i => _tvDtoService.GetChannelInfoDto(i, GetCurrentProgram(i.ExternalId), user))
  136. .ToArray();
  137. var result = new QueryResult<ChannelInfoDto>
  138. {
  139. Items = returnChannels,
  140. TotalRecordCount = allChannels.Count
  141. };
  142. return Task.FromResult(result);
  143. }
  144. public LiveTvChannel GetInternalChannel(string id)
  145. {
  146. return GetInternalChannel(new Guid(id));
  147. }
  148. private LiveTvChannel GetInternalChannel(Guid id)
  149. {
  150. return _libraryManager.GetItemById(id) as LiveTvChannel;
  151. }
  152. public LiveTvProgram GetInternalProgram(string id)
  153. {
  154. var guid = new Guid(id);
  155. LiveTvProgram obj = null;
  156. _programs.TryGetValue(guid, out obj);
  157. return obj;
  158. }
  159. public async Task<ILiveTvRecording> GetInternalRecording(string id, CancellationToken cancellationToken)
  160. {
  161. var service = ActiveService;
  162. var recordings = await service.GetRecordingsAsync(cancellationToken).ConfigureAwait(false);
  163. var recording = recordings.FirstOrDefault(i => _tvDtoService.GetInternalRecordingId(service.Name, i.Id) == new Guid(id));
  164. return await GetRecording(recording, service.Name, cancellationToken).ConfigureAwait(false);
  165. }
  166. private readonly SemaphoreSlim _liveStreamSemaphore = new SemaphoreSlim(1, 1);
  167. public async Task<LiveStreamInfo> GetRecordingStream(string id, CancellationToken cancellationToken)
  168. {
  169. await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  170. try
  171. {
  172. var service = ActiveService;
  173. var recordings = await service.GetRecordingsAsync(cancellationToken).ConfigureAwait(false);
  174. var recording = recordings.First(i => _tvDtoService.GetInternalRecordingId(service.Name, i.Id) == new Guid(id));
  175. var result = await service.GetRecordingStream(recording.Id, cancellationToken).ConfigureAwait(false);
  176. if (!string.IsNullOrEmpty(result.Id))
  177. {
  178. _openStreams.AddOrUpdate(result.Id, result, (key, info) => result);
  179. }
  180. return result;
  181. }
  182. catch (Exception ex)
  183. {
  184. _logger.ErrorException("Error getting recording stream", ex);
  185. throw;
  186. }
  187. finally
  188. {
  189. _liveStreamSemaphore.Release();
  190. }
  191. }
  192. public async Task<LiveStreamInfo> GetChannelStream(string id, CancellationToken cancellationToken)
  193. {
  194. await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  195. try
  196. {
  197. var service = ActiveService;
  198. var channel = GetInternalChannel(id);
  199. _logger.Info("Opening channel stream from {0}, external channel Id: {1}", service.Name, channel.ExternalId);
  200. var result = await service.GetChannelStream(channel.ExternalId, cancellationToken).ConfigureAwait(false);
  201. if (!string.IsNullOrEmpty(result.Id))
  202. {
  203. _openStreams.AddOrUpdate(result.Id, result, (key, info) => result);
  204. }
  205. return result;
  206. }
  207. catch (Exception ex)
  208. {
  209. _logger.ErrorException("Error getting channel stream", ex);
  210. throw;
  211. }
  212. finally
  213. {
  214. _liveStreamSemaphore.Release();
  215. }
  216. }
  217. private async Task<LiveTvChannel> GetChannel(ChannelInfo channelInfo, string serviceName, CancellationToken cancellationToken)
  218. {
  219. var path = Path.Combine(_config.ApplicationPaths.ItemsByNamePath, "channels", _fileSystem.GetValidFilename(channelInfo.Name));
  220. var fileInfo = new DirectoryInfo(path);
  221. var isNew = false;
  222. if (!fileInfo.Exists)
  223. {
  224. Directory.CreateDirectory(path);
  225. fileInfo = new DirectoryInfo(path);
  226. if (!fileInfo.Exists)
  227. {
  228. throw new IOException("Path not created: " + path);
  229. }
  230. isNew = true;
  231. }
  232. var id = _tvDtoService.GetInternalChannelId(serviceName, channelInfo.Id);
  233. var item = _itemRepo.RetrieveItem(id) as LiveTvChannel;
  234. if (item == null)
  235. {
  236. item = new LiveTvChannel
  237. {
  238. Name = channelInfo.Name,
  239. Id = id,
  240. DateCreated = _fileSystem.GetCreationTimeUtc(fileInfo),
  241. DateModified = _fileSystem.GetLastWriteTimeUtc(fileInfo),
  242. Path = path
  243. };
  244. isNew = true;
  245. }
  246. item.ChannelType = channelInfo.ChannelType;
  247. item.ProviderImageUrl = channelInfo.ImageUrl;
  248. item.HasProviderImage = channelInfo.HasImage;
  249. item.ProviderImagePath = channelInfo.ImagePath;
  250. item.ExternalId = channelInfo.Id;
  251. item.ServiceName = serviceName;
  252. item.Number = channelInfo.Number;
  253. if (string.IsNullOrEmpty(item.Name))
  254. {
  255. item.Name = channelInfo.Name;
  256. }
  257. // Set this now so we don't cause additional file system access during provider executions
  258. item.ResetResolveArgs(fileInfo);
  259. await item.RefreshMetadata(cancellationToken, forceSave: isNew, resetResolveArgs: false);
  260. return item;
  261. }
  262. private async Task<LiveTvProgram> GetProgram(ProgramInfo info, ChannelType channelType, string serviceName, CancellationToken cancellationToken)
  263. {
  264. var isNew = false;
  265. var id = _tvDtoService.GetInternalProgramId(serviceName, info.Id);
  266. var item = _itemRepo.RetrieveItem(id) as LiveTvProgram;
  267. if (item == null)
  268. {
  269. item = new LiveTvProgram
  270. {
  271. Name = info.Name,
  272. Id = id,
  273. DateCreated = DateTime.UtcNow,
  274. DateModified = DateTime.UtcNow
  275. };
  276. isNew = true;
  277. }
  278. item.ChannelType = channelType;
  279. item.ServiceName = serviceName;
  280. item.Audio = info.Audio;
  281. item.ExternalChannelId = info.ChannelId;
  282. item.CommunityRating = info.CommunityRating;
  283. item.EndDate = info.EndDate;
  284. item.EpisodeTitle = info.EpisodeTitle;
  285. item.ExternalId = info.Id;
  286. item.Genres = info.Genres;
  287. item.HasProviderImage = info.HasImage;
  288. item.IsHD = info.IsHD;
  289. item.IsKids = info.IsKids;
  290. item.IsLive = info.IsLive;
  291. item.IsMovie = info.IsMovie;
  292. item.IsNews = info.IsNews;
  293. item.IsPremiere = info.IsPremiere;
  294. item.IsRepeat = info.IsRepeat;
  295. item.IsSeries = info.IsSeries;
  296. item.IsSports = info.IsSports;
  297. item.Name = info.Name;
  298. item.OfficialRating = info.OfficialRating;
  299. item.Overview = info.Overview;
  300. item.PremiereDate = info.OriginalAirDate;
  301. item.ProviderImagePath = info.ImagePath;
  302. item.ProviderImageUrl = info.ImageUrl;
  303. item.RunTimeTicks = (info.EndDate - info.StartDate).Ticks;
  304. item.StartDate = info.StartDate;
  305. await item.RefreshMetadata(cancellationToken, forceSave: isNew, resetResolveArgs: false);
  306. return item;
  307. }
  308. private async Task<ILiveTvRecording> GetRecording(RecordingInfo info, string serviceName, CancellationToken cancellationToken)
  309. {
  310. var isNew = false;
  311. var id = _tvDtoService.GetInternalRecordingId(serviceName, info.Id);
  312. var item = _itemRepo.RetrieveItem(id) as ILiveTvRecording;
  313. if (item == null)
  314. {
  315. if (info.ChannelType == ChannelType.TV)
  316. {
  317. item = new LiveTvVideoRecording
  318. {
  319. Name = info.Name,
  320. Id = id,
  321. DateCreated = DateTime.UtcNow,
  322. DateModified = DateTime.UtcNow,
  323. VideoType = VideoType.VideoFile
  324. };
  325. }
  326. else
  327. {
  328. item = new LiveTvAudioRecording
  329. {
  330. Name = info.Name,
  331. Id = id,
  332. DateCreated = DateTime.UtcNow,
  333. DateModified = DateTime.UtcNow
  334. };
  335. }
  336. if (!string.IsNullOrEmpty(info.Path))
  337. {
  338. item.Path = info.Path;
  339. }
  340. else if (!string.IsNullOrEmpty(info.Url))
  341. {
  342. item.Path = info.Url;
  343. }
  344. isNew = true;
  345. }
  346. item.RecordingInfo = info;
  347. item.ServiceName = serviceName;
  348. await item.RefreshMetadata(cancellationToken, forceSave: isNew, resetResolveArgs: false);
  349. _libraryManager.RegisterItem((BaseItem)item);
  350. return item;
  351. }
  352. private LiveTvChannel GetChannel(LiveTvProgram program)
  353. {
  354. var programChannelId = program.ExternalChannelId;
  355. var internalProgramChannelId = _tvDtoService.GetInternalChannelId(program.ServiceName, programChannelId);
  356. return GetInternalChannel(internalProgramChannelId);
  357. }
  358. public async Task<ProgramInfoDto> GetProgram(string id, CancellationToken cancellationToken, User user = null)
  359. {
  360. var program = GetInternalProgram(id);
  361. var channel = GetChannel(program);
  362. var dto = _tvDtoService.GetProgramInfoDto(program, channel, user);
  363. await AddRecordingInfo(new[] { dto }, cancellationToken).ConfigureAwait(false);
  364. return dto;
  365. }
  366. public async Task<QueryResult<ProgramInfoDto>> GetPrograms(ProgramQuery query, CancellationToken cancellationToken)
  367. {
  368. IEnumerable<LiveTvProgram> programs = _programs.Values;
  369. if (query.MinEndDate.HasValue)
  370. {
  371. var val = query.MinEndDate.Value;
  372. programs = programs.Where(i => i.EndDate.HasValue && i.EndDate.Value >= val);
  373. }
  374. if (query.MinStartDate.HasValue)
  375. {
  376. var val = query.MinStartDate.Value;
  377. programs = programs.Where(i => i.StartDate >= val);
  378. }
  379. if (query.MaxEndDate.HasValue)
  380. {
  381. var val = query.MaxEndDate.Value;
  382. programs = programs.Where(i => i.EndDate.HasValue && i.EndDate.Value <= val);
  383. }
  384. if (query.MaxStartDate.HasValue)
  385. {
  386. var val = query.MaxStartDate.Value;
  387. programs = programs.Where(i => i.StartDate <= val);
  388. }
  389. if (query.ChannelIdList.Length > 0)
  390. {
  391. var guids = query.ChannelIdList.Select(i => new Guid(i)).ToList();
  392. var serviceName = ActiveService.Name;
  393. programs = programs.Where(i =>
  394. {
  395. var programChannelId = i.ExternalChannelId;
  396. var internalProgramChannelId = _tvDtoService.GetInternalChannelId(serviceName, programChannelId);
  397. return guids.Contains(internalProgramChannelId);
  398. });
  399. }
  400. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(new Guid(query.UserId));
  401. if (user != null)
  402. {
  403. // Avoid implicitly captured closure
  404. var currentUser = user;
  405. programs = programs.Where(i => i.IsParentalAllowed(currentUser));
  406. }
  407. var returnArray = programs
  408. .Select(i =>
  409. {
  410. var channel = GetChannel(i);
  411. return _tvDtoService.GetProgramInfoDto(i, channel, user);
  412. })
  413. .ToArray();
  414. await AddRecordingInfo(returnArray, cancellationToken).ConfigureAwait(false);
  415. var result = new QueryResult<ProgramInfoDto>
  416. {
  417. Items = returnArray,
  418. TotalRecordCount = returnArray.Length
  419. };
  420. return result;
  421. }
  422. public async Task<QueryResult<ProgramInfoDto>> GetRecommendedPrograms(RecommendedProgramQuery query, CancellationToken cancellationToken)
  423. {
  424. IEnumerable<LiveTvProgram> programs = _programs.Values;
  425. var user = _userManager.GetUserById(new Guid(query.UserId));
  426. // Avoid implicitly captured closure
  427. var currentUser = user;
  428. programs = programs.Where(i => i.IsParentalAllowed(currentUser));
  429. if (query.IsAiring.HasValue)
  430. {
  431. var val = query.IsAiring.Value;
  432. programs = programs.Where(i => i.IsAiring == val);
  433. }
  434. if (query.HasAired.HasValue)
  435. {
  436. var val = query.HasAired.Value;
  437. programs = programs.Where(i => i.HasAired == val);
  438. }
  439. var serviceName = ActiveService.Name;
  440. var programList = programs.ToList();
  441. var genres = programList.SelectMany(i => i.Genres)
  442. .Distinct(StringComparer.OrdinalIgnoreCase)
  443. .Select(i => _libraryManager.GetGenre(i))
  444. .ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);
  445. programs = programList.OrderByDescending(i => GetRecommendationScore(i, user.Id, serviceName, genres))
  446. .ThenBy(i => i.StartDate);
  447. if (query.Limit.HasValue)
  448. {
  449. programs = programs.Take(query.Limit.Value)
  450. .OrderBy(i => i.StartDate);
  451. }
  452. var returnArray = programs
  453. .Select(i =>
  454. {
  455. var channel = GetChannel(i);
  456. return _tvDtoService.GetProgramInfoDto(i, channel, user);
  457. })
  458. .ToArray();
  459. await AddRecordingInfo(returnArray, cancellationToken).ConfigureAwait(false);
  460. var result = new QueryResult<ProgramInfoDto>
  461. {
  462. Items = returnArray,
  463. TotalRecordCount = returnArray.Length
  464. };
  465. return result;
  466. }
  467. private int GetRecommendationScore(LiveTvProgram program, Guid userId, string serviceName, Dictionary<string, Genre> genres)
  468. {
  469. var score = 0;
  470. if (program.IsLive)
  471. {
  472. score++;
  473. }
  474. if (program.IsSeries && !program.IsRepeat)
  475. {
  476. score++;
  477. }
  478. var internalChannelId = _tvDtoService.GetInternalChannelId(serviceName, program.ExternalChannelId);
  479. var channel = GetInternalChannel(internalChannelId);
  480. var channelUserdata = _userDataManager.GetUserData(userId, channel.GetUserDataKey());
  481. if ((channelUserdata.Likes ?? false))
  482. {
  483. score += 2;
  484. }
  485. else if (!(channelUserdata.Likes ?? true))
  486. {
  487. score -= 2;
  488. }
  489. if (channelUserdata.IsFavorite)
  490. {
  491. score += 3;
  492. }
  493. score += GetGenreScore(program.Genres, userId, genres);
  494. return score;
  495. }
  496. private int GetGenreScore(IEnumerable<string> programGenres, Guid userId, Dictionary<string, Genre> genres)
  497. {
  498. return programGenres.Select(i =>
  499. {
  500. var score = 0;
  501. Genre genre;
  502. if (genres.TryGetValue(i, out genre))
  503. {
  504. var genreUserdata = _userDataManager.GetUserData(userId, genre.GetUserDataKey());
  505. if ((genreUserdata.Likes ?? false))
  506. {
  507. score++;
  508. }
  509. else if (!(genreUserdata.Likes ?? true))
  510. {
  511. score--;
  512. }
  513. if (genreUserdata.IsFavorite)
  514. {
  515. score += 2;
  516. }
  517. }
  518. return score;
  519. }).Sum();
  520. }
  521. private async Task AddRecordingInfo(IEnumerable<ProgramInfoDto> programs, CancellationToken cancellationToken)
  522. {
  523. var timers = await ActiveService.GetTimersAsync(cancellationToken).ConfigureAwait(false);
  524. var timerList = timers.ToList();
  525. foreach (var program in programs)
  526. {
  527. var timer = timerList.FirstOrDefault(i => string.Equals(i.ProgramId, program.ExternalId, StringComparison.OrdinalIgnoreCase));
  528. if (timer != null)
  529. {
  530. program.TimerId = _tvDtoService.GetInternalTimerId(program.ServiceName, timer.Id)
  531. .ToString("N");
  532. if (!string.IsNullOrEmpty(timer.SeriesTimerId))
  533. {
  534. program.SeriesTimerId = _tvDtoService.GetInternalSeriesTimerId(program.ServiceName, timer.SeriesTimerId)
  535. .ToString("N");
  536. }
  537. }
  538. }
  539. }
  540. internal async Task RefreshChannels(IProgress<double> progress, CancellationToken cancellationToken)
  541. {
  542. // Avoid implicitly captured closure
  543. var service = ActiveService;
  544. if (service == null)
  545. {
  546. progress.Report(100);
  547. return;
  548. }
  549. progress.Report(10);
  550. var allChannels = await GetChannels(service, cancellationToken).ConfigureAwait(false);
  551. var allChannelsList = allChannels.ToList();
  552. var list = new List<LiveTvChannel>();
  553. var numComplete = 0;
  554. foreach (var channelInfo in allChannelsList)
  555. {
  556. try
  557. {
  558. var item = await GetChannel(channelInfo.Item2, channelInfo.Item1, cancellationToken).ConfigureAwait(false);
  559. list.Add(item);
  560. _libraryManager.RegisterItem(item);
  561. }
  562. catch (OperationCanceledException)
  563. {
  564. throw;
  565. }
  566. catch (Exception ex)
  567. {
  568. _logger.ErrorException("Error getting channel information for {0}", ex, channelInfo.Item2.Name);
  569. }
  570. numComplete++;
  571. double percent = numComplete;
  572. percent /= allChannelsList.Count;
  573. progress.Report(5 * percent + 10);
  574. }
  575. _channelIdList = list.Select(i => i.Id).ToList();
  576. progress.Report(15);
  577. numComplete = 0;
  578. var programs = new List<LiveTvProgram>();
  579. var guideDays = GetGuideDays(list.Count);
  580. foreach (var item in list)
  581. {
  582. // Avoid implicitly captured closure
  583. var currentChannel = item;
  584. try
  585. {
  586. var start = DateTime.UtcNow.AddHours(-1);
  587. var end = start.AddDays(guideDays);
  588. var channelPrograms = await service.GetProgramsAsync(currentChannel.ExternalId, start, end, cancellationToken).ConfigureAwait(false);
  589. var programTasks = channelPrograms.Select(program => GetProgram(program, currentChannel.ChannelType, service.Name, cancellationToken));
  590. var programEntities = await Task.WhenAll(programTasks).ConfigureAwait(false);
  591. programs.AddRange(programEntities);
  592. }
  593. catch (OperationCanceledException)
  594. {
  595. throw;
  596. }
  597. catch (Exception ex)
  598. {
  599. _logger.ErrorException("Error getting programs for channel {0}", ex, currentChannel.Name);
  600. }
  601. numComplete++;
  602. double percent = numComplete;
  603. percent /= allChannelsList.Count;
  604. progress.Report(90 * percent + 10);
  605. }
  606. _programs = programs.ToDictionary(i => i.Id);
  607. }
  608. private double GetGuideDays(int channelCount)
  609. {
  610. if (_config.Configuration.LiveTvOptions.GuideDays.HasValue)
  611. {
  612. return _config.Configuration.LiveTvOptions.GuideDays.Value;
  613. }
  614. var programsPerDay = channelCount * 48;
  615. const int maxPrograms = 24000;
  616. var days = Math.Round(((double)maxPrograms) / programsPerDay);
  617. // No less than 2, no more than 14
  618. return Math.Max(2, Math.Min(days, 14));
  619. }
  620. private async Task<IEnumerable<Tuple<string, ChannelInfo>>> GetChannels(ILiveTvService service, CancellationToken cancellationToken)
  621. {
  622. var channels = await service.GetChannelsAsync(cancellationToken).ConfigureAwait(false);
  623. return channels.Select(i => new Tuple<string, ChannelInfo>(service.Name, i));
  624. }
  625. public async Task<QueryResult<RecordingInfoDto>> GetRecordings(RecordingQuery query, CancellationToken cancellationToken)
  626. {
  627. var service = ActiveService;
  628. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(new Guid(query.UserId));
  629. var recordings = await service.GetRecordingsAsync(cancellationToken).ConfigureAwait(false);
  630. if (!string.IsNullOrEmpty(query.ChannelId))
  631. {
  632. var guid = new Guid(query.ChannelId);
  633. var currentServiceName = service.Name;
  634. recordings = recordings
  635. .Where(i => _tvDtoService.GetInternalChannelId(currentServiceName, i.ChannelId) == guid);
  636. }
  637. if (!string.IsNullOrEmpty(query.Id))
  638. {
  639. var guid = new Guid(query.Id);
  640. var currentServiceName = service.Name;
  641. recordings = recordings
  642. .Where(i => _tvDtoService.GetInternalRecordingId(currentServiceName, i.Id) == guid);
  643. }
  644. if (!string.IsNullOrEmpty(query.GroupId))
  645. {
  646. var guid = new Guid(query.GroupId);
  647. recordings = recordings.Where(i => GetRecordingGroupIds(i).Contains(guid));
  648. }
  649. if (query.IsInProgress.HasValue)
  650. {
  651. var val = query.IsInProgress.Value;
  652. recordings = recordings.Where(i => (i.Status == RecordingStatus.InProgress) == val);
  653. }
  654. if (query.Status.HasValue)
  655. {
  656. var val = query.Status.Value;
  657. recordings = recordings.Where(i => (i.Status == val));
  658. }
  659. if (!string.IsNullOrEmpty(query.SeriesTimerId))
  660. {
  661. var guid = new Guid(query.SeriesTimerId);
  662. var currentServiceName = service.Name;
  663. recordings = recordings
  664. .Where(i => _tvDtoService.GetInternalSeriesTimerId(currentServiceName, i.SeriesTimerId) == guid);
  665. }
  666. recordings = recordings.OrderByDescending(i => i.StartDate);
  667. IEnumerable<ILiveTvRecording> entities = await GetEntities(recordings, service.Name, cancellationToken).ConfigureAwait(false);
  668. if (user != null)
  669. {
  670. var currentUser = user;
  671. entities = entities.Where(i => i.IsParentalAllowed(currentUser));
  672. }
  673. if (query.StartIndex.HasValue)
  674. {
  675. entities = entities.Skip(query.StartIndex.Value);
  676. }
  677. if (query.Limit.HasValue)
  678. {
  679. entities = entities.Take(query.Limit.Value);
  680. }
  681. var returnArray = entities
  682. .Select(i =>
  683. {
  684. var channel = string.IsNullOrEmpty(i.RecordingInfo.ChannelId) ? null : GetInternalChannel(_tvDtoService.GetInternalChannelId(service.Name, i.RecordingInfo.ChannelId));
  685. return _tvDtoService.GetRecordingInfoDto(i, channel, service, user);
  686. })
  687. .ToArray();
  688. return new QueryResult<RecordingInfoDto>
  689. {
  690. Items = returnArray,
  691. TotalRecordCount = returnArray.Length
  692. };
  693. }
  694. private Task<ILiveTvRecording[]> GetEntities(IEnumerable<RecordingInfo> recordings, string serviceName, CancellationToken cancellationToken)
  695. {
  696. var tasks = recordings.Select(i => GetRecording(i, serviceName, cancellationToken));
  697. return Task.WhenAll(tasks);
  698. }
  699. private IEnumerable<ILiveTvService> GetServices(string serviceName, string channelId)
  700. {
  701. IEnumerable<ILiveTvService> services = _services;
  702. if (string.IsNullOrEmpty(serviceName) && !string.IsNullOrEmpty(channelId))
  703. {
  704. var channel = GetInternalChannel(channelId);
  705. if (channel != null)
  706. {
  707. serviceName = channel.ServiceName;
  708. }
  709. }
  710. if (!string.IsNullOrEmpty(serviceName))
  711. {
  712. services = services.Where(i => string.Equals(i.Name, serviceName, StringComparison.OrdinalIgnoreCase));
  713. }
  714. return services;
  715. }
  716. public async Task<QueryResult<TimerInfoDto>> GetTimers(TimerQuery query, CancellationToken cancellationToken)
  717. {
  718. var service = ActiveService;
  719. var timers = await service.GetTimersAsync(cancellationToken).ConfigureAwait(false);
  720. if (!string.IsNullOrEmpty(query.ChannelId))
  721. {
  722. var guid = new Guid(query.ChannelId);
  723. timers = timers.Where(i => guid == _tvDtoService.GetInternalChannelId(service.Name, i.ChannelId));
  724. }
  725. if (!string.IsNullOrEmpty(query.SeriesTimerId))
  726. {
  727. var guid = new Guid(query.SeriesTimerId);
  728. var currentServiceName = service.Name;
  729. timers = timers
  730. .Where(i => _tvDtoService.GetInternalSeriesTimerId(currentServiceName, i.SeriesTimerId) == guid);
  731. }
  732. var returnArray = timers
  733. .Select(i =>
  734. {
  735. var program = string.IsNullOrEmpty(i.ProgramId) ? null : GetInternalProgram(_tvDtoService.GetInternalProgramId(service.Name, i.ProgramId).ToString("N"));
  736. var channel = string.IsNullOrEmpty(i.ChannelId) ? null : GetInternalChannel(_tvDtoService.GetInternalChannelId(service.Name, i.ChannelId));
  737. return _tvDtoService.GetTimerInfoDto(i, service, program, channel);
  738. })
  739. .OrderBy(i => i.StartDate)
  740. .ToArray();
  741. return new QueryResult<TimerInfoDto>
  742. {
  743. Items = returnArray,
  744. TotalRecordCount = returnArray.Length
  745. };
  746. }
  747. public async Task DeleteRecording(string recordingId)
  748. {
  749. var recording = await GetRecording(recordingId, CancellationToken.None).ConfigureAwait(false);
  750. if (recording == null)
  751. {
  752. throw new ResourceNotFoundException(string.Format("Recording with Id {0} not found", recordingId));
  753. }
  754. var service = GetServices(recording.ServiceName, null)
  755. .First();
  756. await service.DeleteRecordingAsync(recording.ExternalId, CancellationToken.None).ConfigureAwait(false);
  757. }
  758. public async Task CancelTimer(string id)
  759. {
  760. var timer = await GetTimer(id, CancellationToken.None).ConfigureAwait(false);
  761. if (timer == null)
  762. {
  763. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  764. }
  765. var service = GetServices(timer.ServiceName, null)
  766. .First();
  767. await service.CancelTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  768. }
  769. public async Task CancelSeriesTimer(string id)
  770. {
  771. var timer = await GetSeriesTimer(id, CancellationToken.None).ConfigureAwait(false);
  772. if (timer == null)
  773. {
  774. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  775. }
  776. var service = GetServices(timer.ServiceName, null)
  777. .First();
  778. await service.CancelSeriesTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  779. }
  780. public async Task<RecordingInfoDto> GetRecording(string id, CancellationToken cancellationToken, User user = null)
  781. {
  782. var results = await GetRecordings(new RecordingQuery
  783. {
  784. UserId = user == null ? null : user.Id.ToString("N"),
  785. Id = id
  786. }, cancellationToken).ConfigureAwait(false);
  787. return results.Items.FirstOrDefault();
  788. }
  789. public async Task<TimerInfoDto> GetTimer(string id, CancellationToken cancellationToken)
  790. {
  791. var results = await GetTimers(new TimerQuery(), cancellationToken).ConfigureAwait(false);
  792. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.CurrentCulture));
  793. }
  794. public async Task<SeriesTimerInfoDto> GetSeriesTimer(string id, CancellationToken cancellationToken)
  795. {
  796. var results = await GetSeriesTimers(new SeriesTimerQuery(), cancellationToken).ConfigureAwait(false);
  797. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.CurrentCulture));
  798. }
  799. public async Task<QueryResult<SeriesTimerInfoDto>> GetSeriesTimers(SeriesTimerQuery query, CancellationToken cancellationToken)
  800. {
  801. var service = ActiveService;
  802. var timers = await service.GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false);
  803. if (string.Equals(query.SortBy, "Priority", StringComparison.OrdinalIgnoreCase))
  804. {
  805. timers = query.SortOrder == SortOrder.Descending ?
  806. timers.OrderBy(i => i.Priority).ThenByStringDescending(i => i.Name) :
  807. timers.OrderByDescending(i => i.Priority).ThenByString(i => i.Name);
  808. }
  809. else
  810. {
  811. timers = query.SortOrder == SortOrder.Descending ?
  812. timers.OrderByStringDescending(i => i.Name) :
  813. timers.OrderByString(i => i.Name);
  814. }
  815. var returnArray = timers
  816. .Select(i =>
  817. {
  818. string channelName = null;
  819. if (!string.IsNullOrEmpty(i.ChannelId))
  820. {
  821. var internalChannelId = _tvDtoService.GetInternalChannelId(service.Name, i.ChannelId);
  822. var channel = GetInternalChannel(internalChannelId);
  823. channelName = channel == null ? null : channel.Name;
  824. }
  825. return _tvDtoService.GetSeriesTimerInfoDto(i, service, channelName);
  826. })
  827. .ToArray();
  828. return new QueryResult<SeriesTimerInfoDto>
  829. {
  830. Items = returnArray,
  831. TotalRecordCount = returnArray.Length
  832. };
  833. }
  834. public Task<ChannelInfoDto> GetChannel(string id, CancellationToken cancellationToken, User user = null)
  835. {
  836. var channel = GetInternalChannel(id);
  837. var dto = _tvDtoService.GetChannelInfoDto(channel, GetCurrentProgram(channel.ExternalId), user);
  838. return Task.FromResult(dto);
  839. }
  840. private LiveTvProgram GetCurrentProgram(string externalChannelId)
  841. {
  842. var now = DateTime.UtcNow;
  843. return _programs.Values
  844. .Where(i => string.Equals(externalChannelId, i.ExternalChannelId, StringComparison.OrdinalIgnoreCase))
  845. .OrderBy(i => i.StartDate)
  846. .SkipWhile(i => now >= (i.EndDate ?? DateTime.MinValue))
  847. .FirstOrDefault();
  848. }
  849. private async Task<SeriesTimerInfo> GetNewTimerDefaultsInternal(CancellationToken cancellationToken, LiveTvProgram program = null)
  850. {
  851. ProgramInfo programInfo = null;
  852. if (program != null)
  853. {
  854. programInfo = new ProgramInfo
  855. {
  856. Audio = program.Audio,
  857. ChannelId = program.ExternalChannelId,
  858. CommunityRating = program.CommunityRating,
  859. EndDate = program.EndDate ?? DateTime.MinValue,
  860. EpisodeTitle = program.EpisodeTitle,
  861. Genres = program.Genres,
  862. HasImage = program.HasProviderImage,
  863. Id = program.ExternalId,
  864. IsHD = program.IsHD,
  865. IsKids = program.IsKids,
  866. IsLive = program.IsLive,
  867. IsMovie = program.IsMovie,
  868. IsNews = program.IsNews,
  869. IsPremiere = program.IsPremiere,
  870. IsRepeat = program.IsRepeat,
  871. IsSeries = program.IsSeries,
  872. IsSports = program.IsSports,
  873. OriginalAirDate = program.PremiereDate,
  874. Overview = program.Overview,
  875. StartDate = program.StartDate,
  876. ImagePath = program.ProviderImagePath,
  877. ImageUrl = program.ProviderImageUrl,
  878. Name = program.Name,
  879. OfficialRating = program.OfficialRating
  880. };
  881. }
  882. var info = await ActiveService.GetNewTimerDefaultsAsync(cancellationToken, programInfo).ConfigureAwait(false);
  883. info.Id = null;
  884. return info;
  885. }
  886. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(CancellationToken cancellationToken)
  887. {
  888. var info = await GetNewTimerDefaultsInternal(cancellationToken).ConfigureAwait(false);
  889. var obj = _tvDtoService.GetSeriesTimerInfoDto(info, ActiveService, null);
  890. return obj;
  891. }
  892. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(string programId, CancellationToken cancellationToken)
  893. {
  894. var program = GetInternalProgram(programId);
  895. var programDto = await GetProgram(programId, cancellationToken).ConfigureAwait(false);
  896. var defaults = await GetNewTimerDefaultsInternal(cancellationToken, program).ConfigureAwait(false);
  897. var info = _tvDtoService.GetSeriesTimerInfoDto(defaults, ActiveService, null);
  898. info.Days = new List<DayOfWeek>
  899. {
  900. program.StartDate.ToLocalTime().DayOfWeek
  901. };
  902. info.DayPattern = _tvDtoService.GetDayPattern(info.Days);
  903. info.Name = program.Name;
  904. info.ChannelId = programDto.ChannelId;
  905. info.ChannelName = programDto.ChannelName;
  906. info.StartDate = program.StartDate;
  907. info.Name = program.Name;
  908. info.Overview = program.Overview;
  909. info.ProgramId = programDto.Id;
  910. info.ExternalProgramId = programDto.ExternalId;
  911. if (program.EndDate.HasValue)
  912. {
  913. info.EndDate = program.EndDate.Value;
  914. }
  915. return info;
  916. }
  917. public async Task CreateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  918. {
  919. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  920. var info = await _tvDtoService.GetTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  921. // Set priority from default values
  922. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  923. info.Priority = defaultValues.Priority;
  924. await service.CreateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  925. }
  926. public async Task CreateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  927. {
  928. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  929. var info = await _tvDtoService.GetSeriesTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  930. // Set priority from default values
  931. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  932. info.Priority = defaultValues.Priority;
  933. await service.CreateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  934. }
  935. public async Task UpdateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  936. {
  937. var info = await _tvDtoService.GetTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  938. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  939. await service.UpdateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  940. }
  941. public async Task UpdateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  942. {
  943. var info = await _tvDtoService.GetSeriesTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  944. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  945. await service.UpdateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  946. }
  947. private IEnumerable<string> GetRecordingGroupNames(RecordingInfo recording)
  948. {
  949. var list = new List<string>();
  950. if (recording.IsSeries)
  951. {
  952. list.Add(recording.Name);
  953. }
  954. if (recording.IsKids)
  955. {
  956. list.Add("Kids");
  957. }
  958. if (recording.IsMovie)
  959. {
  960. list.Add("Movies");
  961. }
  962. if (recording.IsNews)
  963. {
  964. list.Add("News");
  965. }
  966. if (recording.IsSports)
  967. {
  968. list.Add("Sports");
  969. }
  970. if (!recording.IsSports && !recording.IsNews && !recording.IsMovie && !recording.IsKids && !recording.IsSeries)
  971. {
  972. list.Add("Others");
  973. }
  974. return list;
  975. }
  976. private List<Guid> GetRecordingGroupIds(RecordingInfo recording)
  977. {
  978. return GetRecordingGroupNames(recording).Select(i => i.ToLower()
  979. .GetMD5())
  980. .ToList();
  981. }
  982. public async Task<QueryResult<RecordingGroupDto>> GetRecordingGroups(RecordingGroupQuery query, CancellationToken cancellationToken)
  983. {
  984. var recordingResult = await GetRecordings(new RecordingQuery
  985. {
  986. UserId = query.UserId
  987. }, cancellationToken).ConfigureAwait(false);
  988. var recordings = recordingResult.Items;
  989. var groups = new List<RecordingGroupDto>();
  990. var series = recordings
  991. .Where(i => i.IsSeries)
  992. .ToLookup(i => i.Name, StringComparer.OrdinalIgnoreCase)
  993. .ToList();
  994. groups.AddRange(series.OrderByString(i => i.Key).Select(i => new RecordingGroupDto
  995. {
  996. Name = i.Key,
  997. RecordingCount = i.Count()
  998. }));
  999. groups.Add(new RecordingGroupDto
  1000. {
  1001. Name = "Kids",
  1002. RecordingCount = recordings.Count(i => i.IsKids)
  1003. });
  1004. groups.Add(new RecordingGroupDto
  1005. {
  1006. Name = "Movies",
  1007. RecordingCount = recordings.Count(i => i.IsMovie)
  1008. });
  1009. groups.Add(new RecordingGroupDto
  1010. {
  1011. Name = "News",
  1012. RecordingCount = recordings.Count(i => i.IsNews)
  1013. });
  1014. groups.Add(new RecordingGroupDto
  1015. {
  1016. Name = "Sports",
  1017. RecordingCount = recordings.Count(i => i.IsSports)
  1018. });
  1019. groups.Add(new RecordingGroupDto
  1020. {
  1021. Name = "Others",
  1022. RecordingCount = recordings.Count(i => !i.IsSports && !i.IsNews && !i.IsMovie && !i.IsKids && !i.IsSeries)
  1023. });
  1024. groups = groups
  1025. .Where(i => i.RecordingCount > 0)
  1026. .ToList();
  1027. foreach (var group in groups)
  1028. {
  1029. group.Id = group.Name.ToLower().GetMD5().ToString("N");
  1030. }
  1031. return new QueryResult<RecordingGroupDto>
  1032. {
  1033. Items = groups.ToArray(),
  1034. TotalRecordCount = groups.Count
  1035. };
  1036. }
  1037. public async Task CloseLiveStream(string id, CancellationToken cancellationToken)
  1038. {
  1039. await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  1040. var service = ActiveService;
  1041. _logger.Info("Closing live stream from {0}, stream Id: {1}", service.Name, id);
  1042. try
  1043. {
  1044. await service.CloseLiveStream(id, cancellationToken).ConfigureAwait(false);
  1045. }
  1046. catch (Exception ex)
  1047. {
  1048. _logger.ErrorException("Error closing live stream", ex);
  1049. throw;
  1050. }
  1051. finally
  1052. {
  1053. _liveStreamSemaphore.Release();
  1054. }
  1055. }
  1056. public GuideInfo GetGuideInfo()
  1057. {
  1058. var programs = _programs.ToList();
  1059. var startDate = programs.Select(i => i.Value.StartDate).Min();
  1060. var endDate = programs.Select(i => i.Value.StartDate).Max();
  1061. return new GuideInfo
  1062. {
  1063. StartDate = startDate,
  1064. EndDate = endDate
  1065. };
  1066. }
  1067. /// <summary>
  1068. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1069. /// </summary>
  1070. public void Dispose()
  1071. {
  1072. Dispose(true);
  1073. }
  1074. private readonly object _disposeLock = new object();
  1075. /// <summary>
  1076. /// Releases unmanaged and - optionally - managed resources.
  1077. /// </summary>
  1078. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1079. protected virtual void Dispose(bool dispose)
  1080. {
  1081. if (dispose)
  1082. {
  1083. lock (_disposeLock)
  1084. {
  1085. foreach (var stream in _openStreams.Values.ToList())
  1086. {
  1087. var task = CloseLiveStream(stream.Id, CancellationToken.None);
  1088. Task.WaitAll(task);
  1089. }
  1090. _openStreams.Clear();
  1091. }
  1092. }
  1093. }
  1094. private async Task<IEnumerable<LiveTvServiceInfo>> GetServiceInfos(CancellationToken cancellationToken)
  1095. {
  1096. var tasks = Services.Select(i => GetServiceInfo(i, cancellationToken));
  1097. return await Task.WhenAll(tasks).ConfigureAwait(false);
  1098. }
  1099. private async Task<LiveTvServiceInfo> GetServiceInfo(ILiveTvService service, CancellationToken cancellationToken)
  1100. {
  1101. var info = new LiveTvServiceInfo
  1102. {
  1103. Name = service.Name
  1104. };
  1105. try
  1106. {
  1107. var statusInfo = await service.GetStatusInfoAsync(cancellationToken).ConfigureAwait(false);
  1108. info.Status = statusInfo.Status;
  1109. info.StatusMessage = statusInfo.StatusMessage;
  1110. info.Version = statusInfo.Version;
  1111. info.HasUpdateAvailable = statusInfo.HasUpdateAvailable;
  1112. info.HomePageUrl = service.HomePageUrl;
  1113. info.Tuners = statusInfo.Tuners.Select(i => _tvDtoService.GetTunerInfoDto(service.Name, i)).ToList();
  1114. }
  1115. catch (Exception ex)
  1116. {
  1117. _logger.ErrorException("Error getting service status info from {0}", ex, service.Name);
  1118. info.Status = LiveTvServiceStatus.Unavailable;
  1119. info.StatusMessage = ex.Message;
  1120. }
  1121. return info;
  1122. }
  1123. public async Task<LiveTvInfo> GetLiveTvInfo(CancellationToken cancellationToken)
  1124. {
  1125. var services = await GetServiceInfos(CancellationToken.None).ConfigureAwait(false);
  1126. var servicesList = services.ToList();
  1127. var activeServiceInfo = ActiveService == null ? null :
  1128. servicesList.FirstOrDefault(i => string.Equals(i.Name, ActiveService.Name, StringComparison.OrdinalIgnoreCase));
  1129. var info = new LiveTvInfo
  1130. {
  1131. Services = servicesList.ToList(),
  1132. ActiveServiceName = activeServiceInfo == null ? null : activeServiceInfo.Name,
  1133. IsEnabled = ActiveService != null,
  1134. Status = activeServiceInfo == null ? LiveTvServiceStatus.Unavailable : activeServiceInfo.Status,
  1135. StatusMessage = activeServiceInfo == null ? null : activeServiceInfo.StatusMessage
  1136. };
  1137. info.EnabledUsers = _userManager.Users
  1138. .Where(i => i.Configuration.EnableLiveTvAccess && info.IsEnabled)
  1139. .Select(i => i.Id.ToString("N"))
  1140. .ToList();
  1141. return info;
  1142. }
  1143. /// <summary>
  1144. /// Resets the tuner.
  1145. /// </summary>
  1146. /// <param name="id">The identifier.</param>
  1147. /// <param name="cancellationToken">The cancellation token.</param>
  1148. /// <returns>Task.</returns>
  1149. public Task ResetTuner(string id, CancellationToken cancellationToken)
  1150. {
  1151. return ActiveService.ResetTuner(id, cancellationToken);
  1152. }
  1153. }
  1154. }