LiveTvManager.cs 52 KB

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