LiveTvManager.cs 54 KB

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