LiveTvManager.cs 67 KB

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