LiveTvManager.cs 58 KB

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