LiveTvManager.cs 65 KB

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