LiveTvManager.cs 63 KB

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