LiveTvManager.cs 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using Emby.Server.Implementations.Library;
  7. using Emby.Server.Implementations.LiveTv.Listings;
  8. using MediaBrowser.Common.Configuration;
  9. using MediaBrowser.Common.Extensions;
  10. using MediaBrowser.Common.Net;
  11. using MediaBrowser.Common.Progress;
  12. using MediaBrowser.Common.Security;
  13. using MediaBrowser.Controller;
  14. using MediaBrowser.Controller.Channels;
  15. using MediaBrowser.Controller.Configuration;
  16. using MediaBrowser.Controller.Drawing;
  17. using MediaBrowser.Controller.Dto;
  18. using MediaBrowser.Controller.Entities;
  19. using MediaBrowser.Controller.Entities.Movies;
  20. using MediaBrowser.Controller.Entities.TV;
  21. using MediaBrowser.Controller.Library;
  22. using MediaBrowser.Controller.LiveTv;
  23. using MediaBrowser.Controller.Persistence;
  24. using MediaBrowser.Controller.Providers;
  25. using MediaBrowser.Controller.Sorting;
  26. using MediaBrowser.Model.Dto;
  27. using MediaBrowser.Model.Entities;
  28. using MediaBrowser.Model.Events;
  29. using MediaBrowser.Model.Extensions;
  30. using MediaBrowser.Model.Globalization;
  31. using MediaBrowser.Model.IO;
  32. using MediaBrowser.Model.LiveTv;
  33. using MediaBrowser.Model.Querying;
  34. using MediaBrowser.Model.Serialization;
  35. using MediaBrowser.Model.Tasks;
  36. using Microsoft.Extensions.Logging;
  37. namespace Emby.Server.Implementations.LiveTv
  38. {
  39. /// <summary>
  40. /// Class LiveTvManager
  41. /// </summary>
  42. public class LiveTvManager : ILiveTvManager, IDisposable
  43. {
  44. private readonly IServerConfigurationManager _config;
  45. private readonly ILogger _logger;
  46. private readonly IItemRepository _itemRepo;
  47. private readonly IUserManager _userManager;
  48. private readonly IUserDataManager _userDataManager;
  49. private readonly ILibraryManager _libraryManager;
  50. private readonly ITaskManager _taskManager;
  51. private readonly IJsonSerializer _jsonSerializer;
  52. private readonly IProviderManager _providerManager;
  53. private readonly ISecurityManager _security;
  54. private readonly Func<IChannelManager> _channelManager;
  55. private readonly IDtoService _dtoService;
  56. private readonly ILocalizationManager _localization;
  57. private readonly LiveTvDtoService _tvDtoService;
  58. private ILiveTvService[] _services = new ILiveTvService[] { };
  59. private ITunerHost[] _tunerHosts = Array.Empty<ITunerHost>();
  60. private IListingsProvider[] _listingProviders = Array.Empty<IListingsProvider>();
  61. private readonly IFileSystem _fileSystem;
  62. public event EventHandler<GenericEventArgs<TimerEventInfo>> SeriesTimerCancelled;
  63. public event EventHandler<GenericEventArgs<TimerEventInfo>> TimerCancelled;
  64. public event EventHandler<GenericEventArgs<TimerEventInfo>> TimerCreated;
  65. public event EventHandler<GenericEventArgs<TimerEventInfo>> SeriesTimerCreated;
  66. public string GetEmbyTvActiveRecordingPath(string id)
  67. {
  68. return EmbyTV.EmbyTV.Current.GetActiveRecordingPath(id);
  69. }
  70. private IServerApplicationHost _appHost;
  71. private IHttpClient _httpClient;
  72. public LiveTvManager(IServerApplicationHost appHost, IHttpClient httpClient, IServerConfigurationManager config, ILogger logger, IItemRepository itemRepo, IImageProcessor imageProcessor, IUserDataManager userDataManager, IDtoService dtoService, IUserManager userManager, ILibraryManager libraryManager, ITaskManager taskManager, ILocalizationManager localization, IJsonSerializer jsonSerializer, IProviderManager providerManager, IFileSystem fileSystem, ISecurityManager security, Func<IChannelManager> channelManager)
  73. {
  74. _appHost = appHost;
  75. _config = config;
  76. _logger = logger;
  77. _itemRepo = itemRepo;
  78. _userManager = userManager;
  79. _libraryManager = libraryManager;
  80. _taskManager = taskManager;
  81. _localization = localization;
  82. _jsonSerializer = jsonSerializer;
  83. _providerManager = providerManager;
  84. _fileSystem = fileSystem;
  85. _security = security;
  86. _dtoService = dtoService;
  87. _userDataManager = userDataManager;
  88. _channelManager = channelManager;
  89. _httpClient = httpClient;
  90. _tvDtoService = new LiveTvDtoService(dtoService, imageProcessor, logger, appHost, _libraryManager);
  91. }
  92. /// <summary>
  93. /// Gets the services.
  94. /// </summary>
  95. /// <value>The services.</value>
  96. public IReadOnlyList<ILiveTvService> Services => _services;
  97. private LiveTvOptions GetConfiguration()
  98. {
  99. return _config.GetConfiguration<LiveTvOptions>("livetv");
  100. }
  101. /// <summary>
  102. /// Adds the parts.
  103. /// </summary>
  104. /// <param name="services">The services.</param>
  105. /// <param name="tunerHosts">The tuner hosts.</param>
  106. /// <param name="listingProviders">The listing providers.</param>
  107. public void AddParts(IEnumerable<ILiveTvService> services, IEnumerable<ITunerHost> tunerHosts, IEnumerable<IListingsProvider> listingProviders)
  108. {
  109. _services = services.ToArray();
  110. _tunerHosts = tunerHosts.Where(i => i.IsSupported).ToArray();
  111. _listingProviders = listingProviders.ToArray();
  112. foreach (var service in _services)
  113. {
  114. service.DataSourceChanged += service_DataSourceChanged;
  115. if (service is EmbyTV.EmbyTV embyTv)
  116. {
  117. embyTv.TimerCreated += EmbyTv_TimerCreated;
  118. embyTv.TimerCancelled += EmbyTv_TimerCancelled;
  119. }
  120. }
  121. }
  122. private void EmbyTv_TimerCancelled(object sender, GenericEventArgs<string> e)
  123. {
  124. var timerId = e.Argument;
  125. TimerCancelled?.Invoke(this, new GenericEventArgs<TimerEventInfo>
  126. {
  127. Argument = new TimerEventInfo
  128. {
  129. Id = timerId
  130. }
  131. });
  132. }
  133. private void EmbyTv_TimerCreated(object sender, GenericEventArgs<TimerInfo> e)
  134. {
  135. var timer = e.Argument;
  136. var service = sender as ILiveTvService;
  137. TimerCreated?.Invoke(this, new GenericEventArgs<TimerEventInfo>
  138. {
  139. Argument = new TimerEventInfo
  140. {
  141. ProgramId = _tvDtoService.GetInternalProgramId(timer.ProgramId),
  142. Id = timer.Id
  143. }
  144. });
  145. }
  146. public ITunerHost[] TunerHosts => _tunerHosts;
  147. public IListingsProvider[] ListingProviders => _listingProviders;
  148. public List<NameIdPair> GetTunerHostTypes()
  149. {
  150. return _tunerHosts.OrderBy(i => i.Name).Select(i => new NameIdPair
  151. {
  152. Name = i.Name,
  153. Id = i.Type
  154. }).ToList();
  155. }
  156. public Task<List<TunerHostInfo>> DiscoverTuners(bool newDevicesOnly, CancellationToken cancellationToken)
  157. {
  158. return EmbyTV.EmbyTV.Current.DiscoverTuners(newDevicesOnly, cancellationToken);
  159. }
  160. void service_DataSourceChanged(object sender, EventArgs e)
  161. {
  162. if (!_isDisposed)
  163. {
  164. _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
  165. }
  166. }
  167. public QueryResult<BaseItem> GetInternalChannels(LiveTvChannelQuery query, DtoOptions dtoOptions, CancellationToken cancellationToken)
  168. {
  169. var user = query.UserId.Equals(Guid.Empty) ? null : _userManager.GetUserById(query.UserId);
  170. var topFolder = GetInternalLiveTvFolder(cancellationToken);
  171. var internalQuery = new InternalItemsQuery(user)
  172. {
  173. IsMovie = query.IsMovie,
  174. IsNews = query.IsNews,
  175. IsKids = query.IsKids,
  176. IsSports = query.IsSports,
  177. IsSeries = query.IsSeries,
  178. IncludeItemTypes = new[] { typeof(LiveTvChannel).Name },
  179. TopParentIds = new[] { topFolder.Id },
  180. IsFavorite = query.IsFavorite,
  181. IsLiked = query.IsLiked,
  182. StartIndex = query.StartIndex,
  183. Limit = query.Limit,
  184. DtoOptions = dtoOptions
  185. };
  186. var orderBy = internalQuery.OrderBy.ToList();
  187. orderBy.AddRange(query.SortBy.Select(i => new ValueTuple<string, SortOrder>(i, query.SortOrder ?? SortOrder.Ascending)));
  188. if (query.EnableFavoriteSorting)
  189. {
  190. orderBy.Insert(0, new ValueTuple<string, SortOrder>(ItemSortBy.IsFavoriteOrLiked, SortOrder.Descending));
  191. }
  192. if (!internalQuery.OrderBy.Any(i => string.Equals(i.Item1, ItemSortBy.SortName, StringComparison.OrdinalIgnoreCase)))
  193. {
  194. orderBy.Add(new ValueTuple<string, SortOrder>(ItemSortBy.SortName, SortOrder.Ascending));
  195. }
  196. internalQuery.OrderBy = orderBy.ToArray();
  197. return _libraryManager.GetItemsResult(internalQuery);
  198. }
  199. public async Task<Tuple<MediaSourceInfo, ILiveStream>> GetChannelStream(string id, string mediaSourceId, List<ILiveStream> currentLiveStreams, CancellationToken cancellationToken)
  200. {
  201. if (string.Equals(id, mediaSourceId, StringComparison.OrdinalIgnoreCase))
  202. {
  203. mediaSourceId = null;
  204. }
  205. var channel = (LiveTvChannel)_libraryManager.GetItemById(id);
  206. bool isVideo = channel.ChannelType == ChannelType.TV;
  207. var service = GetService(channel);
  208. _logger.LogInformation("Opening channel stream from {0}, external channel Id: {1}", service.Name, channel.ExternalId);
  209. MediaSourceInfo info;
  210. ILiveStream liveStream;
  211. if (service is ISupportsDirectStreamProvider supportsManagedStream)
  212. {
  213. liveStream = await supportsManagedStream.GetChannelStreamWithDirectStreamProvider(channel.ExternalId, mediaSourceId, currentLiveStreams, cancellationToken).ConfigureAwait(false);
  214. info = liveStream.MediaSource;
  215. }
  216. else
  217. {
  218. info = await service.GetChannelStream(channel.ExternalId, mediaSourceId, cancellationToken).ConfigureAwait(false);
  219. var openedId = info.Id;
  220. Func<Task> closeFn = () => service.CloseLiveStream(openedId, CancellationToken.None);
  221. liveStream = new ExclusiveLiveStream(info, closeFn);
  222. var startTime = DateTime.UtcNow;
  223. await liveStream.Open(cancellationToken).ConfigureAwait(false);
  224. var endTime = DateTime.UtcNow;
  225. _logger.LogInformation("Live stream opened after {0}ms", (endTime - startTime).TotalMilliseconds);
  226. }
  227. info.RequiresClosing = true;
  228. var idPrefix = service.GetType().FullName.GetMD5().ToString("N") + "_";
  229. info.LiveStreamId = idPrefix + info.Id;
  230. Normalize(info, service, isVideo);
  231. return new Tuple<MediaSourceInfo, ILiveStream>(info, liveStream);
  232. }
  233. public async Task<IEnumerable<MediaSourceInfo>> GetChannelMediaSources(BaseItem item, CancellationToken cancellationToken)
  234. {
  235. var baseItem = (LiveTvChannel)item;
  236. var service = GetService(baseItem);
  237. var sources = await service.GetChannelStreamMediaSources(baseItem.ExternalId, cancellationToken).ConfigureAwait(false);
  238. if (sources.Count == 0)
  239. {
  240. throw new NotImplementedException();
  241. }
  242. foreach (var source in sources)
  243. {
  244. Normalize(source, service, baseItem.ChannelType == ChannelType.TV);
  245. }
  246. return sources;
  247. }
  248. private ILiveTvService GetService(LiveTvChannel item)
  249. {
  250. var name = item.ServiceName;
  251. return GetService(name);
  252. }
  253. private ILiveTvService GetService(LiveTvProgram item)
  254. {
  255. var channel = _libraryManager.GetItemById(item.ChannelId) as LiveTvChannel;
  256. return GetService(channel);
  257. }
  258. private ILiveTvService GetService(string name)
  259. {
  260. return _services.FirstOrDefault(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase));
  261. }
  262. private static void Normalize(MediaSourceInfo mediaSource, ILiveTvService service, bool isVideo)
  263. {
  264. // Not all of the plugins are setting this
  265. mediaSource.IsInfiniteStream = true;
  266. if (mediaSource.MediaStreams.Count == 0)
  267. {
  268. if (isVideo)
  269. {
  270. mediaSource.MediaStreams.AddRange(new List<MediaStream>
  271. {
  272. new MediaStream
  273. {
  274. Type = MediaStreamType.Video,
  275. // Set the index to -1 because we don't know the exact index of the video stream within the container
  276. Index = -1,
  277. // Set to true if unknown to enable deinterlacing
  278. IsInterlaced = true
  279. },
  280. new MediaStream
  281. {
  282. Type = MediaStreamType.Audio,
  283. // Set the index to -1 because we don't know the exact index of the audio stream within the container
  284. Index = -1
  285. }
  286. });
  287. }
  288. else
  289. {
  290. mediaSource.MediaStreams.AddRange(new List<MediaStream>
  291. {
  292. new MediaStream
  293. {
  294. Type = MediaStreamType.Audio,
  295. // Set the index to -1 because we don't know the exact index of the audio stream within the container
  296. Index = -1
  297. }
  298. });
  299. }
  300. }
  301. // Clean some bad data coming from providers
  302. foreach (var stream in mediaSource.MediaStreams)
  303. {
  304. if (stream.BitRate.HasValue && stream.BitRate <= 0)
  305. {
  306. stream.BitRate = null;
  307. }
  308. if (stream.Channels.HasValue && stream.Channels <= 0)
  309. {
  310. stream.Channels = null;
  311. }
  312. if (stream.AverageFrameRate.HasValue && stream.AverageFrameRate <= 0)
  313. {
  314. stream.AverageFrameRate = null;
  315. }
  316. if (stream.RealFrameRate.HasValue && stream.RealFrameRate <= 0)
  317. {
  318. stream.RealFrameRate = null;
  319. }
  320. if (stream.Width.HasValue && stream.Width <= 0)
  321. {
  322. stream.Width = null;
  323. }
  324. if (stream.Height.HasValue && stream.Height <= 0)
  325. {
  326. stream.Height = null;
  327. }
  328. if (stream.SampleRate.HasValue && stream.SampleRate <= 0)
  329. {
  330. stream.SampleRate = null;
  331. }
  332. if (stream.Level.HasValue && stream.Level <= 0)
  333. {
  334. stream.Level = null;
  335. }
  336. }
  337. var indexes = mediaSource.MediaStreams.Select(i => i.Index).Distinct().ToList();
  338. // If there are duplicate stream indexes, set them all to unknown
  339. if (indexes.Count != mediaSource.MediaStreams.Count)
  340. {
  341. foreach (var stream in mediaSource.MediaStreams)
  342. {
  343. stream.Index = -1;
  344. }
  345. }
  346. // Set the total bitrate if not already supplied
  347. mediaSource.InferTotalBitrate();
  348. if (!(service is EmbyTV.EmbyTV))
  349. {
  350. // We can't trust that we'll be able to direct stream it through emby server, no matter what the provider says
  351. //mediaSource.SupportsDirectPlay = false;
  352. //mediaSource.SupportsDirectStream = false;
  353. mediaSource.SupportsTranscoding = true;
  354. foreach (var stream in mediaSource.MediaStreams)
  355. {
  356. if (stream.Type == MediaStreamType.Video && string.IsNullOrWhiteSpace(stream.NalLengthSize))
  357. {
  358. stream.NalLengthSize = "0";
  359. }
  360. if (stream.Type == MediaStreamType.Video)
  361. {
  362. stream.IsInterlaced = true;
  363. }
  364. }
  365. }
  366. }
  367. private const string ExternalServiceTag = "ExternalServiceId";
  368. private LiveTvChannel GetChannel(ChannelInfo channelInfo, string serviceName, BaseItem parentFolder, CancellationToken cancellationToken)
  369. {
  370. var parentFolderId = parentFolder.Id;
  371. var isNew = false;
  372. var forceUpdate = false;
  373. var id = _tvDtoService.GetInternalChannelId(serviceName, channelInfo.Id);
  374. var item = _libraryManager.GetItemById(id) as LiveTvChannel;
  375. if (item == null)
  376. {
  377. item = new LiveTvChannel
  378. {
  379. Name = channelInfo.Name,
  380. Id = id,
  381. DateCreated = DateTime.UtcNow
  382. };
  383. isNew = true;
  384. }
  385. if (channelInfo.Tags != null)
  386. {
  387. if (!channelInfo.Tags.SequenceEqual(item.Tags, StringComparer.OrdinalIgnoreCase))
  388. {
  389. isNew = true;
  390. }
  391. item.Tags = channelInfo.Tags;
  392. }
  393. if (!item.ParentId.Equals(parentFolderId))
  394. {
  395. isNew = true;
  396. }
  397. item.ParentId = parentFolderId;
  398. item.ChannelType = channelInfo.ChannelType;
  399. item.ServiceName = serviceName;
  400. if (!string.Equals(item.GetProviderId(ExternalServiceTag), serviceName, StringComparison.OrdinalIgnoreCase))
  401. {
  402. forceUpdate = true;
  403. }
  404. item.SetProviderId(ExternalServiceTag, serviceName);
  405. if (!string.Equals(channelInfo.Id, item.ExternalId, StringComparison.Ordinal))
  406. {
  407. forceUpdate = true;
  408. }
  409. item.ExternalId = channelInfo.Id;
  410. if (!string.Equals(channelInfo.Number, item.Number, StringComparison.Ordinal))
  411. {
  412. forceUpdate = true;
  413. }
  414. item.Number = channelInfo.Number;
  415. if (!string.Equals(channelInfo.Name, item.Name, StringComparison.Ordinal))
  416. {
  417. forceUpdate = true;
  418. }
  419. item.Name = channelInfo.Name;
  420. if (!item.HasImage(ImageType.Primary))
  421. {
  422. if (!string.IsNullOrWhiteSpace(channelInfo.ImagePath))
  423. {
  424. item.SetImagePath(ImageType.Primary, channelInfo.ImagePath);
  425. forceUpdate = true;
  426. }
  427. else if (!string.IsNullOrWhiteSpace(channelInfo.ImageUrl))
  428. {
  429. item.SetImagePath(ImageType.Primary, channelInfo.ImageUrl);
  430. forceUpdate = true;
  431. }
  432. }
  433. if (isNew)
  434. {
  435. _libraryManager.CreateItem(item, parentFolder);
  436. }
  437. else if (forceUpdate)
  438. {
  439. _libraryManager.UpdateItem(item, parentFolder, ItemUpdateType.MetadataImport, cancellationToken);
  440. }
  441. return item;
  442. }
  443. private const string EtagKey = "ProgramEtag";
  444. private Tuple<LiveTvProgram, bool, bool> GetProgram(ProgramInfo info, Dictionary<Guid, LiveTvProgram> allExistingPrograms, LiveTvChannel channel, ChannelType channelType, string serviceName, CancellationToken cancellationToken)
  445. {
  446. var id = _tvDtoService.GetInternalProgramId(info.Id);
  447. var isNew = false;
  448. var forceUpdate = false;
  449. if (!allExistingPrograms.TryGetValue(id, out var item))
  450. {
  451. isNew = true;
  452. item = new LiveTvProgram
  453. {
  454. Name = info.Name,
  455. Id = id,
  456. DateCreated = DateTime.UtcNow,
  457. DateModified = DateTime.UtcNow
  458. };
  459. if (!string.IsNullOrEmpty(info.Etag))
  460. {
  461. item.SetProviderId(EtagKey, info.Etag);
  462. }
  463. }
  464. if (!string.Equals(info.ShowId, item.ShowId, StringComparison.OrdinalIgnoreCase))
  465. {
  466. item.ShowId = info.ShowId;
  467. forceUpdate = true;
  468. }
  469. var seriesId = info.SeriesId;
  470. if (!item.ParentId.Equals(channel.Id))
  471. {
  472. forceUpdate = true;
  473. }
  474. item.ParentId = channel.Id;
  475. //item.ChannelType = channelType;
  476. item.Audio = info.Audio;
  477. item.ChannelId = channel.Id;
  478. item.CommunityRating = item.CommunityRating ?? info.CommunityRating;
  479. if ((item.CommunityRating ?? 0).Equals(0))
  480. {
  481. item.CommunityRating = null;
  482. }
  483. item.EpisodeTitle = info.EpisodeTitle;
  484. item.ExternalId = info.Id;
  485. if (!string.IsNullOrWhiteSpace(seriesId) && !string.Equals(item.ExternalSeriesId, seriesId, StringComparison.Ordinal))
  486. {
  487. forceUpdate = true;
  488. }
  489. item.ExternalSeriesId = seriesId;
  490. var isSeries = info.IsSeries || !string.IsNullOrEmpty(info.EpisodeTitle);
  491. if (isSeries || !string.IsNullOrEmpty(info.EpisodeTitle))
  492. {
  493. item.SeriesName = info.Name;
  494. }
  495. var tags = new List<string>();
  496. if (info.IsLive)
  497. {
  498. tags.Add("Live");
  499. }
  500. if (info.IsPremiere)
  501. {
  502. tags.Add("Premiere");
  503. }
  504. if (info.IsNews)
  505. {
  506. tags.Add("News");
  507. }
  508. if (info.IsSports)
  509. {
  510. tags.Add("Sports");
  511. }
  512. if (info.IsKids)
  513. {
  514. tags.Add("Kids");
  515. }
  516. if (info.IsRepeat)
  517. {
  518. tags.Add("Repeat");
  519. }
  520. if (info.IsMovie)
  521. {
  522. tags.Add("Movie");
  523. }
  524. if (isSeries)
  525. {
  526. tags.Add("Series");
  527. }
  528. item.Tags = tags.ToArray();
  529. item.Genres = info.Genres.ToArray();
  530. if (info.IsHD ?? false)
  531. {
  532. item.Width = 1280;
  533. item.Height = 720;
  534. }
  535. item.IsMovie = info.IsMovie;
  536. item.IsRepeat = info.IsRepeat;
  537. if (item.IsSeries != isSeries)
  538. {
  539. forceUpdate = true;
  540. }
  541. item.IsSeries = isSeries;
  542. item.Name = info.Name;
  543. item.OfficialRating = item.OfficialRating ?? info.OfficialRating;
  544. item.Overview = item.Overview ?? info.Overview;
  545. item.RunTimeTicks = (info.EndDate - info.StartDate).Ticks;
  546. item.ProviderIds = info.ProviderIds;
  547. foreach (var providerId in info.SeriesProviderIds)
  548. {
  549. info.ProviderIds["Series" + providerId.Key] = providerId.Value;
  550. }
  551. if (item.StartDate != info.StartDate)
  552. {
  553. forceUpdate = true;
  554. }
  555. item.StartDate = info.StartDate;
  556. if (item.EndDate != info.EndDate)
  557. {
  558. forceUpdate = true;
  559. }
  560. item.EndDate = info.EndDate;
  561. item.ProductionYear = info.ProductionYear;
  562. if (!isSeries || info.IsRepeat)
  563. {
  564. item.PremiereDate = info.OriginalAirDate;
  565. }
  566. item.IndexNumber = info.EpisodeNumber;
  567. item.ParentIndexNumber = info.SeasonNumber;
  568. if (!item.HasImage(ImageType.Primary))
  569. {
  570. if (!string.IsNullOrWhiteSpace(info.ImagePath))
  571. {
  572. item.SetImage(new ItemImageInfo
  573. {
  574. Path = info.ImagePath,
  575. Type = ImageType.Primary
  576. }, 0);
  577. }
  578. else if (!string.IsNullOrWhiteSpace(info.ImageUrl))
  579. {
  580. item.SetImage(new ItemImageInfo
  581. {
  582. Path = info.ImageUrl,
  583. Type = ImageType.Primary
  584. }, 0);
  585. }
  586. }
  587. if (!item.HasImage(ImageType.Thumb))
  588. {
  589. if (!string.IsNullOrWhiteSpace(info.ThumbImageUrl))
  590. {
  591. item.SetImage(new ItemImageInfo
  592. {
  593. Path = info.ThumbImageUrl,
  594. Type = ImageType.Thumb
  595. }, 0);
  596. }
  597. }
  598. if (!item.HasImage(ImageType.Logo))
  599. {
  600. if (!string.IsNullOrWhiteSpace(info.LogoImageUrl))
  601. {
  602. item.SetImage(new ItemImageInfo
  603. {
  604. Path = info.LogoImageUrl,
  605. Type = ImageType.Logo
  606. }, 0);
  607. }
  608. }
  609. if (!item.HasImage(ImageType.Backdrop))
  610. {
  611. if (!string.IsNullOrWhiteSpace(info.BackdropImageUrl))
  612. {
  613. item.SetImage(new ItemImageInfo
  614. {
  615. Path = info.BackdropImageUrl,
  616. Type = ImageType.Backdrop
  617. }, 0);
  618. }
  619. }
  620. var isUpdated = false;
  621. if (isNew)
  622. {
  623. }
  624. else if (forceUpdate || string.IsNullOrWhiteSpace(info.Etag))
  625. {
  626. isUpdated = true;
  627. }
  628. else
  629. {
  630. var etag = info.Etag;
  631. if (!string.Equals(etag, item.GetProviderId(EtagKey), StringComparison.OrdinalIgnoreCase))
  632. {
  633. item.SetProviderId(EtagKey, etag);
  634. isUpdated = true;
  635. }
  636. }
  637. if (isNew || isUpdated)
  638. {
  639. item.OnMetadataChanged();
  640. }
  641. return new Tuple<LiveTvProgram, bool, bool>(item, isNew, isUpdated);
  642. }
  643. public async Task<BaseItemDto> GetProgram(string id, CancellationToken cancellationToken, User user = null)
  644. {
  645. var program = _libraryManager.GetItemById(id);
  646. var dto = _dtoService.GetBaseItemDto(program, new DtoOptions(), user);
  647. var list = new List<Tuple<BaseItemDto, string, string>>() {
  648. new Tuple<BaseItemDto, string, string>(dto, program.ExternalId, program.ExternalSeriesId)
  649. };
  650. await AddRecordingInfo(list, cancellationToken).ConfigureAwait(false);
  651. return dto;
  652. }
  653. public async Task<QueryResult<BaseItemDto>> GetPrograms(InternalItemsQuery query, DtoOptions options, CancellationToken cancellationToken)
  654. {
  655. var user = query.User;
  656. var topFolder = GetInternalLiveTvFolder(cancellationToken);
  657. if (query.OrderBy.Length == 0)
  658. {
  659. if (query.IsAiring ?? false)
  660. {
  661. // Unless something else was specified, order by start date to take advantage of a specialized index
  662. query.OrderBy = new ValueTuple<string, SortOrder>[]
  663. {
  664. new ValueTuple<string, SortOrder>(ItemSortBy.StartDate, SortOrder.Ascending)
  665. };
  666. }
  667. else
  668. {
  669. // Unless something else was specified, order by start date to take advantage of a specialized index
  670. query.OrderBy = new ValueTuple<string, SortOrder>[]
  671. {
  672. new ValueTuple<string, SortOrder>(ItemSortBy.StartDate, SortOrder.Ascending)
  673. };
  674. }
  675. }
  676. RemoveFields(options);
  677. var internalQuery = new InternalItemsQuery(user)
  678. {
  679. IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
  680. MinEndDate = query.MinEndDate,
  681. MinStartDate = query.MinStartDate,
  682. MaxEndDate = query.MaxEndDate,
  683. MaxStartDate = query.MaxStartDate,
  684. ChannelIds = query.ChannelIds,
  685. IsMovie = query.IsMovie,
  686. IsSeries = query.IsSeries,
  687. IsSports = query.IsSports,
  688. IsKids = query.IsKids,
  689. IsNews = query.IsNews,
  690. Genres = query.Genres,
  691. GenreIds = query.GenreIds,
  692. StartIndex = query.StartIndex,
  693. Limit = query.Limit,
  694. OrderBy = query.OrderBy,
  695. EnableTotalRecordCount = query.EnableTotalRecordCount,
  696. TopParentIds = new[] { topFolder.Id },
  697. Name = query.Name,
  698. DtoOptions = options,
  699. HasAired = query.HasAired,
  700. IsAiring = query.IsAiring
  701. };
  702. if (!string.IsNullOrWhiteSpace(query.SeriesTimerId))
  703. {
  704. var seriesTimers = await GetSeriesTimersInternal(new SeriesTimerQuery { }, cancellationToken).ConfigureAwait(false);
  705. var seriesTimer = seriesTimers.Items.FirstOrDefault(i => string.Equals(_tvDtoService.GetInternalSeriesTimerId(i.Id).ToString("N"), query.SeriesTimerId, StringComparison.OrdinalIgnoreCase));
  706. if (seriesTimer != null)
  707. {
  708. internalQuery.ExternalSeriesId = seriesTimer.SeriesId;
  709. if (string.IsNullOrWhiteSpace(seriesTimer.SeriesId))
  710. {
  711. // Better to return nothing than every program in the database
  712. return new QueryResult<BaseItemDto>();
  713. }
  714. }
  715. else
  716. {
  717. // Better to return nothing than every program in the database
  718. return new QueryResult<BaseItemDto>();
  719. }
  720. }
  721. var queryResult = _libraryManager.QueryItems(internalQuery);
  722. var returnArray = _dtoService.GetBaseItemDtos(queryResult.Items, options, user);
  723. var result = new QueryResult<BaseItemDto>
  724. {
  725. Items = returnArray,
  726. TotalRecordCount = queryResult.TotalRecordCount
  727. };
  728. return result;
  729. }
  730. public QueryResult<BaseItem> GetRecommendedProgramsInternal(InternalItemsQuery query, DtoOptions options, CancellationToken cancellationToken)
  731. {
  732. var user = query.User;
  733. var topFolder = GetInternalLiveTvFolder(cancellationToken);
  734. var internalQuery = new InternalItemsQuery(user)
  735. {
  736. IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
  737. IsAiring = query.IsAiring,
  738. HasAired = query.HasAired,
  739. IsNews = query.IsNews,
  740. IsMovie = query.IsMovie,
  741. IsSeries = query.IsSeries,
  742. IsSports = query.IsSports,
  743. IsKids = query.IsKids,
  744. EnableTotalRecordCount = query.EnableTotalRecordCount,
  745. OrderBy = new[] { new ValueTuple<string, SortOrder>(ItemSortBy.StartDate, SortOrder.Ascending) },
  746. TopParentIds = new[] { topFolder.Id },
  747. DtoOptions = options,
  748. GenreIds = query.GenreIds
  749. };
  750. if (query.Limit.HasValue)
  751. {
  752. internalQuery.Limit = Math.Max(query.Limit.Value * 4, 200);
  753. }
  754. var programList = _libraryManager.QueryItems(internalQuery).Items;
  755. var totalCount = programList.Length;
  756. var orderedPrograms = programList.Cast<LiveTvProgram>().OrderBy(i => i.StartDate.Date);
  757. if (query.IsAiring ?? false)
  758. {
  759. orderedPrograms = orderedPrograms
  760. .ThenByDescending(i => GetRecommendationScore(i, user, true));
  761. }
  762. IEnumerable<BaseItem> programs = orderedPrograms;
  763. if (query.Limit.HasValue)
  764. {
  765. programs = programs.Take(query.Limit.Value);
  766. }
  767. return new QueryResult<BaseItem>
  768. {
  769. Items = programs.ToArray(),
  770. TotalRecordCount = totalCount
  771. };
  772. }
  773. public QueryResult<BaseItemDto> GetRecommendedPrograms(InternalItemsQuery query, DtoOptions options, CancellationToken cancellationToken)
  774. {
  775. if (!(query.IsAiring ?? false))
  776. {
  777. return GetPrograms(query, options, cancellationToken).Result;
  778. }
  779. RemoveFields(options);
  780. var internalResult = GetRecommendedProgramsInternal(query, options, cancellationToken);
  781. return new QueryResult<BaseItemDto>
  782. {
  783. Items = _dtoService.GetBaseItemDtos(internalResult.Items, options, query.User),
  784. TotalRecordCount = internalResult.TotalRecordCount
  785. };
  786. }
  787. private int GetRecommendationScore(LiveTvProgram program, User user, bool factorChannelWatchCount)
  788. {
  789. var score = 0;
  790. if (program.IsLive)
  791. {
  792. score++;
  793. }
  794. if (program.IsSeries && !program.IsRepeat)
  795. {
  796. score++;
  797. }
  798. var channel = _libraryManager.GetItemById(program.ChannelId);
  799. if (channel == null)
  800. {
  801. return score;
  802. }
  803. var channelUserdata = _userDataManager.GetUserData(user, channel);
  804. if (channelUserdata.Likes.HasValue)
  805. {
  806. score += channelUserdata.Likes.Value ? 2 : -2;
  807. }
  808. if (channelUserdata.IsFavorite)
  809. {
  810. score += 3;
  811. }
  812. if (factorChannelWatchCount)
  813. {
  814. score += channelUserdata.PlayCount;
  815. }
  816. return score;
  817. }
  818. private async Task AddRecordingInfo(IEnumerable<Tuple<BaseItemDto, string, string>> programs, CancellationToken cancellationToken)
  819. {
  820. var timers = new Dictionary<string, List<TimerInfo>>();
  821. var seriesTimers = new Dictionary<string, List<SeriesTimerInfo>>();
  822. TimerInfo[] timerList = null;
  823. SeriesTimerInfo[] seriesTimerList = null;
  824. foreach (var programTuple in programs)
  825. {
  826. var program = programTuple.Item1;
  827. var externalProgramId = programTuple.Item2;
  828. string externalSeriesId = programTuple.Item3;
  829. if (timerList == null)
  830. {
  831. timerList = (await GetTimersInternal(new TimerQuery(), cancellationToken).ConfigureAwait(false)).Items;
  832. }
  833. var timer = timerList.FirstOrDefault(i => string.Equals(i.ProgramId, externalProgramId, StringComparison.OrdinalIgnoreCase));
  834. var foundSeriesTimer = false;
  835. if (timer != null)
  836. {
  837. if (timer.Status != RecordingStatus.Cancelled && timer.Status != RecordingStatus.Error)
  838. {
  839. program.TimerId = _tvDtoService.GetInternalTimerId(timer.Id);
  840. program.Status = timer.Status.ToString();
  841. }
  842. if (!string.IsNullOrEmpty(timer.SeriesTimerId))
  843. {
  844. program.SeriesTimerId = _tvDtoService.GetInternalSeriesTimerId(timer.SeriesTimerId)
  845. .ToString("N");
  846. foundSeriesTimer = true;
  847. }
  848. }
  849. if (foundSeriesTimer || string.IsNullOrWhiteSpace(externalSeriesId))
  850. {
  851. continue;
  852. }
  853. if (seriesTimerList == null)
  854. {
  855. seriesTimerList = (await GetSeriesTimersInternal(new SeriesTimerQuery(), cancellationToken).ConfigureAwait(false)).Items;
  856. }
  857. var seriesTimer = seriesTimerList.FirstOrDefault(i => string.Equals(i.SeriesId, externalSeriesId, StringComparison.OrdinalIgnoreCase));
  858. if (seriesTimer != null)
  859. {
  860. program.SeriesTimerId = _tvDtoService.GetInternalSeriesTimerId(seriesTimer.Id)
  861. .ToString("N");
  862. }
  863. }
  864. }
  865. internal Task RefreshChannels(IProgress<double> progress, CancellationToken cancellationToken)
  866. {
  867. return RefreshChannelsInternal(progress, cancellationToken);
  868. }
  869. private async Task RefreshChannelsInternal(IProgress<double> progress, CancellationToken cancellationToken)
  870. {
  871. await EmbyTV.EmbyTV.Current.CreateRecordingFolders().ConfigureAwait(false);
  872. await EmbyTV.EmbyTV.Current.ScanForTunerDeviceChanges(cancellationToken).ConfigureAwait(false);
  873. var numComplete = 0;
  874. double progressPerService = _services.Length == 0
  875. ? 0
  876. : 1.0 / _services.Length;
  877. var newChannelIdList = new List<Guid>();
  878. var newProgramIdList = new List<Guid>();
  879. var cleanDatabase = true;
  880. foreach (var service in _services)
  881. {
  882. cancellationToken.ThrowIfCancellationRequested();
  883. _logger.LogDebug("Refreshing guide from {name}", service.Name);
  884. try
  885. {
  886. var innerProgress = new ActionableProgress<double>();
  887. innerProgress.RegisterAction(p => progress.Report(p * progressPerService));
  888. var idList = await RefreshChannelsInternal(service, innerProgress, cancellationToken).ConfigureAwait(false);
  889. newChannelIdList.AddRange(idList.Item1);
  890. newProgramIdList.AddRange(idList.Item2);
  891. }
  892. catch (OperationCanceledException)
  893. {
  894. throw;
  895. }
  896. catch (Exception ex)
  897. {
  898. cleanDatabase = false;
  899. _logger.LogError(ex, "Error refreshing channels for service");
  900. }
  901. numComplete++;
  902. double percent = numComplete;
  903. percent /= _services.Length;
  904. progress.Report(100 * percent);
  905. }
  906. if (cleanDatabase)
  907. {
  908. CleanDatabaseInternal(newChannelIdList.ToArray(), new[] { typeof(LiveTvChannel).Name }, progress, cancellationToken);
  909. CleanDatabaseInternal(newProgramIdList.ToArray(), new[] { typeof(LiveTvProgram).Name }, progress, cancellationToken);
  910. }
  911. var coreService = _services.OfType<EmbyTV.EmbyTV>().FirstOrDefault();
  912. if (coreService != null)
  913. {
  914. await coreService.RefreshSeriesTimers(cancellationToken, new SimpleProgress<double>()).ConfigureAwait(false);
  915. await coreService.RefreshTimers(cancellationToken, new SimpleProgress<double>()).ConfigureAwait(false);
  916. }
  917. // Load these now which will prefetch metadata
  918. var dtoOptions = new DtoOptions();
  919. var fields = dtoOptions.Fields.ToList();
  920. fields.Remove(ItemFields.BasicSyncInfo);
  921. dtoOptions.Fields = fields.ToArray();
  922. progress.Report(100);
  923. }
  924. private async Task<Tuple<List<Guid>, List<Guid>>> RefreshChannelsInternal(ILiveTvService service, IProgress<double> progress, CancellationToken cancellationToken)
  925. {
  926. progress.Report(10);
  927. var allChannelsList = (await service.GetChannelsAsync(cancellationToken).ConfigureAwait(false))
  928. .Select(i => new Tuple<string, ChannelInfo>(service.Name, i))
  929. .ToList();
  930. var list = new List<LiveTvChannel>();
  931. var numComplete = 0;
  932. var parentFolder = GetInternalLiveTvFolder(cancellationToken);
  933. foreach (var channelInfo in allChannelsList)
  934. {
  935. cancellationToken.ThrowIfCancellationRequested();
  936. try
  937. {
  938. var item = GetChannel(channelInfo.Item2, channelInfo.Item1, parentFolder, cancellationToken);
  939. list.Add(item);
  940. }
  941. catch (OperationCanceledException)
  942. {
  943. throw;
  944. }
  945. catch (Exception ex)
  946. {
  947. _logger.LogError(ex, "Error getting channel information for {name}", channelInfo.Item2.Name);
  948. }
  949. numComplete++;
  950. double percent = numComplete;
  951. percent /= allChannelsList.Count;
  952. progress.Report(5 * percent + 10);
  953. }
  954. progress.Report(15);
  955. numComplete = 0;
  956. var programs = new List<Guid>();
  957. var channels = new List<Guid>();
  958. var guideDays = GetGuideDays();
  959. _logger.LogInformation("Refreshing guide with {0} days of guide data", guideDays);
  960. cancellationToken.ThrowIfCancellationRequested();
  961. foreach (var currentChannel in list)
  962. {
  963. channels.Add(currentChannel.Id);
  964. cancellationToken.ThrowIfCancellationRequested();
  965. try
  966. {
  967. var start = DateTime.UtcNow.AddHours(-1);
  968. var end = start.AddDays(guideDays);
  969. var isMovie = false;
  970. var isSports = false;
  971. var isNews = false;
  972. var isKids = false;
  973. var iSSeries = false;
  974. var channelPrograms = (await service.GetProgramsAsync(currentChannel.ExternalId, start, end, cancellationToken).ConfigureAwait(false)).ToList();
  975. var existingPrograms = _libraryManager.GetItemList(new InternalItemsQuery
  976. {
  977. IncludeItemTypes = new string[] { typeof(LiveTvProgram).Name },
  978. ChannelIds = new Guid[] { currentChannel.Id },
  979. DtoOptions = new DtoOptions(true)
  980. }).Cast<LiveTvProgram>().ToDictionary(i => i.Id);
  981. var newPrograms = new List<LiveTvProgram>();
  982. var updatedPrograms = new List<BaseItem>();
  983. foreach (var program in channelPrograms)
  984. {
  985. var programTuple = GetProgram(program, existingPrograms, currentChannel, currentChannel.ChannelType, service.Name, cancellationToken);
  986. var programItem = programTuple.Item1;
  987. if (programTuple.Item2)
  988. {
  989. newPrograms.Add(programItem);
  990. }
  991. else if (programTuple.Item3)
  992. {
  993. updatedPrograms.Add(programItem);
  994. }
  995. programs.Add(programItem.Id);
  996. isMovie |= program.IsMovie;
  997. iSSeries |= program.IsSeries;
  998. isSports |= program.IsSports;
  999. isNews |= program.IsNews;
  1000. isKids |= program.IsKids;
  1001. }
  1002. _logger.LogDebug("Channel {0} has {1} new programs and {2} updated programs", currentChannel.Name, newPrograms.Count, updatedPrograms.Count);
  1003. if (newPrograms.Count > 0)
  1004. {
  1005. _libraryManager.CreateItems(newPrograms, null, cancellationToken);
  1006. }
  1007. if (updatedPrograms.Count > 0)
  1008. {
  1009. _libraryManager.UpdateItems(updatedPrograms, currentChannel, ItemUpdateType.MetadataImport, cancellationToken);
  1010. }
  1011. currentChannel.IsMovie = isMovie;
  1012. currentChannel.IsNews = isNews;
  1013. currentChannel.IsSports = isSports;
  1014. currentChannel.IsSeries = iSSeries;
  1015. if (isKids)
  1016. {
  1017. currentChannel.AddTag("Kids");
  1018. }
  1019. //currentChannel.UpdateToRepository(ItemUpdateType.MetadataImport, cancellationToken);
  1020. await currentChannel.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
  1021. {
  1022. ForceSave = true
  1023. }, cancellationToken).ConfigureAwait(false);
  1024. }
  1025. catch (OperationCanceledException)
  1026. {
  1027. throw;
  1028. }
  1029. catch (Exception ex)
  1030. {
  1031. _logger.LogError(ex, "Error getting programs for channel {name}", currentChannel.Name);
  1032. }
  1033. numComplete++;
  1034. double percent = numComplete / (double)allChannelsList.Count;
  1035. progress.Report(85 * percent + 15);
  1036. }
  1037. progress.Report(100);
  1038. return new Tuple<List<Guid>, List<Guid>>(channels, programs);
  1039. }
  1040. private void CleanDatabaseInternal(Guid[] currentIdList, string[] validTypes, IProgress<double> progress, CancellationToken cancellationToken)
  1041. {
  1042. var list = _itemRepo.GetItemIdsList(new InternalItemsQuery
  1043. {
  1044. IncludeItemTypes = validTypes,
  1045. DtoOptions = new DtoOptions(false)
  1046. });
  1047. var numComplete = 0;
  1048. foreach (var itemId in list)
  1049. {
  1050. cancellationToken.ThrowIfCancellationRequested();
  1051. if (itemId.Equals(Guid.Empty))
  1052. {
  1053. // Somehow some invalid data got into the db. It probably predates the boundary checking
  1054. continue;
  1055. }
  1056. if (!currentIdList.Contains(itemId))
  1057. {
  1058. var item = _libraryManager.GetItemById(itemId);
  1059. if (item != null)
  1060. {
  1061. _libraryManager.DeleteItem(item, new DeleteOptions
  1062. {
  1063. DeleteFileLocation = false,
  1064. DeleteFromExternalProvider = false
  1065. }, false);
  1066. }
  1067. }
  1068. numComplete++;
  1069. double percent = numComplete / (double)list.Count;
  1070. progress.Report(100 * percent);
  1071. }
  1072. }
  1073. private const int MaxGuideDays = 14;
  1074. private double GetGuideDays()
  1075. {
  1076. var config = GetConfiguration();
  1077. if (config.GuideDays.HasValue)
  1078. {
  1079. return Math.Max(1, Math.Min(config.GuideDays.Value, MaxGuideDays));
  1080. }
  1081. return 7;
  1082. }
  1083. private QueryResult<BaseItem> GetEmbyRecordings(RecordingQuery query, DtoOptions dtoOptions, User user)
  1084. {
  1085. if (user == null)
  1086. {
  1087. return new QueryResult<BaseItem>();
  1088. }
  1089. var folderIds = GetRecordingFolders(user, true)
  1090. .Select(i => i.Id)
  1091. .ToList();
  1092. var excludeItemTypes = new List<string>();
  1093. if (folderIds.Count == 0)
  1094. {
  1095. return new QueryResult<BaseItem>();
  1096. }
  1097. var includeItemTypes = new List<string>();
  1098. var genres = new List<string>();
  1099. if (query.IsMovie.HasValue)
  1100. {
  1101. if (query.IsMovie.Value)
  1102. {
  1103. includeItemTypes.Add(typeof(Movie).Name);
  1104. }
  1105. else
  1106. {
  1107. excludeItemTypes.Add(typeof(Movie).Name);
  1108. }
  1109. }
  1110. if (query.IsSeries.HasValue)
  1111. {
  1112. if (query.IsSeries.Value)
  1113. {
  1114. includeItemTypes.Add(typeof(Episode).Name);
  1115. }
  1116. else
  1117. {
  1118. excludeItemTypes.Add(typeof(Episode).Name);
  1119. }
  1120. }
  1121. if (query.IsSports ?? false)
  1122. {
  1123. genres.Add("Sports");
  1124. }
  1125. if (query.IsKids ?? false)
  1126. {
  1127. genres.Add("Kids");
  1128. genres.Add("Children");
  1129. genres.Add("Family");
  1130. }
  1131. var limit = query.Limit;
  1132. if (query.IsInProgress ?? false)
  1133. {
  1134. // limit = (query.Limit ?? 10) * 2;
  1135. limit = null;
  1136. //var allActivePaths = EmbyTV.EmbyTV.Current.GetAllActiveRecordings().Select(i => i.Path).ToArray();
  1137. //var items = allActivePaths.Select(i => _libraryManager.FindByPath(i, false)).Where(i => i != null).ToArray();
  1138. //return new QueryResult<BaseItem>
  1139. //{
  1140. // Items = items,
  1141. // TotalRecordCount = items.Length
  1142. //};
  1143. dtoOptions.Fields = dtoOptions.Fields.Concat(new[] { ItemFields.Tags }).Distinct().ToArray();
  1144. }
  1145. var result = _libraryManager.GetItemsResult(new InternalItemsQuery(user)
  1146. {
  1147. MediaTypes = new[] { MediaType.Video },
  1148. Recursive = true,
  1149. AncestorIds = folderIds.ToArray(),
  1150. IsFolder = false,
  1151. IsVirtualItem = false,
  1152. Limit = limit,
  1153. StartIndex = query.StartIndex,
  1154. OrderBy = new[] { new ValueTuple<string, SortOrder>(ItemSortBy.DateCreated, SortOrder.Descending) },
  1155. EnableTotalRecordCount = query.EnableTotalRecordCount,
  1156. IncludeItemTypes = includeItemTypes.ToArray(),
  1157. ExcludeItemTypes = excludeItemTypes.ToArray(),
  1158. Genres = genres.ToArray(),
  1159. DtoOptions = dtoOptions
  1160. });
  1161. if (query.IsInProgress ?? false)
  1162. {
  1163. //TODO Fix The co-variant conversion between Video[] and BaseItem[], this can generate runtime issues.
  1164. result.Items = result
  1165. .Items
  1166. .OfType<Video>()
  1167. .Where(i => !i.IsCompleteMedia)
  1168. .ToArray();
  1169. result.TotalRecordCount = result.Items.Length;
  1170. }
  1171. return result;
  1172. }
  1173. public Task AddInfoToProgramDto(List<Tuple<BaseItem, BaseItemDto>> tuples, ItemFields[] fields, User user = null)
  1174. {
  1175. var programTuples = new List<Tuple<BaseItemDto, string, string>>();
  1176. var hasChannelImage = fields.Contains(ItemFields.ChannelImage);
  1177. var hasChannelInfo = fields.Contains(ItemFields.ChannelInfo);
  1178. foreach (var tuple in tuples)
  1179. {
  1180. var program = (LiveTvProgram)tuple.Item1;
  1181. var dto = tuple.Item2;
  1182. dto.StartDate = program.StartDate;
  1183. dto.EpisodeTitle = program.EpisodeTitle;
  1184. dto.IsRepeat |= program.IsRepeat;
  1185. dto.IsMovie |= program.IsMovie;
  1186. dto.IsSeries |= program.IsSeries;
  1187. dto.IsSports |= program.IsSports;
  1188. dto.IsLive |= program.IsLive;
  1189. dto.IsNews |= program.IsNews;
  1190. dto.IsKids |= program.IsKids;
  1191. dto.IsPremiere |= program.IsPremiere;
  1192. if (hasChannelInfo || hasChannelImage)
  1193. {
  1194. var channel = _libraryManager.GetItemById(program.ChannelId);
  1195. if (channel is LiveTvChannel liveChannel)
  1196. {
  1197. dto.ChannelName = liveChannel.Name;
  1198. dto.MediaType = liveChannel.MediaType;
  1199. dto.ChannelNumber = liveChannel.Number;
  1200. if (hasChannelImage && liveChannel.HasImage(ImageType.Primary))
  1201. {
  1202. dto.ChannelPrimaryImageTag = _tvDtoService.GetImageTag(liveChannel);
  1203. }
  1204. }
  1205. }
  1206. programTuples.Add(new Tuple<BaseItemDto, string, string>(dto, program.ExternalId, program.ExternalSeriesId));
  1207. }
  1208. return AddRecordingInfo(programTuples, CancellationToken.None);
  1209. }
  1210. public ActiveRecordingInfo GetActiveRecordingInfo(string path)
  1211. {
  1212. return EmbyTV.EmbyTV.Current.GetActiveRecordingInfo(path);
  1213. }
  1214. public void AddInfoToRecordingDto(BaseItem item, BaseItemDto dto, ActiveRecordingInfo activeRecordingInfo, User user = null)
  1215. {
  1216. var service = EmbyTV.EmbyTV.Current;
  1217. var info = activeRecordingInfo.Timer;
  1218. var channel = string.IsNullOrWhiteSpace(info.ChannelId) ? null : _libraryManager.GetItemById(_tvDtoService.GetInternalChannelId(service.Name, info.ChannelId));
  1219. dto.SeriesTimerId = string.IsNullOrEmpty(info.SeriesTimerId)
  1220. ? null
  1221. : _tvDtoService.GetInternalSeriesTimerId(info.SeriesTimerId).ToString("N");
  1222. dto.TimerId = string.IsNullOrEmpty(info.Id)
  1223. ? null
  1224. : _tvDtoService.GetInternalTimerId(info.Id);
  1225. var startDate = info.StartDate;
  1226. var endDate = info.EndDate;
  1227. dto.StartDate = startDate;
  1228. dto.EndDate = endDate;
  1229. dto.Status = info.Status.ToString();
  1230. dto.IsRepeat = info.IsRepeat;
  1231. dto.EpisodeTitle = info.EpisodeTitle;
  1232. dto.IsMovie = info.IsMovie;
  1233. dto.IsSeries = info.IsSeries;
  1234. dto.IsSports = info.IsSports;
  1235. dto.IsLive = info.IsLive;
  1236. dto.IsNews = info.IsNews;
  1237. dto.IsKids = info.IsKids;
  1238. dto.IsPremiere = info.IsPremiere;
  1239. if (info.Status == RecordingStatus.InProgress)
  1240. {
  1241. startDate = info.StartDate.AddSeconds(0 - info.PrePaddingSeconds);
  1242. endDate = info.EndDate.AddSeconds(info.PostPaddingSeconds);
  1243. var now = DateTime.UtcNow.Ticks;
  1244. var start = startDate.Ticks;
  1245. var end = endDate.Ticks;
  1246. var pct = now - start;
  1247. pct /= end;
  1248. pct *= 100;
  1249. dto.CompletionPercentage = pct;
  1250. }
  1251. if (channel != null)
  1252. {
  1253. dto.ChannelName = channel.Name;
  1254. if (channel.HasImage(ImageType.Primary))
  1255. {
  1256. dto.ChannelPrimaryImageTag = _tvDtoService.GetImageTag(channel);
  1257. }
  1258. }
  1259. }
  1260. public QueryResult<BaseItemDto> GetRecordings(RecordingQuery query, DtoOptions options)
  1261. {
  1262. var user = query.UserId.Equals(Guid.Empty) ? null : _userManager.GetUserById(query.UserId);
  1263. RemoveFields(options);
  1264. var internalResult = GetEmbyRecordings(query, options, user);
  1265. var returnArray = _dtoService.GetBaseItemDtos(internalResult.Items, options, user);
  1266. return new QueryResult<BaseItemDto>
  1267. {
  1268. Items = returnArray,
  1269. TotalRecordCount = internalResult.TotalRecordCount
  1270. };
  1271. }
  1272. private async Task<QueryResult<TimerInfo>> GetTimersInternal(TimerQuery query, CancellationToken cancellationToken)
  1273. {
  1274. var tasks = _services.Select(async i =>
  1275. {
  1276. try
  1277. {
  1278. var recs = await i.GetTimersAsync(cancellationToken).ConfigureAwait(false);
  1279. return recs.Select(r => new Tuple<TimerInfo, ILiveTvService>(r, i));
  1280. }
  1281. catch (Exception ex)
  1282. {
  1283. _logger.LogError(ex, "Error getting recordings");
  1284. return new List<Tuple<TimerInfo, ILiveTvService>>();
  1285. }
  1286. });
  1287. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  1288. var timers = results.SelectMany(i => i.ToList());
  1289. if (query.IsActive.HasValue)
  1290. {
  1291. if (query.IsActive.Value)
  1292. {
  1293. timers = timers.Where(i => i.Item1.Status == RecordingStatus.InProgress);
  1294. }
  1295. else
  1296. {
  1297. timers = timers.Where(i => i.Item1.Status != RecordingStatus.InProgress);
  1298. }
  1299. }
  1300. if (query.IsScheduled.HasValue)
  1301. {
  1302. if (query.IsScheduled.Value)
  1303. {
  1304. timers = timers.Where(i => i.Item1.Status == RecordingStatus.New);
  1305. }
  1306. else
  1307. {
  1308. timers = timers.Where(i => i.Item1.Status != RecordingStatus.New);
  1309. }
  1310. }
  1311. if (!string.IsNullOrEmpty(query.ChannelId))
  1312. {
  1313. var guid = new Guid(query.ChannelId);
  1314. timers = timers.Where(i => guid == _tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId));
  1315. }
  1316. if (!string.IsNullOrEmpty(query.SeriesTimerId))
  1317. {
  1318. var guid = new Guid(query.SeriesTimerId);
  1319. timers = timers
  1320. .Where(i => _tvDtoService.GetInternalSeriesTimerId(i.Item1.SeriesTimerId) == guid);
  1321. }
  1322. if (!string.IsNullOrEmpty(query.Id))
  1323. {
  1324. var guid = new Guid(query.Id);
  1325. timers = timers
  1326. .Where(i => string.Equals(_tvDtoService.GetInternalTimerId(i.Item1.Id), query.Id, StringComparison.OrdinalIgnoreCase));
  1327. }
  1328. var returnArray = timers
  1329. .Select(i => i.Item1)
  1330. .OrderBy(i => i.StartDate)
  1331. .ToArray();
  1332. return new QueryResult<TimerInfo>
  1333. {
  1334. Items = returnArray,
  1335. TotalRecordCount = returnArray.Length
  1336. };
  1337. }
  1338. public async Task<QueryResult<TimerInfoDto>> GetTimers(TimerQuery query, CancellationToken cancellationToken)
  1339. {
  1340. var tasks = _services.Select(async i =>
  1341. {
  1342. try
  1343. {
  1344. var recs = await i.GetTimersAsync(cancellationToken).ConfigureAwait(false);
  1345. return recs.Select(r => new Tuple<TimerInfo, ILiveTvService>(r, i));
  1346. }
  1347. catch (Exception ex)
  1348. {
  1349. _logger.LogError(ex, "Error getting recordings");
  1350. return new List<Tuple<TimerInfo, ILiveTvService>>();
  1351. }
  1352. });
  1353. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  1354. var timers = results.SelectMany(i => i.ToList());
  1355. if (query.IsActive.HasValue)
  1356. {
  1357. if (query.IsActive.Value)
  1358. {
  1359. timers = timers.Where(i => i.Item1.Status == RecordingStatus.InProgress);
  1360. }
  1361. else
  1362. {
  1363. timers = timers.Where(i => i.Item1.Status != RecordingStatus.InProgress);
  1364. }
  1365. }
  1366. if (query.IsScheduled.HasValue)
  1367. {
  1368. if (query.IsScheduled.Value)
  1369. {
  1370. timers = timers.Where(i => i.Item1.Status == RecordingStatus.New);
  1371. }
  1372. else
  1373. {
  1374. timers = timers.Where(i => i.Item1.Status != RecordingStatus.New);
  1375. }
  1376. }
  1377. if (!string.IsNullOrEmpty(query.ChannelId))
  1378. {
  1379. var guid = new Guid(query.ChannelId);
  1380. timers = timers.Where(i => guid == _tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId));
  1381. }
  1382. if (!string.IsNullOrEmpty(query.SeriesTimerId))
  1383. {
  1384. var guid = new Guid(query.SeriesTimerId);
  1385. timers = timers
  1386. .Where(i => _tvDtoService.GetInternalSeriesTimerId(i.Item1.SeriesTimerId) == guid);
  1387. }
  1388. if (!string.IsNullOrEmpty(query.Id))
  1389. {
  1390. timers = timers
  1391. .Where(i => string.Equals(_tvDtoService.GetInternalTimerId(i.Item1.Id), query.Id, StringComparison.OrdinalIgnoreCase));
  1392. }
  1393. var returnList = new List<TimerInfoDto>();
  1394. foreach (var i in timers)
  1395. {
  1396. var program = string.IsNullOrEmpty(i.Item1.ProgramId) ?
  1397. null :
  1398. _libraryManager.GetItemById(_tvDtoService.GetInternalProgramId(i.Item1.ProgramId)) as LiveTvProgram;
  1399. var channel = string.IsNullOrEmpty(i.Item1.ChannelId) ? null : _libraryManager.GetItemById(_tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId));
  1400. returnList.Add(_tvDtoService.GetTimerInfoDto(i.Item1, i.Item2, program, channel));
  1401. }
  1402. var returnArray = returnList
  1403. .OrderBy(i => i.StartDate)
  1404. .ToArray();
  1405. return new QueryResult<TimerInfoDto>
  1406. {
  1407. Items = returnArray,
  1408. TotalRecordCount = returnArray.Length
  1409. };
  1410. }
  1411. public async Task CancelTimer(string id)
  1412. {
  1413. var timer = await GetTimer(id, CancellationToken.None).ConfigureAwait(false);
  1414. if (timer == null)
  1415. {
  1416. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  1417. }
  1418. var service = GetService(timer.ServiceName);
  1419. await service.CancelTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  1420. if (!(service is EmbyTV.EmbyTV))
  1421. {
  1422. TimerCancelled?.Invoke(this, new GenericEventArgs<TimerEventInfo>
  1423. {
  1424. Argument = new TimerEventInfo
  1425. {
  1426. Id = id
  1427. }
  1428. });
  1429. }
  1430. }
  1431. public async Task CancelSeriesTimer(string id)
  1432. {
  1433. var timer = await GetSeriesTimer(id, CancellationToken.None).ConfigureAwait(false);
  1434. if (timer == null)
  1435. {
  1436. throw new ResourceNotFoundException(string.Format("SeriesTimer with Id {0} not found", id));
  1437. }
  1438. var service = GetService(timer.ServiceName);
  1439. await service.CancelSeriesTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  1440. SeriesTimerCancelled?.Invoke(this, new GenericEventArgs<TimerEventInfo>
  1441. {
  1442. Argument = new TimerEventInfo
  1443. {
  1444. Id = id
  1445. }
  1446. });
  1447. }
  1448. public async Task<TimerInfoDto> GetTimer(string id, CancellationToken cancellationToken)
  1449. {
  1450. var results = await GetTimers(new TimerQuery
  1451. {
  1452. Id = id
  1453. }, cancellationToken).ConfigureAwait(false);
  1454. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
  1455. }
  1456. public async Task<SeriesTimerInfoDto> GetSeriesTimer(string id, CancellationToken cancellationToken)
  1457. {
  1458. var results = await GetSeriesTimers(new SeriesTimerQuery(), cancellationToken).ConfigureAwait(false);
  1459. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
  1460. }
  1461. private async Task<QueryResult<SeriesTimerInfo>> GetSeriesTimersInternal(SeriesTimerQuery query, CancellationToken cancellationToken)
  1462. {
  1463. var tasks = _services.Select(async i =>
  1464. {
  1465. try
  1466. {
  1467. var recs = await i.GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false);
  1468. return recs.Select(r =>
  1469. {
  1470. r.ServiceName = i.Name;
  1471. return new Tuple<SeriesTimerInfo, ILiveTvService>(r, i);
  1472. });
  1473. }
  1474. catch (Exception ex)
  1475. {
  1476. _logger.LogError(ex, "Error getting recordings");
  1477. return new List<Tuple<SeriesTimerInfo, ILiveTvService>>();
  1478. }
  1479. });
  1480. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  1481. var timers = results.SelectMany(i => i.ToList());
  1482. if (string.Equals(query.SortBy, "Priority", StringComparison.OrdinalIgnoreCase))
  1483. {
  1484. timers = query.SortOrder == SortOrder.Descending ?
  1485. timers.OrderBy(i => i.Item1.Priority).ThenByStringDescending(i => i.Item1.Name) :
  1486. timers.OrderByDescending(i => i.Item1.Priority).ThenByString(i => i.Item1.Name);
  1487. }
  1488. else
  1489. {
  1490. timers = query.SortOrder == SortOrder.Descending ?
  1491. timers.OrderByStringDescending(i => i.Item1.Name) :
  1492. timers.OrderByString(i => i.Item1.Name);
  1493. }
  1494. var returnArray = timers
  1495. .Select(i =>
  1496. {
  1497. return i.Item1;
  1498. })
  1499. .ToArray();
  1500. return new QueryResult<SeriesTimerInfo>
  1501. {
  1502. Items = returnArray,
  1503. TotalRecordCount = returnArray.Length
  1504. };
  1505. }
  1506. public async Task<QueryResult<SeriesTimerInfoDto>> GetSeriesTimers(SeriesTimerQuery query, CancellationToken cancellationToken)
  1507. {
  1508. var tasks = _services.Select(async i =>
  1509. {
  1510. try
  1511. {
  1512. var recs = await i.GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false);
  1513. return recs.Select(r => new Tuple<SeriesTimerInfo, ILiveTvService>(r, i));
  1514. }
  1515. catch (Exception ex)
  1516. {
  1517. _logger.LogError(ex, "Error getting recordings");
  1518. return new List<Tuple<SeriesTimerInfo, ILiveTvService>>();
  1519. }
  1520. });
  1521. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  1522. var timers = results.SelectMany(i => i.ToList());
  1523. if (string.Equals(query.SortBy, "Priority", StringComparison.OrdinalIgnoreCase))
  1524. {
  1525. timers = query.SortOrder == SortOrder.Descending ?
  1526. timers.OrderBy(i => i.Item1.Priority).ThenByStringDescending(i => i.Item1.Name) :
  1527. timers.OrderByDescending(i => i.Item1.Priority).ThenByString(i => i.Item1.Name);
  1528. }
  1529. else
  1530. {
  1531. timers = query.SortOrder == SortOrder.Descending ?
  1532. timers.OrderByStringDescending(i => i.Item1.Name) :
  1533. timers.OrderByString(i => i.Item1.Name);
  1534. }
  1535. var returnArray = timers
  1536. .Select(i =>
  1537. {
  1538. string channelName = null;
  1539. if (!string.IsNullOrEmpty(i.Item1.ChannelId))
  1540. {
  1541. var internalChannelId = _tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId);
  1542. var channel = _libraryManager.GetItemById(internalChannelId);
  1543. channelName = channel == null ? null : channel.Name;
  1544. }
  1545. return _tvDtoService.GetSeriesTimerInfoDto(i.Item1, i.Item2, channelName);
  1546. })
  1547. .ToArray();
  1548. return new QueryResult<SeriesTimerInfoDto>
  1549. {
  1550. Items = returnArray,
  1551. TotalRecordCount = returnArray.Length
  1552. };
  1553. }
  1554. public BaseItem GetLiveTvChannel(TimerInfo timer, ILiveTvService service)
  1555. {
  1556. var internalChannelId = _tvDtoService.GetInternalChannelId(service.Name, timer.ChannelId);
  1557. return _libraryManager.GetItemById(internalChannelId);
  1558. }
  1559. public void AddChannelInfo(List<Tuple<BaseItemDto, LiveTvChannel>> tuples, DtoOptions options, User user)
  1560. {
  1561. var now = DateTime.UtcNow;
  1562. var channelIds = tuples.Select(i => i.Item2.Id).Distinct().ToArray();
  1563. var programs = options.AddCurrentProgram ? _libraryManager.GetItemList(new InternalItemsQuery(user)
  1564. {
  1565. IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
  1566. ChannelIds = channelIds,
  1567. MaxStartDate = now,
  1568. MinEndDate = now,
  1569. Limit = channelIds.Length,
  1570. OrderBy = new[] { new ValueTuple<string, SortOrder>(ItemSortBy.StartDate, SortOrder.Ascending) },
  1571. TopParentIds = new[] { GetInternalLiveTvFolder(CancellationToken.None).Id },
  1572. DtoOptions = options
  1573. }) : new List<BaseItem>();
  1574. RemoveFields(options);
  1575. var currentProgramsList = new List<BaseItem>();
  1576. var currentChannelsDict = new Dictionary<Guid, BaseItemDto>();
  1577. var addCurrentProgram = options.AddCurrentProgram;
  1578. foreach (var tuple in tuples)
  1579. {
  1580. var dto = tuple.Item1;
  1581. var channel = tuple.Item2;
  1582. dto.Number = channel.Number;
  1583. dto.ChannelNumber = channel.Number;
  1584. dto.ChannelType = channel.ChannelType;
  1585. currentChannelsDict[dto.Id] = dto;
  1586. if (addCurrentProgram)
  1587. {
  1588. var currentProgram = programs.FirstOrDefault(i => channel.Id.Equals(i.ChannelId));
  1589. if (currentProgram != null)
  1590. {
  1591. currentProgramsList.Add(currentProgram);
  1592. }
  1593. }
  1594. }
  1595. if (addCurrentProgram)
  1596. {
  1597. var currentProgramDtos = _dtoService.GetBaseItemDtos(currentProgramsList, options, user);
  1598. foreach (var programDto in currentProgramDtos)
  1599. {
  1600. if (currentChannelsDict.TryGetValue(programDto.ChannelId, out var channelDto))
  1601. {
  1602. channelDto.CurrentProgram = programDto;
  1603. }
  1604. }
  1605. }
  1606. }
  1607. private async Task<Tuple<SeriesTimerInfo, ILiveTvService>> GetNewTimerDefaultsInternal(CancellationToken cancellationToken, LiveTvProgram program = null)
  1608. {
  1609. ILiveTvService service = null;
  1610. ProgramInfo programInfo = null;
  1611. if (program != null)
  1612. {
  1613. service = GetService(program);
  1614. var channel = _libraryManager.GetItemById(program.ChannelId);
  1615. programInfo = new ProgramInfo
  1616. {
  1617. Audio = program.Audio,
  1618. ChannelId = channel.ExternalId,
  1619. CommunityRating = program.CommunityRating,
  1620. EndDate = program.EndDate ?? DateTime.MinValue,
  1621. EpisodeTitle = program.EpisodeTitle,
  1622. Genres = program.Genres.ToList(),
  1623. Id = program.ExternalId,
  1624. IsHD = program.IsHD,
  1625. IsKids = program.IsKids,
  1626. IsLive = program.IsLive,
  1627. IsMovie = program.IsMovie,
  1628. IsNews = program.IsNews,
  1629. IsPremiere = program.IsPremiere,
  1630. IsRepeat = program.IsRepeat,
  1631. IsSeries = program.IsSeries,
  1632. IsSports = program.IsSports,
  1633. OriginalAirDate = program.PremiereDate,
  1634. Overview = program.Overview,
  1635. StartDate = program.StartDate,
  1636. //ImagePath = program.ExternalImagePath,
  1637. Name = program.Name,
  1638. OfficialRating = program.OfficialRating
  1639. };
  1640. }
  1641. if (service == null)
  1642. {
  1643. service = _services.First();
  1644. }
  1645. var info = await service.GetNewTimerDefaultsAsync(cancellationToken, programInfo).ConfigureAwait(false);
  1646. info.RecordAnyTime = true;
  1647. info.Days = new List<DayOfWeek>
  1648. {
  1649. DayOfWeek.Sunday,
  1650. DayOfWeek.Monday,
  1651. DayOfWeek.Tuesday,
  1652. DayOfWeek.Wednesday,
  1653. DayOfWeek.Thursday,
  1654. DayOfWeek.Friday,
  1655. DayOfWeek.Saturday
  1656. };
  1657. info.Id = null;
  1658. return new Tuple<SeriesTimerInfo, ILiveTvService>(info, service);
  1659. }
  1660. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(CancellationToken cancellationToken)
  1661. {
  1662. var info = await GetNewTimerDefaultsInternal(cancellationToken).ConfigureAwait(false);
  1663. var obj = _tvDtoService.GetSeriesTimerInfoDto(info.Item1, info.Item2, null);
  1664. return obj;
  1665. }
  1666. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(string programId, CancellationToken cancellationToken)
  1667. {
  1668. var program = (LiveTvProgram)_libraryManager.GetItemById(programId);
  1669. var programDto = await GetProgram(programId, cancellationToken).ConfigureAwait(false);
  1670. var defaults = await GetNewTimerDefaultsInternal(cancellationToken, program).ConfigureAwait(false);
  1671. var info = _tvDtoService.GetSeriesTimerInfoDto(defaults.Item1, defaults.Item2, null);
  1672. info.Days = defaults.Item1.Days.ToArray();
  1673. info.DayPattern = _tvDtoService.GetDayPattern(info.Days);
  1674. info.Name = program.Name;
  1675. info.ChannelId = programDto.ChannelId;
  1676. info.ChannelName = programDto.ChannelName;
  1677. info.StartDate = program.StartDate;
  1678. info.Name = program.Name;
  1679. info.Overview = program.Overview;
  1680. info.ProgramId = programDto.Id.ToString("N");
  1681. info.ExternalProgramId = program.ExternalId;
  1682. if (program.EndDate.HasValue)
  1683. {
  1684. info.EndDate = program.EndDate.Value;
  1685. }
  1686. return info;
  1687. }
  1688. public async Task CreateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  1689. {
  1690. var service = GetService(timer.ServiceName);
  1691. var info = await _tvDtoService.GetTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  1692. // Set priority from default values
  1693. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  1694. info.Priority = defaultValues.Priority;
  1695. string newTimerId = null;
  1696. if (service is ISupportsNewTimerIds supportsNewTimerIds)
  1697. {
  1698. newTimerId = await supportsNewTimerIds.CreateTimer(info, cancellationToken).ConfigureAwait(false);
  1699. newTimerId = _tvDtoService.GetInternalTimerId(newTimerId);
  1700. }
  1701. else
  1702. {
  1703. await service.CreateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1704. }
  1705. _logger.LogInformation("New recording scheduled");
  1706. if (!(service is EmbyTV.EmbyTV))
  1707. {
  1708. TimerCreated?.Invoke(this, new GenericEventArgs<TimerEventInfo>
  1709. {
  1710. Argument = new TimerEventInfo
  1711. {
  1712. ProgramId = _tvDtoService.GetInternalProgramId(info.ProgramId),
  1713. Id = newTimerId
  1714. }
  1715. });
  1716. }
  1717. }
  1718. public async Task CreateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  1719. {
  1720. var registration = await GetRegistrationInfo("seriesrecordings").ConfigureAwait(false);
  1721. if (!registration.IsValid)
  1722. {
  1723. _logger.LogInformation("Creating series recordings requires an active Emby Premiere subscription.");
  1724. return;
  1725. }
  1726. var service = GetService(timer.ServiceName);
  1727. var info = await _tvDtoService.GetSeriesTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  1728. // Set priority from default values
  1729. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  1730. info.Priority = defaultValues.Priority;
  1731. string newTimerId = null;
  1732. if (service is ISupportsNewTimerIds supportsNewTimerIds)
  1733. {
  1734. newTimerId = await supportsNewTimerIds.CreateSeriesTimer(info, cancellationToken).ConfigureAwait(false);
  1735. newTimerId = _tvDtoService.GetInternalSeriesTimerId(newTimerId).ToString("N");
  1736. }
  1737. else
  1738. {
  1739. await service.CreateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1740. }
  1741. SeriesTimerCreated?.Invoke(this, new GenericEventArgs<TimerEventInfo>
  1742. {
  1743. Argument = new TimerEventInfo
  1744. {
  1745. ProgramId = _tvDtoService.GetInternalProgramId(info.ProgramId),
  1746. Id = newTimerId
  1747. }
  1748. });
  1749. }
  1750. public async Task UpdateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  1751. {
  1752. var info = await _tvDtoService.GetTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  1753. var service = GetService(timer.ServiceName);
  1754. await service.UpdateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1755. }
  1756. public async Task UpdateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  1757. {
  1758. var info = await _tvDtoService.GetSeriesTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  1759. var service = GetService(timer.ServiceName);
  1760. await service.UpdateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1761. }
  1762. public GuideInfo GetGuideInfo()
  1763. {
  1764. var startDate = DateTime.UtcNow;
  1765. var endDate = startDate.AddDays(GetGuideDays());
  1766. return new GuideInfo
  1767. {
  1768. StartDate = startDate,
  1769. EndDate = endDate
  1770. };
  1771. }
  1772. /// <summary>
  1773. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1774. /// </summary>
  1775. public void Dispose()
  1776. {
  1777. Dispose(true);
  1778. }
  1779. private bool _isDisposed = false;
  1780. /// <summary>
  1781. /// Releases unmanaged and - optionally - managed resources.
  1782. /// </summary>
  1783. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1784. protected virtual void Dispose(bool dispose)
  1785. {
  1786. if (dispose)
  1787. {
  1788. _isDisposed = true;
  1789. }
  1790. }
  1791. private LiveTvServiceInfo[] GetServiceInfos()
  1792. {
  1793. return Services.Select(GetServiceInfo).ToArray();
  1794. }
  1795. private static LiveTvServiceInfo GetServiceInfo(ILiveTvService service)
  1796. {
  1797. return new LiveTvServiceInfo
  1798. {
  1799. Name = service.Name
  1800. };
  1801. }
  1802. public LiveTvInfo GetLiveTvInfo(CancellationToken cancellationToken)
  1803. {
  1804. var services = GetServiceInfos();
  1805. var info = new LiveTvInfo
  1806. {
  1807. Services = services,
  1808. IsEnabled = services.Length > 0
  1809. };
  1810. info.EnabledUsers = _userManager.Users
  1811. .Where(IsLiveTvEnabled)
  1812. .Select(i => i.Id.ToString("N"))
  1813. .ToArray();
  1814. return info;
  1815. }
  1816. private bool IsLiveTvEnabled(User user)
  1817. {
  1818. return user.Policy.EnableLiveTvAccess && (Services.Count > 1 || GetConfiguration().TunerHosts.Length > 0);
  1819. }
  1820. public IEnumerable<User> GetEnabledUsers()
  1821. {
  1822. return _userManager.Users
  1823. .Where(IsLiveTvEnabled);
  1824. }
  1825. /// <summary>
  1826. /// Resets the tuner.
  1827. /// </summary>
  1828. /// <param name="id">The identifier.</param>
  1829. /// <param name="cancellationToken">The cancellation token.</param>
  1830. /// <returns>Task.</returns>
  1831. public Task ResetTuner(string id, CancellationToken cancellationToken)
  1832. {
  1833. var parts = id.Split(new[] { '_' }, 2);
  1834. var service = _services.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N"), parts[0], StringComparison.OrdinalIgnoreCase));
  1835. if (service == null)
  1836. {
  1837. throw new ArgumentException("Service not found.");
  1838. }
  1839. return service.ResetTuner(parts[1], cancellationToken);
  1840. }
  1841. private static void RemoveFields(DtoOptions options)
  1842. {
  1843. var fields = options.Fields.ToList();
  1844. fields.Remove(ItemFields.CanDelete);
  1845. fields.Remove(ItemFields.CanDownload);
  1846. fields.Remove(ItemFields.DisplayPreferencesId);
  1847. fields.Remove(ItemFields.Etag);
  1848. options.Fields = fields.ToArray();
  1849. }
  1850. public Folder GetInternalLiveTvFolder(CancellationToken cancellationToken)
  1851. {
  1852. var name = _localization.GetLocalizedString("HeaderLiveTV");
  1853. return _libraryManager.GetNamedView(name, CollectionType.LiveTv, name);
  1854. }
  1855. public async Task<TunerHostInfo> SaveTunerHost(TunerHostInfo info, bool dataSourceChanged = true)
  1856. {
  1857. info = _jsonSerializer.DeserializeFromString<TunerHostInfo>(_jsonSerializer.SerializeToString(info));
  1858. var provider = _tunerHosts.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  1859. if (provider == null)
  1860. {
  1861. throw new ResourceNotFoundException();
  1862. }
  1863. if (provider is IConfigurableTunerHost configurable)
  1864. {
  1865. await configurable.Validate(info).ConfigureAwait(false);
  1866. }
  1867. var config = GetConfiguration();
  1868. var list = config.TunerHosts.ToList();
  1869. var index = list.FindIndex(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase));
  1870. if (index == -1 || string.IsNullOrWhiteSpace(info.Id))
  1871. {
  1872. info.Id = Guid.NewGuid().ToString("N");
  1873. list.Add(info);
  1874. config.TunerHosts = list.ToArray();
  1875. }
  1876. else
  1877. {
  1878. config.TunerHosts[index] = info;
  1879. }
  1880. _config.SaveConfiguration("livetv", config);
  1881. if (dataSourceChanged)
  1882. {
  1883. _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
  1884. }
  1885. return info;
  1886. }
  1887. public async Task<ListingsProviderInfo> SaveListingProvider(ListingsProviderInfo info, bool validateLogin, bool validateListings)
  1888. {
  1889. // Hack to make the object a pure ListingsProviderInfo instead of an AddListingProvider
  1890. // ServerConfiguration.SaveConfiguration crashes during xml serialization for AddListingProvider
  1891. info = _jsonSerializer.DeserializeFromString<ListingsProviderInfo>(_jsonSerializer.SerializeToString(info));
  1892. var provider = _listingProviders.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  1893. if (provider == null)
  1894. {
  1895. throw new ResourceNotFoundException(
  1896. string.Format("Couldn't find provider of type: '{0}'", info.Type)
  1897. );
  1898. }
  1899. await provider.Validate(info, validateLogin, validateListings).ConfigureAwait(false);
  1900. var config = GetConfiguration();
  1901. var list = config.ListingProviders.ToList();
  1902. int index = list.FindIndex(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase));
  1903. if (index == -1 || string.IsNullOrWhiteSpace(info.Id))
  1904. {
  1905. info.Id = Guid.NewGuid().ToString("N");
  1906. list.Add(info);
  1907. config.ListingProviders = list.ToArray();
  1908. }
  1909. else
  1910. {
  1911. config.ListingProviders[index] = info;
  1912. }
  1913. _config.SaveConfiguration("livetv", config);
  1914. _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
  1915. return info;
  1916. }
  1917. public void DeleteListingsProvider(string id)
  1918. {
  1919. var config = GetConfiguration();
  1920. config.ListingProviders = config.ListingProviders.Where(i => !string.Equals(id, i.Id, StringComparison.OrdinalIgnoreCase)).ToArray();
  1921. _config.SaveConfiguration("livetv", config);
  1922. _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
  1923. }
  1924. public async Task<TunerChannelMapping> SetChannelMapping(string providerId, string tunerChannelId, string providerChannelId)
  1925. {
  1926. var config = GetConfiguration();
  1927. var listingsProviderInfo = config.ListingProviders.First(i => string.Equals(providerId, i.Id, StringComparison.OrdinalIgnoreCase));
  1928. listingsProviderInfo.ChannelMappings = listingsProviderInfo.ChannelMappings.Where(i => !string.Equals(i.Name, tunerChannelId, StringComparison.OrdinalIgnoreCase)).ToArray();
  1929. if (!string.Equals(tunerChannelId, providerChannelId, StringComparison.OrdinalIgnoreCase))
  1930. {
  1931. var list = listingsProviderInfo.ChannelMappings.ToList();
  1932. list.Add(new NameValuePair
  1933. {
  1934. Name = tunerChannelId,
  1935. Value = providerChannelId
  1936. });
  1937. listingsProviderInfo.ChannelMappings = list.ToArray();
  1938. }
  1939. _config.SaveConfiguration("livetv", config);
  1940. var tunerChannels = await GetChannelsForListingsProvider(providerId, CancellationToken.None)
  1941. .ConfigureAwait(false);
  1942. var providerChannels = await GetChannelsFromListingsProviderData(providerId, CancellationToken.None)
  1943. .ConfigureAwait(false);
  1944. var mappings = listingsProviderInfo.ChannelMappings;
  1945. var tunerChannelMappings =
  1946. tunerChannels.Select(i => GetTunerChannelMapping(i, mappings, providerChannels)).ToList();
  1947. _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
  1948. return tunerChannelMappings.First(i => string.Equals(i.Id, tunerChannelId, StringComparison.OrdinalIgnoreCase));
  1949. }
  1950. public TunerChannelMapping GetTunerChannelMapping(ChannelInfo tunerChannel, NameValuePair[] mappings, List<ChannelInfo> epgChannels)
  1951. {
  1952. var result = new TunerChannelMapping
  1953. {
  1954. Name = tunerChannel.Name,
  1955. Id = tunerChannel.Id
  1956. };
  1957. if (!string.IsNullOrWhiteSpace(tunerChannel.Number))
  1958. {
  1959. result.Name = tunerChannel.Number + " " + result.Name;
  1960. }
  1961. var providerChannel = EmbyTV.EmbyTV.Current.GetEpgChannelFromTunerChannel(mappings, tunerChannel, epgChannels);
  1962. if (providerChannel != null)
  1963. {
  1964. result.ProviderChannelName = providerChannel.Name;
  1965. result.ProviderChannelId = providerChannel.Id;
  1966. }
  1967. return result;
  1968. }
  1969. public Task<List<NameIdPair>> GetLineups(string providerType, string providerId, string country, string location)
  1970. {
  1971. var config = GetConfiguration();
  1972. if (string.IsNullOrWhiteSpace(providerId))
  1973. {
  1974. var provider = _listingProviders.FirstOrDefault(i => string.Equals(providerType, i.Type, StringComparison.OrdinalIgnoreCase));
  1975. if (provider == null)
  1976. {
  1977. throw new ResourceNotFoundException();
  1978. }
  1979. return provider.GetLineups(null, country, location);
  1980. }
  1981. else
  1982. {
  1983. var info = config.ListingProviders.FirstOrDefault(i => string.Equals(i.Id, providerId, StringComparison.OrdinalIgnoreCase));
  1984. var provider = _listingProviders.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  1985. if (provider == null)
  1986. {
  1987. throw new ResourceNotFoundException();
  1988. }
  1989. return provider.GetLineups(info, country, location);
  1990. }
  1991. }
  1992. public Task<MBRegistrationRecord> GetRegistrationInfo(string feature)
  1993. {
  1994. if (string.Equals(feature, "seriesrecordings", StringComparison.OrdinalIgnoreCase))
  1995. {
  1996. feature = "embytvseriesrecordings";
  1997. }
  1998. if (string.Equals(feature, "dvr-l", StringComparison.OrdinalIgnoreCase))
  1999. {
  2000. var config = GetConfiguration();
  2001. if (config.TunerHosts.Length > 0 &&
  2002. config.ListingProviders.Count(i => (i.EnableAllTuners || i.EnabledTuners.Length > 0) && string.Equals(i.Type, SchedulesDirect.TypeName, StringComparison.OrdinalIgnoreCase)) > 0)
  2003. {
  2004. return Task.FromResult(new MBRegistrationRecord
  2005. {
  2006. IsRegistered = true,
  2007. IsValid = true
  2008. });
  2009. }
  2010. }
  2011. return _security.GetRegistrationStatus(feature);
  2012. }
  2013. public Task<List<ChannelInfo>> GetChannelsForListingsProvider(string id, CancellationToken cancellationToken)
  2014. {
  2015. var info = GetConfiguration().ListingProviders.First(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
  2016. return EmbyTV.EmbyTV.Current.GetChannelsForListingsProvider(info, cancellationToken);
  2017. }
  2018. public Task<List<ChannelInfo>> GetChannelsFromListingsProviderData(string id, CancellationToken cancellationToken)
  2019. {
  2020. var info = GetConfiguration().ListingProviders.First(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
  2021. var provider = _listingProviders.First(i => string.Equals(i.Type, info.Type, StringComparison.OrdinalIgnoreCase));
  2022. return provider.GetChannels(info, cancellationToken);
  2023. }
  2024. public Guid GetInternalChannelId(string serviceName, string externalId)
  2025. {
  2026. return _tvDtoService.GetInternalChannelId(serviceName, externalId);
  2027. }
  2028. public Guid GetInternalProgramId(string externalId)
  2029. {
  2030. return _tvDtoService.GetInternalProgramId(externalId);
  2031. }
  2032. public List<BaseItem> GetRecordingFolders(User user)
  2033. {
  2034. return GetRecordingFolders(user, false);
  2035. }
  2036. private List<BaseItem> GetRecordingFolders(User user, bool refreshChannels)
  2037. {
  2038. var folders = EmbyTV.EmbyTV.Current.GetRecordingFolders()
  2039. .SelectMany(i => i.Locations)
  2040. .Distinct(StringComparer.OrdinalIgnoreCase)
  2041. .Select(i => _libraryManager.FindByPath(i, true))
  2042. .Where(i => i != null)
  2043. .Where(i => i.IsVisibleStandalone(user))
  2044. .SelectMany(i => _libraryManager.GetCollectionFolders(i))
  2045. .DistinctBy(i => i.Id)
  2046. .OrderBy(i => i.SortName)
  2047. .ToList();
  2048. folders.AddRange(_channelManager().GetChannelsInternal(new MediaBrowser.Model.Channels.ChannelQuery
  2049. {
  2050. UserId = user.Id,
  2051. IsRecordingsFolder = true,
  2052. RefreshLatestChannelItems = refreshChannels
  2053. }).Items);
  2054. return folders.Cast<BaseItem>().ToList();
  2055. }
  2056. }
  2057. }