LiveTvManager.cs 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500
  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 =>
  1114. {
  1115. string channelName = null;
  1116. if (!string.IsNullOrEmpty(i.ChannelId))
  1117. {
  1118. var internalChannelId = _tvDtoService.GetInternalChannelId(service.Name, i.ChannelId);
  1119. var channel = GetInternalChannel(internalChannelId);
  1120. channelName = channel == null ? null : channel.Name;
  1121. }
  1122. return _tvDtoService.GetTunerInfoDto(service.Name, i, channelName);
  1123. }).ToList();
  1124. }
  1125. catch (Exception ex)
  1126. {
  1127. _logger.ErrorException("Error getting service status info from {0}", ex, service.Name);
  1128. info.Status = LiveTvServiceStatus.Unavailable;
  1129. info.StatusMessage = ex.Message;
  1130. }
  1131. return info;
  1132. }
  1133. public async Task<LiveTvInfo> GetLiveTvInfo(CancellationToken cancellationToken)
  1134. {
  1135. var services = await GetServiceInfos(CancellationToken.None).ConfigureAwait(false);
  1136. var servicesList = services.ToList();
  1137. var activeServiceInfo = ActiveService == null ? null :
  1138. servicesList.FirstOrDefault(i => string.Equals(i.Name, ActiveService.Name, StringComparison.OrdinalIgnoreCase));
  1139. var info = new LiveTvInfo
  1140. {
  1141. Services = servicesList.ToList(),
  1142. ActiveServiceName = activeServiceInfo == null ? null : activeServiceInfo.Name,
  1143. IsEnabled = ActiveService != null,
  1144. Status = activeServiceInfo == null ? LiveTvServiceStatus.Unavailable : activeServiceInfo.Status,
  1145. StatusMessage = activeServiceInfo == null ? null : activeServiceInfo.StatusMessage
  1146. };
  1147. info.EnabledUsers = _userManager.Users
  1148. .Where(i => i.Configuration.EnableLiveTvAccess && info.IsEnabled)
  1149. .Select(i => i.Id.ToString("N"))
  1150. .ToList();
  1151. return info;
  1152. }
  1153. /// <summary>
  1154. /// Resets the tuner.
  1155. /// </summary>
  1156. /// <param name="id">The identifier.</param>
  1157. /// <param name="cancellationToken">The cancellation token.</param>
  1158. /// <returns>Task.</returns>
  1159. public Task ResetTuner(string id, CancellationToken cancellationToken)
  1160. {
  1161. return ActiveService.ResetTuner(id, cancellationToken);
  1162. }
  1163. }
  1164. }