LiveTvManager.cs 76 KB

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