LiveTvManager.cs 65 KB

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