LiveTvManager.cs 54 KB

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