LiveTvManager.cs 52 KB

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