LiveTvManager.cs 114 KB

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