LiveTvManager.cs 53 KB

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