LiveTvManager.cs 69 KB

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