LiveTvManager.cs 64 KB

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