LiveTvManager.cs 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516
  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. // Set this now so we don't cause additional file system access during provider executions
  259. item.ResetResolveArgs(fileInfo);
  260. await item.RefreshMetadata(new MetadataRefreshOptions
  261. {
  262. ForceSave = isNew,
  263. ResetResolveArgs = false
  264. }, cancellationToken);
  265. return item;
  266. }
  267. private async Task<LiveTvProgram> GetProgram(ProgramInfo info, ChannelType channelType, string serviceName, CancellationToken cancellationToken)
  268. {
  269. var isNew = false;
  270. var id = _tvDtoService.GetInternalProgramId(serviceName, info.Id);
  271. var item = _itemRepo.RetrieveItem(id) as LiveTvProgram;
  272. if (item == null)
  273. {
  274. item = new LiveTvProgram
  275. {
  276. Name = info.Name,
  277. Id = id,
  278. DateCreated = DateTime.UtcNow,
  279. DateModified = DateTime.UtcNow
  280. };
  281. isNew = true;
  282. }
  283. item.ChannelType = channelType;
  284. item.ServiceName = serviceName;
  285. item.Audio = info.Audio;
  286. item.ExternalChannelId = info.ChannelId;
  287. item.CommunityRating = info.CommunityRating;
  288. item.EndDate = info.EndDate;
  289. item.EpisodeTitle = info.EpisodeTitle;
  290. item.ExternalId = info.Id;
  291. item.Genres = info.Genres;
  292. item.HasProviderImage = info.HasImage;
  293. item.IsHD = info.IsHD;
  294. item.IsKids = info.IsKids;
  295. item.IsLive = info.IsLive;
  296. item.IsMovie = info.IsMovie;
  297. item.IsNews = info.IsNews;
  298. item.IsPremiere = info.IsPremiere;
  299. item.IsRepeat = info.IsRepeat;
  300. item.IsSeries = info.IsSeries;
  301. item.IsSports = info.IsSports;
  302. item.Name = info.Name;
  303. item.OfficialRating = info.OfficialRating;
  304. item.Overview = info.Overview;
  305. item.PremiereDate = info.OriginalAirDate;
  306. item.ProviderImagePath = info.ImagePath;
  307. item.ProviderImageUrl = info.ImageUrl;
  308. item.RunTimeTicks = (info.EndDate - info.StartDate).Ticks;
  309. item.StartDate = info.StartDate;
  310. await item.RefreshMetadata(new MetadataRefreshOptions
  311. {
  312. ForceSave = isNew,
  313. ResetResolveArgs = false
  314. }, cancellationToken);
  315. return item;
  316. }
  317. private async Task<ILiveTvRecording> GetRecording(RecordingInfo info, string serviceName, CancellationToken cancellationToken)
  318. {
  319. var isNew = false;
  320. var id = _tvDtoService.GetInternalRecordingId(serviceName, info.Id);
  321. var item = _itemRepo.RetrieveItem(id) as ILiveTvRecording;
  322. if (item == null)
  323. {
  324. if (info.ChannelType == ChannelType.TV)
  325. {
  326. item = new LiveTvVideoRecording
  327. {
  328. Name = info.Name,
  329. Id = id,
  330. DateCreated = DateTime.UtcNow,
  331. DateModified = DateTime.UtcNow,
  332. VideoType = VideoType.VideoFile
  333. };
  334. }
  335. else
  336. {
  337. item = new LiveTvAudioRecording
  338. {
  339. Name = info.Name,
  340. Id = id,
  341. DateCreated = DateTime.UtcNow,
  342. DateModified = DateTime.UtcNow
  343. };
  344. }
  345. if (!string.IsNullOrEmpty(info.Path))
  346. {
  347. item.Path = info.Path;
  348. }
  349. else if (!string.IsNullOrEmpty(info.Url))
  350. {
  351. item.Path = info.Url;
  352. }
  353. isNew = true;
  354. }
  355. item.RecordingInfo = info;
  356. item.ServiceName = serviceName;
  357. await item.RefreshMetadata(new MetadataRefreshOptions
  358. {
  359. ForceSave = isNew,
  360. ResetResolveArgs = false
  361. }, cancellationToken);
  362. _libraryManager.RegisterItem((BaseItem)item);
  363. return item;
  364. }
  365. private LiveTvChannel GetChannel(LiveTvProgram program)
  366. {
  367. var programChannelId = program.ExternalChannelId;
  368. var internalProgramChannelId = _tvDtoService.GetInternalChannelId(program.ServiceName, programChannelId);
  369. return GetInternalChannel(internalProgramChannelId);
  370. }
  371. public async Task<ProgramInfoDto> GetProgram(string id, CancellationToken cancellationToken, User user = null)
  372. {
  373. var program = GetInternalProgram(id);
  374. var channel = GetChannel(program);
  375. var dto = _tvDtoService.GetProgramInfoDto(program, channel, user);
  376. await AddRecordingInfo(new[] { dto }, cancellationToken).ConfigureAwait(false);
  377. return dto;
  378. }
  379. public async Task<QueryResult<ProgramInfoDto>> GetPrograms(ProgramQuery query, CancellationToken cancellationToken)
  380. {
  381. IEnumerable<LiveTvProgram> programs = _programs.Values;
  382. if (query.MinEndDate.HasValue)
  383. {
  384. var val = query.MinEndDate.Value;
  385. programs = programs.Where(i => i.EndDate.HasValue && i.EndDate.Value >= val);
  386. }
  387. if (query.MinStartDate.HasValue)
  388. {
  389. var val = query.MinStartDate.Value;
  390. programs = programs.Where(i => i.StartDate >= val);
  391. }
  392. if (query.MaxEndDate.HasValue)
  393. {
  394. var val = query.MaxEndDate.Value;
  395. programs = programs.Where(i => i.EndDate.HasValue && i.EndDate.Value <= val);
  396. }
  397. if (query.MaxStartDate.HasValue)
  398. {
  399. var val = query.MaxStartDate.Value;
  400. programs = programs.Where(i => i.StartDate <= val);
  401. }
  402. if (query.ChannelIdList.Length > 0)
  403. {
  404. var guids = query.ChannelIdList.Select(i => new Guid(i)).ToList();
  405. var serviceName = ActiveService.Name;
  406. programs = programs.Where(i =>
  407. {
  408. var programChannelId = i.ExternalChannelId;
  409. var internalProgramChannelId = _tvDtoService.GetInternalChannelId(serviceName, programChannelId);
  410. return guids.Contains(internalProgramChannelId);
  411. });
  412. }
  413. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(new Guid(query.UserId));
  414. if (user != null)
  415. {
  416. // Avoid implicitly captured closure
  417. var currentUser = user;
  418. programs = programs.Where(i => i.IsParentalAllowed(currentUser));
  419. }
  420. var returnArray = programs
  421. .Select(i =>
  422. {
  423. var channel = GetChannel(i);
  424. return _tvDtoService.GetProgramInfoDto(i, channel, user);
  425. })
  426. .ToArray();
  427. await AddRecordingInfo(returnArray, cancellationToken).ConfigureAwait(false);
  428. var result = new QueryResult<ProgramInfoDto>
  429. {
  430. Items = returnArray,
  431. TotalRecordCount = returnArray.Length
  432. };
  433. return result;
  434. }
  435. public async Task<QueryResult<ProgramInfoDto>> GetRecommendedPrograms(RecommendedProgramQuery query, CancellationToken cancellationToken)
  436. {
  437. IEnumerable<LiveTvProgram> programs = _programs.Values;
  438. var user = _userManager.GetUserById(new Guid(query.UserId));
  439. // Avoid implicitly captured closure
  440. var currentUser = user;
  441. programs = programs.Where(i => i.IsParentalAllowed(currentUser));
  442. if (query.IsAiring.HasValue)
  443. {
  444. var val = query.IsAiring.Value;
  445. programs = programs.Where(i => i.IsAiring == val);
  446. }
  447. if (query.HasAired.HasValue)
  448. {
  449. var val = query.HasAired.Value;
  450. programs = programs.Where(i => i.HasAired == val);
  451. }
  452. var serviceName = ActiveService.Name;
  453. var programList = programs.ToList();
  454. var genres = programList.SelectMany(i => i.Genres)
  455. .Distinct(StringComparer.OrdinalIgnoreCase)
  456. .Select(i => _libraryManager.GetGenre(i))
  457. .ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);
  458. programs = programList.OrderByDescending(i => GetRecommendationScore(i, user.Id, serviceName, genres))
  459. .ThenBy(i => i.StartDate);
  460. if (query.Limit.HasValue)
  461. {
  462. programs = programs.Take(query.Limit.Value)
  463. .OrderBy(i => i.StartDate);
  464. }
  465. var returnArray = programs
  466. .Select(i =>
  467. {
  468. var channel = GetChannel(i);
  469. return _tvDtoService.GetProgramInfoDto(i, channel, user);
  470. })
  471. .ToArray();
  472. await AddRecordingInfo(returnArray, cancellationToken).ConfigureAwait(false);
  473. var result = new QueryResult<ProgramInfoDto>
  474. {
  475. Items = returnArray,
  476. TotalRecordCount = returnArray.Length
  477. };
  478. return result;
  479. }
  480. private int GetRecommendationScore(LiveTvProgram program, Guid userId, string serviceName, Dictionary<string, Genre> genres)
  481. {
  482. var score = 0;
  483. if (program.IsLive)
  484. {
  485. score++;
  486. }
  487. if (program.IsSeries && !program.IsRepeat)
  488. {
  489. score++;
  490. }
  491. var internalChannelId = _tvDtoService.GetInternalChannelId(serviceName, program.ExternalChannelId);
  492. var channel = GetInternalChannel(internalChannelId);
  493. var channelUserdata = _userDataManager.GetUserData(userId, channel.GetUserDataKey());
  494. if ((channelUserdata.Likes ?? false))
  495. {
  496. score += 2;
  497. }
  498. else if (!(channelUserdata.Likes ?? true))
  499. {
  500. score -= 2;
  501. }
  502. if (channelUserdata.IsFavorite)
  503. {
  504. score += 3;
  505. }
  506. score += GetGenreScore(program.Genres, userId, genres);
  507. return score;
  508. }
  509. private int GetGenreScore(IEnumerable<string> programGenres, Guid userId, Dictionary<string, Genre> genres)
  510. {
  511. return programGenres.Select(i =>
  512. {
  513. var score = 0;
  514. Genre genre;
  515. if (genres.TryGetValue(i, out genre))
  516. {
  517. var genreUserdata = _userDataManager.GetUserData(userId, genre.GetUserDataKey());
  518. if ((genreUserdata.Likes ?? false))
  519. {
  520. score++;
  521. }
  522. else if (!(genreUserdata.Likes ?? true))
  523. {
  524. score--;
  525. }
  526. if (genreUserdata.IsFavorite)
  527. {
  528. score += 2;
  529. }
  530. }
  531. return score;
  532. }).Sum();
  533. }
  534. private async Task AddRecordingInfo(IEnumerable<ProgramInfoDto> programs, CancellationToken cancellationToken)
  535. {
  536. var timers = await ActiveService.GetTimersAsync(cancellationToken).ConfigureAwait(false);
  537. var timerList = timers.ToList();
  538. foreach (var program in programs)
  539. {
  540. var timer = timerList.FirstOrDefault(i => string.Equals(i.ProgramId, program.ExternalId, StringComparison.OrdinalIgnoreCase));
  541. if (timer != null)
  542. {
  543. program.TimerId = _tvDtoService.GetInternalTimerId(program.ServiceName, timer.Id)
  544. .ToString("N");
  545. if (!string.IsNullOrEmpty(timer.SeriesTimerId))
  546. {
  547. program.SeriesTimerId = _tvDtoService.GetInternalSeriesTimerId(program.ServiceName, timer.SeriesTimerId)
  548. .ToString("N");
  549. }
  550. }
  551. }
  552. }
  553. internal async Task RefreshChannels(IProgress<double> progress, CancellationToken cancellationToken)
  554. {
  555. // Avoid implicitly captured closure
  556. var service = ActiveService;
  557. if (service == null)
  558. {
  559. progress.Report(100);
  560. return;
  561. }
  562. progress.Report(10);
  563. var allChannels = await GetChannels(service, cancellationToken).ConfigureAwait(false);
  564. var allChannelsList = allChannels.ToList();
  565. var list = new List<LiveTvChannel>();
  566. var numComplete = 0;
  567. foreach (var channelInfo in allChannelsList)
  568. {
  569. try
  570. {
  571. var item = await GetChannel(channelInfo.Item2, channelInfo.Item1, cancellationToken).ConfigureAwait(false);
  572. list.Add(item);
  573. _libraryManager.RegisterItem(item);
  574. }
  575. catch (OperationCanceledException)
  576. {
  577. throw;
  578. }
  579. catch (Exception ex)
  580. {
  581. _logger.ErrorException("Error getting channel information for {0}", ex, channelInfo.Item2.Name);
  582. }
  583. numComplete++;
  584. double percent = numComplete;
  585. percent /= allChannelsList.Count;
  586. progress.Report(5 * percent + 10);
  587. }
  588. _channelIdList = list.Select(i => i.Id).ToList();
  589. progress.Report(15);
  590. numComplete = 0;
  591. var programs = new List<LiveTvProgram>();
  592. var guideDays = GetGuideDays(list.Count);
  593. foreach (var item in list)
  594. {
  595. // Avoid implicitly captured closure
  596. var currentChannel = item;
  597. try
  598. {
  599. var start = DateTime.UtcNow.AddHours(-1);
  600. var end = start.AddDays(guideDays);
  601. var channelPrograms = await service.GetProgramsAsync(currentChannel.ExternalId, start, end, cancellationToken).ConfigureAwait(false);
  602. var programTasks = channelPrograms.Select(program => GetProgram(program, currentChannel.ChannelType, service.Name, cancellationToken));
  603. var programEntities = await Task.WhenAll(programTasks).ConfigureAwait(false);
  604. programs.AddRange(programEntities);
  605. }
  606. catch (OperationCanceledException)
  607. {
  608. throw;
  609. }
  610. catch (Exception ex)
  611. {
  612. _logger.ErrorException("Error getting programs for channel {0}", ex, currentChannel.Name);
  613. }
  614. numComplete++;
  615. double percent = numComplete;
  616. percent /= allChannelsList.Count;
  617. progress.Report(90 * percent + 10);
  618. }
  619. _programs = programs.ToDictionary(i => i.Id);
  620. }
  621. private double GetGuideDays(int channelCount)
  622. {
  623. if (_config.Configuration.LiveTvOptions.GuideDays.HasValue)
  624. {
  625. return _config.Configuration.LiveTvOptions.GuideDays.Value;
  626. }
  627. var programsPerDay = channelCount * 48;
  628. const int maxPrograms = 24000;
  629. var days = Math.Round(((double)maxPrograms) / programsPerDay);
  630. // No less than 2, no more than 14
  631. return Math.Max(2, Math.Min(days, 14));
  632. }
  633. private async Task<IEnumerable<Tuple<string, ChannelInfo>>> GetChannels(ILiveTvService service, CancellationToken cancellationToken)
  634. {
  635. var channels = await service.GetChannelsAsync(cancellationToken).ConfigureAwait(false);
  636. return channels.Select(i => new Tuple<string, ChannelInfo>(service.Name, i));
  637. }
  638. public async Task<QueryResult<RecordingInfoDto>> GetRecordings(RecordingQuery query, CancellationToken cancellationToken)
  639. {
  640. var service = ActiveService;
  641. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(new Guid(query.UserId));
  642. var recordings = await service.GetRecordingsAsync(cancellationToken).ConfigureAwait(false);
  643. if (!string.IsNullOrEmpty(query.ChannelId))
  644. {
  645. var guid = new Guid(query.ChannelId);
  646. var currentServiceName = service.Name;
  647. recordings = recordings
  648. .Where(i => _tvDtoService.GetInternalChannelId(currentServiceName, i.ChannelId) == guid);
  649. }
  650. if (!string.IsNullOrEmpty(query.Id))
  651. {
  652. var guid = new Guid(query.Id);
  653. var currentServiceName = service.Name;
  654. recordings = recordings
  655. .Where(i => _tvDtoService.GetInternalRecordingId(currentServiceName, i.Id) == guid);
  656. }
  657. if (!string.IsNullOrEmpty(query.GroupId))
  658. {
  659. var guid = new Guid(query.GroupId);
  660. recordings = recordings.Where(i => GetRecordingGroupIds(i).Contains(guid));
  661. }
  662. if (query.IsInProgress.HasValue)
  663. {
  664. var val = query.IsInProgress.Value;
  665. recordings = recordings.Where(i => (i.Status == RecordingStatus.InProgress) == val);
  666. }
  667. if (query.Status.HasValue)
  668. {
  669. var val = query.Status.Value;
  670. recordings = recordings.Where(i => (i.Status == val));
  671. }
  672. if (!string.IsNullOrEmpty(query.SeriesTimerId))
  673. {
  674. var guid = new Guid(query.SeriesTimerId);
  675. var currentServiceName = service.Name;
  676. recordings = recordings
  677. .Where(i => _tvDtoService.GetInternalSeriesTimerId(currentServiceName, i.SeriesTimerId) == guid);
  678. }
  679. recordings = recordings.OrderByDescending(i => i.StartDate);
  680. IEnumerable<ILiveTvRecording> entities = await GetEntities(recordings, service.Name, cancellationToken).ConfigureAwait(false);
  681. if (user != null)
  682. {
  683. var currentUser = user;
  684. entities = entities.Where(i => i.IsParentalAllowed(currentUser));
  685. }
  686. if (query.StartIndex.HasValue)
  687. {
  688. entities = entities.Skip(query.StartIndex.Value);
  689. }
  690. if (query.Limit.HasValue)
  691. {
  692. entities = entities.Take(query.Limit.Value);
  693. }
  694. var returnArray = entities
  695. .Select(i =>
  696. {
  697. var channel = string.IsNullOrEmpty(i.RecordingInfo.ChannelId) ? null : GetInternalChannel(_tvDtoService.GetInternalChannelId(service.Name, i.RecordingInfo.ChannelId));
  698. return _tvDtoService.GetRecordingInfoDto(i, channel, service, user);
  699. })
  700. .ToArray();
  701. return new QueryResult<RecordingInfoDto>
  702. {
  703. Items = returnArray,
  704. TotalRecordCount = returnArray.Length
  705. };
  706. }
  707. private Task<ILiveTvRecording[]> GetEntities(IEnumerable<RecordingInfo> recordings, string serviceName, CancellationToken cancellationToken)
  708. {
  709. var tasks = recordings.Select(i => GetRecording(i, serviceName, cancellationToken));
  710. return Task.WhenAll(tasks);
  711. }
  712. private IEnumerable<ILiveTvService> GetServices(string serviceName, string channelId)
  713. {
  714. IEnumerable<ILiveTvService> services = _services;
  715. if (string.IsNullOrEmpty(serviceName) && !string.IsNullOrEmpty(channelId))
  716. {
  717. var channel = GetInternalChannel(channelId);
  718. if (channel != null)
  719. {
  720. serviceName = channel.ServiceName;
  721. }
  722. }
  723. if (!string.IsNullOrEmpty(serviceName))
  724. {
  725. services = services.Where(i => string.Equals(i.Name, serviceName, StringComparison.OrdinalIgnoreCase));
  726. }
  727. return services;
  728. }
  729. public async Task<QueryResult<TimerInfoDto>> GetTimers(TimerQuery query, CancellationToken cancellationToken)
  730. {
  731. var service = ActiveService;
  732. var timers = await service.GetTimersAsync(cancellationToken).ConfigureAwait(false);
  733. if (!string.IsNullOrEmpty(query.ChannelId))
  734. {
  735. var guid = new Guid(query.ChannelId);
  736. timers = timers.Where(i => guid == _tvDtoService.GetInternalChannelId(service.Name, i.ChannelId));
  737. }
  738. if (!string.IsNullOrEmpty(query.SeriesTimerId))
  739. {
  740. var guid = new Guid(query.SeriesTimerId);
  741. var currentServiceName = service.Name;
  742. timers = timers
  743. .Where(i => _tvDtoService.GetInternalSeriesTimerId(currentServiceName, i.SeriesTimerId) == guid);
  744. }
  745. var returnArray = timers
  746. .Select(i =>
  747. {
  748. var program = string.IsNullOrEmpty(i.ProgramId) ? null : GetInternalProgram(_tvDtoService.GetInternalProgramId(service.Name, i.ProgramId).ToString("N"));
  749. var channel = string.IsNullOrEmpty(i.ChannelId) ? null : GetInternalChannel(_tvDtoService.GetInternalChannelId(service.Name, i.ChannelId));
  750. return _tvDtoService.GetTimerInfoDto(i, service, program, channel);
  751. })
  752. .OrderBy(i => i.StartDate)
  753. .ToArray();
  754. return new QueryResult<TimerInfoDto>
  755. {
  756. Items = returnArray,
  757. TotalRecordCount = returnArray.Length
  758. };
  759. }
  760. public async Task DeleteRecording(string recordingId)
  761. {
  762. var recording = await GetRecording(recordingId, CancellationToken.None).ConfigureAwait(false);
  763. if (recording == null)
  764. {
  765. throw new ResourceNotFoundException(string.Format("Recording with Id {0} not found", recordingId));
  766. }
  767. var service = GetServices(recording.ServiceName, null)
  768. .First();
  769. await service.DeleteRecordingAsync(recording.ExternalId, CancellationToken.None).ConfigureAwait(false);
  770. }
  771. public async Task CancelTimer(string id)
  772. {
  773. var timer = await GetTimer(id, CancellationToken.None).ConfigureAwait(false);
  774. if (timer == null)
  775. {
  776. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  777. }
  778. var service = GetServices(timer.ServiceName, null)
  779. .First();
  780. await service.CancelTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  781. }
  782. public async Task CancelSeriesTimer(string id)
  783. {
  784. var timer = await GetSeriesTimer(id, CancellationToken.None).ConfigureAwait(false);
  785. if (timer == null)
  786. {
  787. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  788. }
  789. var service = GetServices(timer.ServiceName, null)
  790. .First();
  791. await service.CancelSeriesTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  792. }
  793. public async Task<RecordingInfoDto> GetRecording(string id, CancellationToken cancellationToken, User user = null)
  794. {
  795. var results = await GetRecordings(new RecordingQuery
  796. {
  797. UserId = user == null ? null : user.Id.ToString("N"),
  798. Id = id
  799. }, cancellationToken).ConfigureAwait(false);
  800. return results.Items.FirstOrDefault();
  801. }
  802. public async Task<TimerInfoDto> GetTimer(string id, CancellationToken cancellationToken)
  803. {
  804. var results = await GetTimers(new TimerQuery(), cancellationToken).ConfigureAwait(false);
  805. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.CurrentCulture));
  806. }
  807. public async Task<SeriesTimerInfoDto> GetSeriesTimer(string id, CancellationToken cancellationToken)
  808. {
  809. var results = await GetSeriesTimers(new SeriesTimerQuery(), cancellationToken).ConfigureAwait(false);
  810. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.CurrentCulture));
  811. }
  812. public async Task<QueryResult<SeriesTimerInfoDto>> GetSeriesTimers(SeriesTimerQuery query, CancellationToken cancellationToken)
  813. {
  814. var service = ActiveService;
  815. var timers = await service.GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false);
  816. if (string.Equals(query.SortBy, "Priority", StringComparison.OrdinalIgnoreCase))
  817. {
  818. timers = query.SortOrder == SortOrder.Descending ?
  819. timers.OrderBy(i => i.Priority).ThenByStringDescending(i => i.Name) :
  820. timers.OrderByDescending(i => i.Priority).ThenByString(i => i.Name);
  821. }
  822. else
  823. {
  824. timers = query.SortOrder == SortOrder.Descending ?
  825. timers.OrderByStringDescending(i => i.Name) :
  826. timers.OrderByString(i => i.Name);
  827. }
  828. var returnArray = timers
  829. .Select(i =>
  830. {
  831. string channelName = null;
  832. if (!string.IsNullOrEmpty(i.ChannelId))
  833. {
  834. var internalChannelId = _tvDtoService.GetInternalChannelId(service.Name, i.ChannelId);
  835. var channel = GetInternalChannel(internalChannelId);
  836. channelName = channel == null ? null : channel.Name;
  837. }
  838. return _tvDtoService.GetSeriesTimerInfoDto(i, service, channelName);
  839. })
  840. .ToArray();
  841. return new QueryResult<SeriesTimerInfoDto>
  842. {
  843. Items = returnArray,
  844. TotalRecordCount = returnArray.Length
  845. };
  846. }
  847. public Task<ChannelInfoDto> GetChannel(string id, CancellationToken cancellationToken, User user = null)
  848. {
  849. var channel = GetInternalChannel(id);
  850. var dto = _tvDtoService.GetChannelInfoDto(channel, GetCurrentProgram(channel.ExternalId), user);
  851. return Task.FromResult(dto);
  852. }
  853. private LiveTvProgram GetCurrentProgram(string externalChannelId)
  854. {
  855. var now = DateTime.UtcNow;
  856. return _programs.Values
  857. .Where(i => string.Equals(externalChannelId, i.ExternalChannelId, StringComparison.OrdinalIgnoreCase))
  858. .OrderBy(i => i.StartDate)
  859. .SkipWhile(i => now >= (i.EndDate ?? DateTime.MinValue))
  860. .FirstOrDefault();
  861. }
  862. private async Task<SeriesTimerInfo> GetNewTimerDefaultsInternal(CancellationToken cancellationToken, LiveTvProgram program = null)
  863. {
  864. ProgramInfo programInfo = null;
  865. if (program != null)
  866. {
  867. programInfo = new ProgramInfo
  868. {
  869. Audio = program.Audio,
  870. ChannelId = program.ExternalChannelId,
  871. CommunityRating = program.CommunityRating,
  872. EndDate = program.EndDate ?? DateTime.MinValue,
  873. EpisodeTitle = program.EpisodeTitle,
  874. Genres = program.Genres,
  875. HasImage = program.HasProviderImage,
  876. Id = program.ExternalId,
  877. IsHD = program.IsHD,
  878. IsKids = program.IsKids,
  879. IsLive = program.IsLive,
  880. IsMovie = program.IsMovie,
  881. IsNews = program.IsNews,
  882. IsPremiere = program.IsPremiere,
  883. IsRepeat = program.IsRepeat,
  884. IsSeries = program.IsSeries,
  885. IsSports = program.IsSports,
  886. OriginalAirDate = program.PremiereDate,
  887. Overview = program.Overview,
  888. StartDate = program.StartDate,
  889. ImagePath = program.ProviderImagePath,
  890. ImageUrl = program.ProviderImageUrl,
  891. Name = program.Name,
  892. OfficialRating = program.OfficialRating
  893. };
  894. }
  895. var info = await ActiveService.GetNewTimerDefaultsAsync(cancellationToken, programInfo).ConfigureAwait(false);
  896. info.Id = null;
  897. return info;
  898. }
  899. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(CancellationToken cancellationToken)
  900. {
  901. var info = await GetNewTimerDefaultsInternal(cancellationToken).ConfigureAwait(false);
  902. var obj = _tvDtoService.GetSeriesTimerInfoDto(info, ActiveService, null);
  903. return obj;
  904. }
  905. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(string programId, CancellationToken cancellationToken)
  906. {
  907. var program = GetInternalProgram(programId);
  908. var programDto = await GetProgram(programId, cancellationToken).ConfigureAwait(false);
  909. var defaults = await GetNewTimerDefaultsInternal(cancellationToken, program).ConfigureAwait(false);
  910. var info = _tvDtoService.GetSeriesTimerInfoDto(defaults, ActiveService, null);
  911. info.Days = new List<DayOfWeek>
  912. {
  913. program.StartDate.ToLocalTime().DayOfWeek
  914. };
  915. info.DayPattern = _tvDtoService.GetDayPattern(info.Days);
  916. info.Name = program.Name;
  917. info.ChannelId = programDto.ChannelId;
  918. info.ChannelName = programDto.ChannelName;
  919. info.StartDate = program.StartDate;
  920. info.Name = program.Name;
  921. info.Overview = program.Overview;
  922. info.ProgramId = programDto.Id;
  923. info.ExternalProgramId = programDto.ExternalId;
  924. if (program.EndDate.HasValue)
  925. {
  926. info.EndDate = program.EndDate.Value;
  927. }
  928. return info;
  929. }
  930. public async Task CreateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  931. {
  932. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  933. var info = await _tvDtoService.GetTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  934. // Set priority from default values
  935. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  936. info.Priority = defaultValues.Priority;
  937. await service.CreateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  938. }
  939. public async Task CreateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  940. {
  941. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  942. var info = await _tvDtoService.GetSeriesTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  943. // Set priority from default values
  944. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  945. info.Priority = defaultValues.Priority;
  946. await service.CreateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  947. }
  948. public async Task UpdateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  949. {
  950. var info = await _tvDtoService.GetTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  951. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  952. await service.UpdateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  953. }
  954. public async Task UpdateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  955. {
  956. var info = await _tvDtoService.GetSeriesTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  957. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  958. await service.UpdateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  959. }
  960. private IEnumerable<string> GetRecordingGroupNames(RecordingInfo recording)
  961. {
  962. var list = new List<string>();
  963. if (recording.IsSeries)
  964. {
  965. list.Add(recording.Name);
  966. }
  967. if (recording.IsKids)
  968. {
  969. list.Add("Kids");
  970. }
  971. if (recording.IsMovie)
  972. {
  973. list.Add("Movies");
  974. }
  975. if (recording.IsNews)
  976. {
  977. list.Add("News");
  978. }
  979. if (recording.IsSports)
  980. {
  981. list.Add("Sports");
  982. }
  983. if (!recording.IsSports && !recording.IsNews && !recording.IsMovie && !recording.IsKids && !recording.IsSeries)
  984. {
  985. list.Add("Others");
  986. }
  987. return list;
  988. }
  989. private List<Guid> GetRecordingGroupIds(RecordingInfo recording)
  990. {
  991. return GetRecordingGroupNames(recording).Select(i => i.ToLower()
  992. .GetMD5())
  993. .ToList();
  994. }
  995. public async Task<QueryResult<RecordingGroupDto>> GetRecordingGroups(RecordingGroupQuery query, CancellationToken cancellationToken)
  996. {
  997. var recordingResult = await GetRecordings(new RecordingQuery
  998. {
  999. UserId = query.UserId
  1000. }, cancellationToken).ConfigureAwait(false);
  1001. var recordings = recordingResult.Items;
  1002. var groups = new List<RecordingGroupDto>();
  1003. var series = recordings
  1004. .Where(i => i.IsSeries)
  1005. .ToLookup(i => i.Name, StringComparer.OrdinalIgnoreCase)
  1006. .ToList();
  1007. groups.AddRange(series.OrderByString(i => i.Key).Select(i => new RecordingGroupDto
  1008. {
  1009. Name = i.Key,
  1010. RecordingCount = i.Count()
  1011. }));
  1012. groups.Add(new RecordingGroupDto
  1013. {
  1014. Name = "Kids",
  1015. RecordingCount = recordings.Count(i => i.IsKids)
  1016. });
  1017. groups.Add(new RecordingGroupDto
  1018. {
  1019. Name = "Movies",
  1020. RecordingCount = recordings.Count(i => i.IsMovie)
  1021. });
  1022. groups.Add(new RecordingGroupDto
  1023. {
  1024. Name = "News",
  1025. RecordingCount = recordings.Count(i => i.IsNews)
  1026. });
  1027. groups.Add(new RecordingGroupDto
  1028. {
  1029. Name = "Sports",
  1030. RecordingCount = recordings.Count(i => i.IsSports)
  1031. });
  1032. groups.Add(new RecordingGroupDto
  1033. {
  1034. Name = "Others",
  1035. RecordingCount = recordings.Count(i => !i.IsSports && !i.IsNews && !i.IsMovie && !i.IsKids && !i.IsSeries)
  1036. });
  1037. groups = groups
  1038. .Where(i => i.RecordingCount > 0)
  1039. .ToList();
  1040. foreach (var group in groups)
  1041. {
  1042. group.Id = group.Name.ToLower().GetMD5().ToString("N");
  1043. }
  1044. return new QueryResult<RecordingGroupDto>
  1045. {
  1046. Items = groups.ToArray(),
  1047. TotalRecordCount = groups.Count
  1048. };
  1049. }
  1050. public async Task CloseLiveStream(string id, CancellationToken cancellationToken)
  1051. {
  1052. await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  1053. var service = ActiveService;
  1054. _logger.Info("Closing live stream from {0}, stream Id: {1}", service.Name, id);
  1055. try
  1056. {
  1057. await service.CloseLiveStream(id, cancellationToken).ConfigureAwait(false);
  1058. }
  1059. catch (Exception ex)
  1060. {
  1061. _logger.ErrorException("Error closing live stream", ex);
  1062. throw;
  1063. }
  1064. finally
  1065. {
  1066. _liveStreamSemaphore.Release();
  1067. }
  1068. }
  1069. public GuideInfo GetGuideInfo()
  1070. {
  1071. var programs = _programs.ToList();
  1072. var startDate = programs.Select(i => i.Value.StartDate).Min();
  1073. var endDate = programs.Select(i => i.Value.StartDate).Max();
  1074. return new GuideInfo
  1075. {
  1076. StartDate = startDate,
  1077. EndDate = endDate
  1078. };
  1079. }
  1080. /// <summary>
  1081. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1082. /// </summary>
  1083. public void Dispose()
  1084. {
  1085. Dispose(true);
  1086. }
  1087. private readonly object _disposeLock = new object();
  1088. /// <summary>
  1089. /// Releases unmanaged and - optionally - managed resources.
  1090. /// </summary>
  1091. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1092. protected virtual void Dispose(bool dispose)
  1093. {
  1094. if (dispose)
  1095. {
  1096. lock (_disposeLock)
  1097. {
  1098. foreach (var stream in _openStreams.Values.ToList())
  1099. {
  1100. var task = CloseLiveStream(stream.Id, CancellationToken.None);
  1101. Task.WaitAll(task);
  1102. }
  1103. _openStreams.Clear();
  1104. }
  1105. }
  1106. }
  1107. private async Task<IEnumerable<LiveTvServiceInfo>> GetServiceInfos(CancellationToken cancellationToken)
  1108. {
  1109. var tasks = Services.Select(i => GetServiceInfo(i, cancellationToken));
  1110. return await Task.WhenAll(tasks).ConfigureAwait(false);
  1111. }
  1112. private async Task<LiveTvServiceInfo> GetServiceInfo(ILiveTvService service, CancellationToken cancellationToken)
  1113. {
  1114. var info = new LiveTvServiceInfo
  1115. {
  1116. Name = service.Name
  1117. };
  1118. try
  1119. {
  1120. var statusInfo = await service.GetStatusInfoAsync(cancellationToken).ConfigureAwait(false);
  1121. info.Status = statusInfo.Status;
  1122. info.StatusMessage = statusInfo.StatusMessage;
  1123. info.Version = statusInfo.Version;
  1124. info.HasUpdateAvailable = statusInfo.HasUpdateAvailable;
  1125. info.HomePageUrl = service.HomePageUrl;
  1126. info.Tuners = statusInfo.Tuners.Select(i =>
  1127. {
  1128. string channelName = null;
  1129. if (!string.IsNullOrEmpty(i.ChannelId))
  1130. {
  1131. var internalChannelId = _tvDtoService.GetInternalChannelId(service.Name, i.ChannelId);
  1132. var channel = GetInternalChannel(internalChannelId);
  1133. channelName = channel == null ? null : channel.Name;
  1134. }
  1135. return _tvDtoService.GetTunerInfoDto(service.Name, i, channelName);
  1136. }).ToList();
  1137. }
  1138. catch (Exception ex)
  1139. {
  1140. _logger.ErrorException("Error getting service status info from {0}", ex, service.Name);
  1141. info.Status = LiveTvServiceStatus.Unavailable;
  1142. info.StatusMessage = ex.Message;
  1143. }
  1144. return info;
  1145. }
  1146. public async Task<LiveTvInfo> GetLiveTvInfo(CancellationToken cancellationToken)
  1147. {
  1148. var services = await GetServiceInfos(CancellationToken.None).ConfigureAwait(false);
  1149. var servicesList = services.ToList();
  1150. var activeServiceInfo = ActiveService == null ? null :
  1151. servicesList.FirstOrDefault(i => string.Equals(i.Name, ActiveService.Name, StringComparison.OrdinalIgnoreCase));
  1152. var info = new LiveTvInfo
  1153. {
  1154. Services = servicesList.ToList(),
  1155. ActiveServiceName = activeServiceInfo == null ? null : activeServiceInfo.Name,
  1156. IsEnabled = ActiveService != null,
  1157. Status = activeServiceInfo == null ? LiveTvServiceStatus.Unavailable : activeServiceInfo.Status,
  1158. StatusMessage = activeServiceInfo == null ? null : activeServiceInfo.StatusMessage
  1159. };
  1160. info.EnabledUsers = _userManager.Users
  1161. .Where(i => i.Configuration.EnableLiveTvAccess && info.IsEnabled)
  1162. .Select(i => i.Id.ToString("N"))
  1163. .ToList();
  1164. return info;
  1165. }
  1166. /// <summary>
  1167. /// Resets the tuner.
  1168. /// </summary>
  1169. /// <param name="id">The identifier.</param>
  1170. /// <param name="cancellationToken">The cancellation token.</param>
  1171. /// <returns>Task.</returns>
  1172. public Task ResetTuner(string id, CancellationToken cancellationToken)
  1173. {
  1174. return ActiveService.ResetTuner(id, cancellationToken);
  1175. }
  1176. }
  1177. }