LiveTvManager.cs 70 KB

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