LiveTvManager.cs 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581
  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.OrderBy(i => i.HasImage(ImageType.Primary) ? 0 : 1)
  453. .ThenByDescending(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. await _refreshSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  551. try
  552. {
  553. await RefreshChannelsInternal(progress, cancellationToken).ConfigureAwait(false);
  554. }
  555. finally
  556. {
  557. _refreshSemaphore.Release();
  558. }
  559. }
  560. private async Task RefreshChannelsInternal(IProgress<double> progress, CancellationToken cancellationToken)
  561. {
  562. // Avoid implicitly captured closure
  563. var service = ActiveService;
  564. if (service == null)
  565. {
  566. progress.Report(100);
  567. return;
  568. }
  569. progress.Report(10);
  570. var allChannels = await GetChannels(service, cancellationToken).ConfigureAwait(false);
  571. var allChannelsList = allChannels.ToList();
  572. var list = new List<LiveTvChannel>();
  573. var numComplete = 0;
  574. foreach (var channelInfo in allChannelsList)
  575. {
  576. cancellationToken.ThrowIfCancellationRequested();
  577. try
  578. {
  579. var item = await GetChannel(channelInfo.Item2, channelInfo.Item1, cancellationToken).ConfigureAwait(false);
  580. list.Add(item);
  581. _libraryManager.RegisterItem(item);
  582. }
  583. catch (OperationCanceledException)
  584. {
  585. throw;
  586. }
  587. catch (Exception ex)
  588. {
  589. _logger.ErrorException("Error getting channel information for {0}", ex, channelInfo.Item2.Name);
  590. }
  591. numComplete++;
  592. double percent = numComplete;
  593. percent /= allChannelsList.Count;
  594. progress.Report(5 * percent + 10);
  595. }
  596. _channelIdList = list.Select(i => i.Id).ToList();
  597. progress.Report(15);
  598. numComplete = 0;
  599. var programs = new List<LiveTvProgram>();
  600. var guideDays = GetGuideDays(list.Count);
  601. cancellationToken.ThrowIfCancellationRequested();
  602. foreach (var item in list)
  603. {
  604. cancellationToken.ThrowIfCancellationRequested();
  605. // Avoid implicitly captured closure
  606. var currentChannel = item;
  607. try
  608. {
  609. var start = DateTime.UtcNow.AddHours(-1);
  610. var end = start.AddDays(guideDays);
  611. var channelPrograms = await service.GetProgramsAsync(currentChannel.ExternalId, start, end, cancellationToken).ConfigureAwait(false);
  612. var programTasks = channelPrograms.Select(program => GetProgram(program, currentChannel.ChannelType, service.Name, cancellationToken));
  613. var programEntities = await Task.WhenAll(programTasks).ConfigureAwait(false);
  614. programs.AddRange(programEntities);
  615. }
  616. catch (OperationCanceledException)
  617. {
  618. throw;
  619. }
  620. catch (Exception ex)
  621. {
  622. _logger.ErrorException("Error getting programs for channel {0}", ex, currentChannel.Name);
  623. }
  624. numComplete++;
  625. double percent = numComplete;
  626. percent /= allChannelsList.Count;
  627. progress.Report(80 * percent + 10);
  628. }
  629. _programs = programs.ToDictionary(i => i.Id);
  630. progress.Report(90);
  631. // Load these now which will prefetch metadata
  632. await GetRecordings(new RecordingQuery(), cancellationToken).ConfigureAwait(false);
  633. progress.Report(100);
  634. }
  635. public async Task CleanDatabase(IProgress<double> progress, CancellationToken cancellationToken)
  636. {
  637. var service = ActiveService;
  638. if (service == null)
  639. {
  640. progress.Report(100);
  641. return;
  642. }
  643. await _refreshSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  644. try
  645. {
  646. await DeleteOldPrograms(_programs.Keys.ToList(), progress, cancellationToken).ConfigureAwait(false);
  647. }
  648. finally
  649. {
  650. _refreshSemaphore.Release();
  651. }
  652. }
  653. private async Task DeleteOldPrograms(List<Guid> currentIdList, IProgress<double> progress, CancellationToken cancellationToken)
  654. {
  655. var list = _itemRepo.GetItemsOfType(typeof(LiveTvProgram)).ToList();
  656. var numComplete = 0;
  657. foreach (var program in list)
  658. {
  659. cancellationToken.ThrowIfCancellationRequested();
  660. if (!currentIdList.Contains(program.Id))
  661. {
  662. await _libraryManager.DeleteItem(program).ConfigureAwait(false);
  663. }
  664. numComplete++;
  665. double percent = numComplete;
  666. percent /= list.Count;
  667. progress.Report(100 * percent);
  668. }
  669. }
  670. private double GetGuideDays(int channelCount)
  671. {
  672. if (_config.Configuration.LiveTvOptions.GuideDays.HasValue)
  673. {
  674. return _config.Configuration.LiveTvOptions.GuideDays.Value;
  675. }
  676. var programsPerDay = channelCount * 48;
  677. const int maxPrograms = 24000;
  678. var days = Math.Round(((double)maxPrograms) / programsPerDay);
  679. // No less than 2, no more than 7
  680. return Math.Max(2, Math.Min(days, 7));
  681. }
  682. private async Task<IEnumerable<Tuple<string, ChannelInfo>>> GetChannels(ILiveTvService service, CancellationToken cancellationToken)
  683. {
  684. var channels = await service.GetChannelsAsync(cancellationToken).ConfigureAwait(false);
  685. return channels.Select(i => new Tuple<string, ChannelInfo>(service.Name, i));
  686. }
  687. public async Task<QueryResult<RecordingInfoDto>> GetRecordings(RecordingQuery query, CancellationToken cancellationToken)
  688. {
  689. var service = ActiveService;
  690. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(new Guid(query.UserId));
  691. var recordings = await service.GetRecordingsAsync(cancellationToken).ConfigureAwait(false);
  692. if (!string.IsNullOrEmpty(query.ChannelId))
  693. {
  694. var guid = new Guid(query.ChannelId);
  695. var currentServiceName = service.Name;
  696. recordings = recordings
  697. .Where(i => _tvDtoService.GetInternalChannelId(currentServiceName, i.ChannelId) == guid);
  698. }
  699. if (!string.IsNullOrEmpty(query.Id))
  700. {
  701. var guid = new Guid(query.Id);
  702. var currentServiceName = service.Name;
  703. recordings = recordings
  704. .Where(i => _tvDtoService.GetInternalRecordingId(currentServiceName, i.Id) == guid);
  705. }
  706. if (!string.IsNullOrEmpty(query.GroupId))
  707. {
  708. var guid = new Guid(query.GroupId);
  709. recordings = recordings.Where(i => GetRecordingGroupIds(i).Contains(guid));
  710. }
  711. if (query.IsInProgress.HasValue)
  712. {
  713. var val = query.IsInProgress.Value;
  714. recordings = recordings.Where(i => (i.Status == RecordingStatus.InProgress) == val);
  715. }
  716. if (query.Status.HasValue)
  717. {
  718. var val = query.Status.Value;
  719. recordings = recordings.Where(i => (i.Status == val));
  720. }
  721. if (!string.IsNullOrEmpty(query.SeriesTimerId))
  722. {
  723. var guid = new Guid(query.SeriesTimerId);
  724. var currentServiceName = service.Name;
  725. recordings = recordings
  726. .Where(i => _tvDtoService.GetInternalSeriesTimerId(currentServiceName, i.SeriesTimerId) == guid);
  727. }
  728. recordings = recordings.OrderByDescending(i => i.StartDate);
  729. IEnumerable<ILiveTvRecording> entities = await GetEntities(recordings, service.Name, cancellationToken).ConfigureAwait(false);
  730. if (user != null)
  731. {
  732. var currentUser = user;
  733. entities = entities.Where(i => i.IsParentalAllowed(currentUser));
  734. }
  735. if (query.StartIndex.HasValue)
  736. {
  737. entities = entities.Skip(query.StartIndex.Value);
  738. }
  739. if (query.Limit.HasValue)
  740. {
  741. entities = entities.Take(query.Limit.Value);
  742. }
  743. var returnArray = entities
  744. .Select(i =>
  745. {
  746. var channel = string.IsNullOrEmpty(i.RecordingInfo.ChannelId) ? null : GetInternalChannel(_tvDtoService.GetInternalChannelId(service.Name, i.RecordingInfo.ChannelId));
  747. return _tvDtoService.GetRecordingInfoDto(i, channel, service, user);
  748. })
  749. .ToArray();
  750. return new QueryResult<RecordingInfoDto>
  751. {
  752. Items = returnArray,
  753. TotalRecordCount = returnArray.Length
  754. };
  755. }
  756. private Task<ILiveTvRecording[]> GetEntities(IEnumerable<RecordingInfo> recordings, string serviceName, CancellationToken cancellationToken)
  757. {
  758. var tasks = recordings.Select(i => GetRecording(i, serviceName, cancellationToken));
  759. return Task.WhenAll(tasks);
  760. }
  761. private IEnumerable<ILiveTvService> GetServices(string serviceName, string channelId)
  762. {
  763. IEnumerable<ILiveTvService> services = _services;
  764. if (string.IsNullOrEmpty(serviceName) && !string.IsNullOrEmpty(channelId))
  765. {
  766. var channel = GetInternalChannel(channelId);
  767. if (channel != null)
  768. {
  769. serviceName = channel.ServiceName;
  770. }
  771. }
  772. if (!string.IsNullOrEmpty(serviceName))
  773. {
  774. services = services.Where(i => string.Equals(i.Name, serviceName, StringComparison.OrdinalIgnoreCase));
  775. }
  776. return services;
  777. }
  778. public async Task<QueryResult<TimerInfoDto>> GetTimers(TimerQuery query, CancellationToken cancellationToken)
  779. {
  780. var service = ActiveService;
  781. var timers = await service.GetTimersAsync(cancellationToken).ConfigureAwait(false);
  782. if (!string.IsNullOrEmpty(query.ChannelId))
  783. {
  784. var guid = new Guid(query.ChannelId);
  785. timers = timers.Where(i => guid == _tvDtoService.GetInternalChannelId(service.Name, i.ChannelId));
  786. }
  787. if (!string.IsNullOrEmpty(query.SeriesTimerId))
  788. {
  789. var guid = new Guid(query.SeriesTimerId);
  790. var currentServiceName = service.Name;
  791. timers = timers
  792. .Where(i => _tvDtoService.GetInternalSeriesTimerId(currentServiceName, i.SeriesTimerId) == guid);
  793. }
  794. var returnArray = timers
  795. .Select(i =>
  796. {
  797. var program = string.IsNullOrEmpty(i.ProgramId) ? null : GetInternalProgram(_tvDtoService.GetInternalProgramId(service.Name, i.ProgramId).ToString("N"));
  798. var channel = string.IsNullOrEmpty(i.ChannelId) ? null : GetInternalChannel(_tvDtoService.GetInternalChannelId(service.Name, i.ChannelId));
  799. return _tvDtoService.GetTimerInfoDto(i, service, program, channel);
  800. })
  801. .OrderBy(i => i.StartDate)
  802. .ToArray();
  803. return new QueryResult<TimerInfoDto>
  804. {
  805. Items = returnArray,
  806. TotalRecordCount = returnArray.Length
  807. };
  808. }
  809. public async Task DeleteRecording(string recordingId)
  810. {
  811. var recording = await GetRecording(recordingId, CancellationToken.None).ConfigureAwait(false);
  812. if (recording == null)
  813. {
  814. throw new ResourceNotFoundException(string.Format("Recording with Id {0} not found", recordingId));
  815. }
  816. var service = GetServices(recording.ServiceName, null)
  817. .First();
  818. await service.DeleteRecordingAsync(recording.ExternalId, CancellationToken.None).ConfigureAwait(false);
  819. }
  820. public async Task CancelTimer(string id)
  821. {
  822. var timer = await GetTimer(id, CancellationToken.None).ConfigureAwait(false);
  823. if (timer == null)
  824. {
  825. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  826. }
  827. var service = GetServices(timer.ServiceName, null)
  828. .First();
  829. await service.CancelTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  830. }
  831. public async Task CancelSeriesTimer(string id)
  832. {
  833. var timer = await GetSeriesTimer(id, CancellationToken.None).ConfigureAwait(false);
  834. if (timer == null)
  835. {
  836. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  837. }
  838. var service = GetServices(timer.ServiceName, null)
  839. .First();
  840. await service.CancelSeriesTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  841. }
  842. public async Task<RecordingInfoDto> GetRecording(string id, CancellationToken cancellationToken, User user = null)
  843. {
  844. var results = await GetRecordings(new RecordingQuery
  845. {
  846. UserId = user == null ? null : user.Id.ToString("N"),
  847. Id = id
  848. }, cancellationToken).ConfigureAwait(false);
  849. return results.Items.FirstOrDefault();
  850. }
  851. public async Task<TimerInfoDto> GetTimer(string id, CancellationToken cancellationToken)
  852. {
  853. var results = await GetTimers(new TimerQuery(), cancellationToken).ConfigureAwait(false);
  854. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.CurrentCulture));
  855. }
  856. public async Task<SeriesTimerInfoDto> GetSeriesTimer(string id, CancellationToken cancellationToken)
  857. {
  858. var results = await GetSeriesTimers(new SeriesTimerQuery(), cancellationToken).ConfigureAwait(false);
  859. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.CurrentCulture));
  860. }
  861. public async Task<QueryResult<SeriesTimerInfoDto>> GetSeriesTimers(SeriesTimerQuery query, CancellationToken cancellationToken)
  862. {
  863. var service = ActiveService;
  864. var timers = await service.GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false);
  865. if (string.Equals(query.SortBy, "Priority", StringComparison.OrdinalIgnoreCase))
  866. {
  867. timers = query.SortOrder == SortOrder.Descending ?
  868. timers.OrderBy(i => i.Priority).ThenByStringDescending(i => i.Name) :
  869. timers.OrderByDescending(i => i.Priority).ThenByString(i => i.Name);
  870. }
  871. else
  872. {
  873. timers = query.SortOrder == SortOrder.Descending ?
  874. timers.OrderByStringDescending(i => i.Name) :
  875. timers.OrderByString(i => i.Name);
  876. }
  877. var returnArray = timers
  878. .Select(i =>
  879. {
  880. string channelName = null;
  881. if (!string.IsNullOrEmpty(i.ChannelId))
  882. {
  883. var internalChannelId = _tvDtoService.GetInternalChannelId(service.Name, i.ChannelId);
  884. var channel = GetInternalChannel(internalChannelId);
  885. channelName = channel == null ? null : channel.Name;
  886. }
  887. return _tvDtoService.GetSeriesTimerInfoDto(i, service, channelName);
  888. })
  889. .ToArray();
  890. return new QueryResult<SeriesTimerInfoDto>
  891. {
  892. Items = returnArray,
  893. TotalRecordCount = returnArray.Length
  894. };
  895. }
  896. public Task<ChannelInfoDto> GetChannel(string id, CancellationToken cancellationToken, User user = null)
  897. {
  898. var channel = GetInternalChannel(id);
  899. var dto = _tvDtoService.GetChannelInfoDto(channel, GetCurrentProgram(channel.ExternalId), user);
  900. return Task.FromResult(dto);
  901. }
  902. private LiveTvProgram GetCurrentProgram(string externalChannelId)
  903. {
  904. var now = DateTime.UtcNow;
  905. return _programs.Values
  906. .Where(i => string.Equals(externalChannelId, i.ExternalChannelId, StringComparison.OrdinalIgnoreCase))
  907. .OrderBy(i => i.StartDate)
  908. .SkipWhile(i => now >= (i.EndDate ?? DateTime.MinValue))
  909. .FirstOrDefault();
  910. }
  911. private async Task<SeriesTimerInfo> GetNewTimerDefaultsInternal(CancellationToken cancellationToken, LiveTvProgram program = null)
  912. {
  913. ProgramInfo programInfo = null;
  914. if (program != null)
  915. {
  916. programInfo = new ProgramInfo
  917. {
  918. Audio = program.Audio,
  919. ChannelId = program.ExternalChannelId,
  920. CommunityRating = program.CommunityRating,
  921. EndDate = program.EndDate ?? DateTime.MinValue,
  922. EpisodeTitle = program.EpisodeTitle,
  923. Genres = program.Genres,
  924. HasImage = program.HasProviderImage,
  925. Id = program.ExternalId,
  926. IsHD = program.IsHD,
  927. IsKids = program.IsKids,
  928. IsLive = program.IsLive,
  929. IsMovie = program.IsMovie,
  930. IsNews = program.IsNews,
  931. IsPremiere = program.IsPremiere,
  932. IsRepeat = program.IsRepeat,
  933. IsSeries = program.IsSeries,
  934. IsSports = program.IsSports,
  935. OriginalAirDate = program.PremiereDate,
  936. Overview = program.Overview,
  937. StartDate = program.StartDate,
  938. ImagePath = program.ProviderImagePath,
  939. ImageUrl = program.ProviderImageUrl,
  940. Name = program.Name,
  941. OfficialRating = program.OfficialRating
  942. };
  943. }
  944. var info = await ActiveService.GetNewTimerDefaultsAsync(cancellationToken, programInfo).ConfigureAwait(false);
  945. info.Id = null;
  946. return info;
  947. }
  948. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(CancellationToken cancellationToken)
  949. {
  950. var info = await GetNewTimerDefaultsInternal(cancellationToken).ConfigureAwait(false);
  951. var obj = _tvDtoService.GetSeriesTimerInfoDto(info, ActiveService, null);
  952. return obj;
  953. }
  954. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(string programId, CancellationToken cancellationToken)
  955. {
  956. var program = GetInternalProgram(programId);
  957. var programDto = await GetProgram(programId, cancellationToken).ConfigureAwait(false);
  958. var defaults = await GetNewTimerDefaultsInternal(cancellationToken, program).ConfigureAwait(false);
  959. var info = _tvDtoService.GetSeriesTimerInfoDto(defaults, ActiveService, null);
  960. info.Days = new List<DayOfWeek>
  961. {
  962. program.StartDate.ToLocalTime().DayOfWeek
  963. };
  964. info.DayPattern = _tvDtoService.GetDayPattern(info.Days);
  965. info.Name = program.Name;
  966. info.ChannelId = programDto.ChannelId;
  967. info.ChannelName = programDto.ChannelName;
  968. info.StartDate = program.StartDate;
  969. info.Name = program.Name;
  970. info.Overview = program.Overview;
  971. info.ProgramId = programDto.Id;
  972. info.ExternalProgramId = programDto.ExternalId;
  973. if (program.EndDate.HasValue)
  974. {
  975. info.EndDate = program.EndDate.Value;
  976. }
  977. return info;
  978. }
  979. public async Task CreateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  980. {
  981. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  982. var info = await _tvDtoService.GetTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  983. // Set priority from default values
  984. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  985. info.Priority = defaultValues.Priority;
  986. await service.CreateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  987. }
  988. public async Task CreateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  989. {
  990. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  991. var info = await _tvDtoService.GetSeriesTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  992. // Set priority from default values
  993. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  994. info.Priority = defaultValues.Priority;
  995. await service.CreateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  996. }
  997. public async Task UpdateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  998. {
  999. var info = await _tvDtoService.GetTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  1000. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  1001. await service.UpdateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1002. }
  1003. public async Task UpdateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  1004. {
  1005. var info = await _tvDtoService.GetSeriesTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  1006. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  1007. await service.UpdateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1008. }
  1009. private IEnumerable<string> GetRecordingGroupNames(RecordingInfo recording)
  1010. {
  1011. var list = new List<string>();
  1012. if (recording.IsSeries)
  1013. {
  1014. list.Add(recording.Name);
  1015. }
  1016. if (recording.IsKids)
  1017. {
  1018. list.Add("Kids");
  1019. }
  1020. if (recording.IsMovie)
  1021. {
  1022. list.Add("Movies");
  1023. }
  1024. if (recording.IsNews)
  1025. {
  1026. list.Add("News");
  1027. }
  1028. if (recording.IsSports)
  1029. {
  1030. list.Add("Sports");
  1031. }
  1032. if (!recording.IsSports && !recording.IsNews && !recording.IsMovie && !recording.IsKids && !recording.IsSeries)
  1033. {
  1034. list.Add("Others");
  1035. }
  1036. return list;
  1037. }
  1038. private List<Guid> GetRecordingGroupIds(RecordingInfo recording)
  1039. {
  1040. return GetRecordingGroupNames(recording).Select(i => i.ToLower()
  1041. .GetMD5())
  1042. .ToList();
  1043. }
  1044. public async Task<QueryResult<RecordingGroupDto>> GetRecordingGroups(RecordingGroupQuery query, CancellationToken cancellationToken)
  1045. {
  1046. var recordingResult = await GetRecordings(new RecordingQuery
  1047. {
  1048. UserId = query.UserId
  1049. }, cancellationToken).ConfigureAwait(false);
  1050. var recordings = recordingResult.Items;
  1051. var groups = new List<RecordingGroupDto>();
  1052. var series = recordings
  1053. .Where(i => i.IsSeries)
  1054. .ToLookup(i => i.Name, StringComparer.OrdinalIgnoreCase)
  1055. .ToList();
  1056. groups.AddRange(series.OrderByString(i => i.Key).Select(i => new RecordingGroupDto
  1057. {
  1058. Name = i.Key,
  1059. RecordingCount = i.Count()
  1060. }));
  1061. groups.Add(new RecordingGroupDto
  1062. {
  1063. Name = "Kids",
  1064. RecordingCount = recordings.Count(i => i.IsKids)
  1065. });
  1066. groups.Add(new RecordingGroupDto
  1067. {
  1068. Name = "Movies",
  1069. RecordingCount = recordings.Count(i => i.IsMovie)
  1070. });
  1071. groups.Add(new RecordingGroupDto
  1072. {
  1073. Name = "News",
  1074. RecordingCount = recordings.Count(i => i.IsNews)
  1075. });
  1076. groups.Add(new RecordingGroupDto
  1077. {
  1078. Name = "Sports",
  1079. RecordingCount = recordings.Count(i => i.IsSports)
  1080. });
  1081. groups.Add(new RecordingGroupDto
  1082. {
  1083. Name = "Others",
  1084. RecordingCount = recordings.Count(i => !i.IsSports && !i.IsNews && !i.IsMovie && !i.IsKids && !i.IsSeries)
  1085. });
  1086. groups = groups
  1087. .Where(i => i.RecordingCount > 0)
  1088. .ToList();
  1089. foreach (var group in groups)
  1090. {
  1091. group.Id = group.Name.ToLower().GetMD5().ToString("N");
  1092. }
  1093. return new QueryResult<RecordingGroupDto>
  1094. {
  1095. Items = groups.ToArray(),
  1096. TotalRecordCount = groups.Count
  1097. };
  1098. }
  1099. public async Task CloseLiveStream(string id, CancellationToken cancellationToken)
  1100. {
  1101. await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  1102. var service = ActiveService;
  1103. _logger.Info("Closing live stream from {0}, stream Id: {1}", service.Name, id);
  1104. try
  1105. {
  1106. await service.CloseLiveStream(id, cancellationToken).ConfigureAwait(false);
  1107. }
  1108. catch (Exception ex)
  1109. {
  1110. _logger.ErrorException("Error closing live stream", ex);
  1111. throw;
  1112. }
  1113. finally
  1114. {
  1115. _liveStreamSemaphore.Release();
  1116. }
  1117. }
  1118. public GuideInfo GetGuideInfo()
  1119. {
  1120. var programs = _programs.ToList();
  1121. var startDate = programs.Select(i => i.Value.StartDate).Min();
  1122. var endDate = programs.Select(i => i.Value.StartDate).Max();
  1123. return new GuideInfo
  1124. {
  1125. StartDate = startDate,
  1126. EndDate = endDate
  1127. };
  1128. }
  1129. /// <summary>
  1130. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1131. /// </summary>
  1132. public void Dispose()
  1133. {
  1134. Dispose(true);
  1135. }
  1136. private readonly object _disposeLock = new object();
  1137. /// <summary>
  1138. /// Releases unmanaged and - optionally - managed resources.
  1139. /// </summary>
  1140. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1141. protected virtual void Dispose(bool dispose)
  1142. {
  1143. if (dispose)
  1144. {
  1145. lock (_disposeLock)
  1146. {
  1147. foreach (var stream in _openStreams.Values.ToList())
  1148. {
  1149. var task = CloseLiveStream(stream.Id, CancellationToken.None);
  1150. Task.WaitAll(task);
  1151. }
  1152. _openStreams.Clear();
  1153. }
  1154. }
  1155. }
  1156. private async Task<IEnumerable<LiveTvServiceInfo>> GetServiceInfos(CancellationToken cancellationToken)
  1157. {
  1158. var tasks = Services.Select(i => GetServiceInfo(i, cancellationToken));
  1159. return await Task.WhenAll(tasks).ConfigureAwait(false);
  1160. }
  1161. private async Task<LiveTvServiceInfo> GetServiceInfo(ILiveTvService service, CancellationToken cancellationToken)
  1162. {
  1163. var info = new LiveTvServiceInfo
  1164. {
  1165. Name = service.Name
  1166. };
  1167. try
  1168. {
  1169. var statusInfo = await service.GetStatusInfoAsync(cancellationToken).ConfigureAwait(false);
  1170. info.Status = statusInfo.Status;
  1171. info.StatusMessage = statusInfo.StatusMessage;
  1172. info.Version = statusInfo.Version;
  1173. info.HasUpdateAvailable = statusInfo.HasUpdateAvailable;
  1174. info.HomePageUrl = service.HomePageUrl;
  1175. info.Tuners = statusInfo.Tuners.Select(i =>
  1176. {
  1177. string channelName = null;
  1178. if (!string.IsNullOrEmpty(i.ChannelId))
  1179. {
  1180. var internalChannelId = _tvDtoService.GetInternalChannelId(service.Name, i.ChannelId);
  1181. var channel = GetInternalChannel(internalChannelId);
  1182. channelName = channel == null ? null : channel.Name;
  1183. }
  1184. return _tvDtoService.GetTunerInfoDto(service.Name, i, channelName);
  1185. }).ToList();
  1186. }
  1187. catch (Exception ex)
  1188. {
  1189. _logger.ErrorException("Error getting service status info from {0}", ex, service.Name);
  1190. info.Status = LiveTvServiceStatus.Unavailable;
  1191. info.StatusMessage = ex.Message;
  1192. }
  1193. return info;
  1194. }
  1195. public async Task<LiveTvInfo> GetLiveTvInfo(CancellationToken cancellationToken)
  1196. {
  1197. var services = await GetServiceInfos(CancellationToken.None).ConfigureAwait(false);
  1198. var servicesList = services.ToList();
  1199. var activeServiceInfo = ActiveService == null ? null :
  1200. servicesList.FirstOrDefault(i => string.Equals(i.Name, ActiveService.Name, StringComparison.OrdinalIgnoreCase));
  1201. var info = new LiveTvInfo
  1202. {
  1203. Services = servicesList.ToList(),
  1204. ActiveServiceName = activeServiceInfo == null ? null : activeServiceInfo.Name,
  1205. IsEnabled = ActiveService != null,
  1206. Status = activeServiceInfo == null ? LiveTvServiceStatus.Unavailable : activeServiceInfo.Status,
  1207. StatusMessage = activeServiceInfo == null ? null : activeServiceInfo.StatusMessage
  1208. };
  1209. info.EnabledUsers = _userManager.Users
  1210. .Where(i => i.Configuration.EnableLiveTvAccess && info.IsEnabled)
  1211. .Select(i => i.Id.ToString("N"))
  1212. .ToList();
  1213. return info;
  1214. }
  1215. /// <summary>
  1216. /// Resets the tuner.
  1217. /// </summary>
  1218. /// <param name="id">The identifier.</param>
  1219. /// <param name="cancellationToken">The cancellation token.</param>
  1220. /// <returns>Task.</returns>
  1221. public Task ResetTuner(string id, CancellationToken cancellationToken)
  1222. {
  1223. return ActiveService.ResetTuner(id, cancellationToken);
  1224. }
  1225. }
  1226. }