LiveTvManager.cs 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111
  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<BaseItem>> 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. return _libraryManager.GetItemsResult(internalQuery);
  182. }
  183. public LiveTvChannel GetInternalChannel(string id)
  184. {
  185. return GetInternalChannel(new Guid(id));
  186. }
  187. private LiveTvChannel GetInternalChannel(Guid id)
  188. {
  189. return _libraryManager.GetItemById(id) as LiveTvChannel;
  190. }
  191. internal LiveTvProgram GetInternalProgram(string id)
  192. {
  193. return _libraryManager.GetItemById(id) as LiveTvProgram;
  194. }
  195. internal LiveTvProgram GetInternalProgram(Guid id)
  196. {
  197. return _libraryManager.GetItemById(id) as LiveTvProgram;
  198. }
  199. public async Task<BaseItem> GetInternalRecording(string id, CancellationToken cancellationToken)
  200. {
  201. if (string.IsNullOrWhiteSpace(id))
  202. {
  203. throw new ArgumentNullException("id");
  204. }
  205. var result = await GetInternalRecordings(new RecordingQuery
  206. {
  207. Id = id
  208. }, new DtoOptions(), cancellationToken).ConfigureAwait(false);
  209. return result.Items.FirstOrDefault();
  210. }
  211. public async Task<MediaSourceInfo> GetRecordingStream(string id, CancellationToken cancellationToken)
  212. {
  213. var info = await GetLiveStream(id, null, false, cancellationToken).ConfigureAwait(false);
  214. return info.Item1;
  215. }
  216. public Task<Tuple<MediaSourceInfo, IDirectStreamProvider>> GetChannelStream(string id, string mediaSourceId, CancellationToken cancellationToken)
  217. {
  218. return GetLiveStream(id, mediaSourceId, true, cancellationToken);
  219. }
  220. private string GetItemExternalId(BaseItem item)
  221. {
  222. var externalId = item.ExternalId;
  223. if (string.IsNullOrWhiteSpace(externalId))
  224. {
  225. externalId = item.GetProviderId("ProviderExternalId");
  226. }
  227. return externalId;
  228. }
  229. public async Task<IEnumerable<MediaSourceInfo>> GetRecordingMediaSources(IHasMediaSources item, CancellationToken cancellationToken)
  230. {
  231. var baseItem = (BaseItem)item;
  232. var service = GetService(baseItem);
  233. return await service.GetRecordingStreamMediaSources(GetItemExternalId(baseItem), cancellationToken).ConfigureAwait(false);
  234. }
  235. public async Task<IEnumerable<MediaSourceInfo>> GetChannelMediaSources(IHasMediaSources item, CancellationToken cancellationToken)
  236. {
  237. var baseItem = (LiveTvChannel)item;
  238. var service = GetService(baseItem);
  239. var sources = await service.GetChannelStreamMediaSources(baseItem.ExternalId, cancellationToken).ConfigureAwait(false);
  240. if (sources.Count == 0)
  241. {
  242. throw new NotImplementedException();
  243. }
  244. var list = sources.ToList();
  245. foreach (var source in list)
  246. {
  247. Normalize(source, service, baseItem.ChannelType == ChannelType.TV);
  248. }
  249. return list;
  250. }
  251. private ILiveTvService GetService(ILiveTvRecording item)
  252. {
  253. return GetService(item.ServiceName);
  254. }
  255. private ILiveTvService GetService(BaseItem item)
  256. {
  257. return GetService(item.ServiceName);
  258. }
  259. private ILiveTvService GetService(string name)
  260. {
  261. return _services.FirstOrDefault(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase));
  262. }
  263. private async Task<Tuple<MediaSourceInfo, IDirectStreamProvider>> GetLiveStream(string id, string mediaSourceId, bool isChannel, CancellationToken cancellationToken)
  264. {
  265. if (string.Equals(id, mediaSourceId, StringComparison.OrdinalIgnoreCase))
  266. {
  267. mediaSourceId = null;
  268. }
  269. MediaSourceInfo info;
  270. bool isVideo;
  271. ILiveTvService service;
  272. IDirectStreamProvider directStreamProvider = null;
  273. if (isChannel)
  274. {
  275. var channel = GetInternalChannel(id);
  276. isVideo = channel.ChannelType == ChannelType.TV;
  277. service = GetService(channel);
  278. _logger.Info("Opening channel stream from {0}, external channel Id: {1}", service.Name, GetItemExternalId(channel));
  279. var supportsManagedStream = service as ISupportsDirectStreamProvider;
  280. if (supportsManagedStream != null)
  281. {
  282. var streamInfo = await supportsManagedStream.GetChannelStreamWithDirectStreamProvider(GetItemExternalId(channel), mediaSourceId, cancellationToken).ConfigureAwait(false);
  283. info = streamInfo.Item1;
  284. directStreamProvider = streamInfo.Item2;
  285. }
  286. else
  287. {
  288. info = await service.GetChannelStream(GetItemExternalId(channel), mediaSourceId, cancellationToken).ConfigureAwait(false);
  289. }
  290. info.RequiresClosing = true;
  291. if (info.RequiresClosing)
  292. {
  293. var idPrefix = service.GetType().FullName.GetMD5().ToString("N") + "_";
  294. info.LiveStreamId = idPrefix + info.Id;
  295. }
  296. }
  297. else
  298. {
  299. var recording = await GetInternalRecording(id, cancellationToken).ConfigureAwait(false);
  300. isVideo = !string.Equals(recording.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase);
  301. service = GetService(recording);
  302. _logger.Info("Opening recording stream from {0}, external recording Id: {1}", service.Name, GetItemExternalId(recording));
  303. info = await service.GetRecordingStream(GetItemExternalId(recording), null, cancellationToken).ConfigureAwait(false);
  304. info.RequiresClosing = true;
  305. if (info.RequiresClosing)
  306. {
  307. var idPrefix = service.GetType().FullName.GetMD5().ToString("N") + "_";
  308. info.LiveStreamId = idPrefix + info.Id;
  309. }
  310. }
  311. Normalize(info, service, isVideo);
  312. return new Tuple<MediaSourceInfo, IDirectStreamProvider>(info, directStreamProvider);
  313. }
  314. private void Normalize(MediaSourceInfo mediaSource, ILiveTvService service, bool isVideo)
  315. {
  316. if (mediaSource.MediaStreams.Count == 0)
  317. {
  318. if (isVideo)
  319. {
  320. mediaSource.MediaStreams.AddRange(new List<MediaStream>
  321. {
  322. new MediaStream
  323. {
  324. Type = MediaStreamType.Video,
  325. // Set the index to -1 because we don't know the exact index of the video stream within the container
  326. Index = -1,
  327. // Set to true if unknown to enable deinterlacing
  328. IsInterlaced = true
  329. },
  330. new MediaStream
  331. {
  332. Type = MediaStreamType.Audio,
  333. // Set the index to -1 because we don't know the exact index of the audio stream within the container
  334. Index = -1
  335. }
  336. });
  337. }
  338. else
  339. {
  340. mediaSource.MediaStreams.AddRange(new List<MediaStream>
  341. {
  342. new MediaStream
  343. {
  344. Type = MediaStreamType.Audio,
  345. // Set the index to -1 because we don't know the exact index of the audio stream within the container
  346. Index = -1
  347. }
  348. });
  349. }
  350. }
  351. // Clean some bad data coming from providers
  352. foreach (var stream in mediaSource.MediaStreams)
  353. {
  354. if (stream.BitRate.HasValue && stream.BitRate <= 0)
  355. {
  356. stream.BitRate = null;
  357. }
  358. if (stream.Channels.HasValue && stream.Channels <= 0)
  359. {
  360. stream.Channels = null;
  361. }
  362. if (stream.AverageFrameRate.HasValue && stream.AverageFrameRate <= 0)
  363. {
  364. stream.AverageFrameRate = null;
  365. }
  366. if (stream.RealFrameRate.HasValue && stream.RealFrameRate <= 0)
  367. {
  368. stream.RealFrameRate = null;
  369. }
  370. if (stream.Width.HasValue && stream.Width <= 0)
  371. {
  372. stream.Width = null;
  373. }
  374. if (stream.Height.HasValue && stream.Height <= 0)
  375. {
  376. stream.Height = null;
  377. }
  378. if (stream.SampleRate.HasValue && stream.SampleRate <= 0)
  379. {
  380. stream.SampleRate = null;
  381. }
  382. if (stream.Level.HasValue && stream.Level <= 0)
  383. {
  384. stream.Level = null;
  385. }
  386. }
  387. var indexes = mediaSource.MediaStreams.Select(i => i.Index).Distinct().ToList();
  388. // If there are duplicate stream indexes, set them all to unknown
  389. if (indexes.Count != mediaSource.MediaStreams.Count)
  390. {
  391. foreach (var stream in mediaSource.MediaStreams)
  392. {
  393. stream.Index = -1;
  394. }
  395. }
  396. // Set the total bitrate if not already supplied
  397. mediaSource.InferTotalBitrate();
  398. if (!(service is EmbyTV.EmbyTV))
  399. {
  400. // We can't trust that we'll be able to direct stream it through emby server, no matter what the provider says
  401. //mediaSource.SupportsDirectPlay = false;
  402. mediaSource.SupportsDirectStream = false;
  403. mediaSource.SupportsTranscoding = true;
  404. foreach (var stream in mediaSource.MediaStreams)
  405. {
  406. if (stream.Type == MediaStreamType.Video && string.IsNullOrWhiteSpace(stream.NalLengthSize))
  407. {
  408. stream.NalLengthSize = "0";
  409. }
  410. if (stream.Type == MediaStreamType.Video)
  411. {
  412. stream.IsInterlaced = true;
  413. }
  414. }
  415. }
  416. }
  417. private async Task<LiveTvChannel> GetChannel(ChannelInfo channelInfo, string serviceName, Guid parentFolderId, CancellationToken cancellationToken)
  418. {
  419. var isNew = false;
  420. var forceUpdate = false;
  421. var id = _tvDtoService.GetInternalChannelId(serviceName, channelInfo.Id);
  422. var item = _libraryManager.GetItemById(id) as LiveTvChannel;
  423. if (item == null)
  424. {
  425. item = new LiveTvChannel
  426. {
  427. Name = channelInfo.Name,
  428. Id = id,
  429. DateCreated = DateTime.UtcNow,
  430. };
  431. isNew = true;
  432. }
  433. if (!string.Equals(channelInfo.Id, item.ExternalId, StringComparison.Ordinal))
  434. {
  435. isNew = true;
  436. }
  437. item.ExternalId = channelInfo.Id;
  438. if (!item.ParentId.Equals(parentFolderId))
  439. {
  440. isNew = true;
  441. }
  442. item.ParentId = parentFolderId;
  443. item.ChannelType = channelInfo.ChannelType;
  444. item.ServiceName = serviceName;
  445. item.Number = channelInfo.Number;
  446. //if (!string.Equals(item.ProviderImageUrl, channelInfo.ImageUrl, StringComparison.OrdinalIgnoreCase))
  447. //{
  448. // isNew = true;
  449. // replaceImages.Add(ImageType.Primary);
  450. //}
  451. //if (!string.Equals(item.ProviderImagePath, channelInfo.ImagePath, StringComparison.OrdinalIgnoreCase))
  452. //{
  453. // isNew = true;
  454. // replaceImages.Add(ImageType.Primary);
  455. //}
  456. if (!item.HasImage(ImageType.Primary))
  457. {
  458. if (!string.IsNullOrWhiteSpace(channelInfo.ImagePath))
  459. {
  460. item.SetImagePath(ImageType.Primary, channelInfo.ImagePath);
  461. forceUpdate = true;
  462. }
  463. else if (!string.IsNullOrWhiteSpace(channelInfo.ImageUrl))
  464. {
  465. item.SetImagePath(ImageType.Primary, channelInfo.ImageUrl);
  466. forceUpdate = true;
  467. }
  468. }
  469. if (string.IsNullOrEmpty(item.Name))
  470. {
  471. item.Name = channelInfo.Name;
  472. }
  473. if (isNew)
  474. {
  475. await _libraryManager.CreateItem(item, cancellationToken).ConfigureAwait(false);
  476. }
  477. else if (forceUpdate)
  478. {
  479. await _libraryManager.UpdateItem(item, ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
  480. }
  481. await item.RefreshMetadata(new MetadataRefreshOptions(_fileSystem)
  482. {
  483. ForceSave = isNew || forceUpdate
  484. }, cancellationToken);
  485. return item;
  486. }
  487. private Tuple<LiveTvProgram, bool, bool> GetProgram(ProgramInfo info, Dictionary<Guid, LiveTvProgram> allExistingPrograms, LiveTvChannel channel, ChannelType channelType, string serviceName, CancellationToken cancellationToken)
  488. {
  489. var id = _tvDtoService.GetInternalProgramId(serviceName, info.Id);
  490. LiveTvProgram item = null;
  491. allExistingPrograms.TryGetValue(id, out item);
  492. var isNew = false;
  493. var forceUpdate = false;
  494. if (item == null)
  495. {
  496. isNew = true;
  497. item = new LiveTvProgram
  498. {
  499. Name = info.Name,
  500. Id = id,
  501. DateCreated = DateTime.UtcNow,
  502. DateModified = DateTime.UtcNow,
  503. ExternalEtag = info.Etag
  504. };
  505. }
  506. var seriesId = info.SeriesId;
  507. if (!item.ParentId.Equals(channel.Id))
  508. {
  509. forceUpdate = true;
  510. }
  511. item.ParentId = channel.Id;
  512. //item.ChannelType = channelType;
  513. item.ServiceName = serviceName;
  514. item.Audio = info.Audio;
  515. item.ChannelId = channel.Id.ToString("N");
  516. item.CommunityRating = item.CommunityRating ?? info.CommunityRating;
  517. if ((item.CommunityRating ?? 0).Equals(0))
  518. {
  519. item.CommunityRating = null;
  520. }
  521. item.EpisodeTitle = info.EpisodeTitle;
  522. item.ExternalId = info.Id;
  523. if (!string.IsNullOrWhiteSpace(seriesId) && !string.Equals(item.ExternalSeriesId, seriesId, StringComparison.Ordinal))
  524. {
  525. forceUpdate = true;
  526. }
  527. item.ExternalSeriesId = seriesId;
  528. item.Genres = info.Genres;
  529. item.IsHD = info.IsHD;
  530. item.IsKids = info.IsKids;
  531. item.IsLive = info.IsLive;
  532. item.IsMovie = info.IsMovie;
  533. item.IsNews = info.IsNews;
  534. item.IsPremiere = info.IsPremiere;
  535. item.IsRepeat = info.IsRepeat;
  536. item.IsSeries = info.IsSeries;
  537. item.IsSports = info.IsSports;
  538. item.Name = info.Name;
  539. item.OfficialRating = item.OfficialRating ?? info.OfficialRating;
  540. item.Overview = item.Overview ?? info.Overview;
  541. item.RunTimeTicks = (info.EndDate - info.StartDate).Ticks;
  542. if (item.StartDate != info.StartDate)
  543. {
  544. forceUpdate = true;
  545. }
  546. item.StartDate = info.StartDate;
  547. if (item.EndDate != info.EndDate)
  548. {
  549. forceUpdate = true;
  550. }
  551. item.EndDate = info.EndDate;
  552. item.HomePageUrl = info.HomePageUrl;
  553. item.ProductionYear = info.ProductionYear;
  554. if (!info.IsSeries || info.IsRepeat)
  555. {
  556. item.PremiereDate = info.OriginalAirDate;
  557. }
  558. item.IndexNumber = info.EpisodeNumber;
  559. item.ParentIndexNumber = info.SeasonNumber;
  560. if (!item.HasImage(ImageType.Primary))
  561. {
  562. if (!string.IsNullOrWhiteSpace(info.ImagePath))
  563. {
  564. item.SetImage(new ItemImageInfo
  565. {
  566. Path = info.ImagePath,
  567. Type = ImageType.Primary
  568. }, 0);
  569. }
  570. else if (!string.IsNullOrWhiteSpace(info.ImageUrl))
  571. {
  572. item.SetImage(new ItemImageInfo
  573. {
  574. Path = info.ImageUrl,
  575. Type = ImageType.Primary
  576. }, 0);
  577. }
  578. }
  579. if (!item.HasImage(ImageType.Thumb))
  580. {
  581. if (!string.IsNullOrWhiteSpace(info.ThumbImageUrl))
  582. {
  583. item.SetImage(new ItemImageInfo
  584. {
  585. Path = info.ThumbImageUrl,
  586. Type = ImageType.Thumb
  587. }, 0);
  588. }
  589. }
  590. if (!item.HasImage(ImageType.Logo))
  591. {
  592. if (!string.IsNullOrWhiteSpace(info.LogoImageUrl))
  593. {
  594. item.SetImage(new ItemImageInfo
  595. {
  596. Path = info.LogoImageUrl,
  597. Type = ImageType.Logo
  598. }, 0);
  599. }
  600. }
  601. if (!item.HasImage(ImageType.Backdrop))
  602. {
  603. if (!string.IsNullOrWhiteSpace(info.BackdropImageUrl))
  604. {
  605. item.SetImage(new ItemImageInfo
  606. {
  607. Path = info.BackdropImageUrl,
  608. Type = ImageType.Backdrop
  609. }, 0);
  610. }
  611. }
  612. var isUpdated = false;
  613. if (isNew)
  614. {
  615. }
  616. else if (forceUpdate || string.IsNullOrWhiteSpace(info.Etag))
  617. {
  618. isUpdated = true;
  619. }
  620. else
  621. {
  622. // Increment this whenver some internal change deems it necessary
  623. var etag = info.Etag + "6";
  624. if (!string.Equals(etag, item.ExternalEtag, StringComparison.OrdinalIgnoreCase))
  625. {
  626. item.ExternalEtag = etag;
  627. isUpdated = true;
  628. }
  629. }
  630. return new Tuple<LiveTvProgram, bool, bool>(item, isNew, isUpdated);
  631. }
  632. private async Task<Guid> CreateRecordingRecord(RecordingInfo info, string serviceName, Guid parentFolderId, CancellationToken cancellationToken)
  633. {
  634. var isNew = false;
  635. var id = _tvDtoService.GetInternalRecordingId(serviceName, info.Id);
  636. var item = _itemRepo.RetrieveItem(id);
  637. if (item == null)
  638. {
  639. if (info.ChannelType == ChannelType.TV)
  640. {
  641. item = new LiveTvVideoRecording
  642. {
  643. Name = info.Name,
  644. Id = id,
  645. DateCreated = DateTime.UtcNow,
  646. DateModified = DateTime.UtcNow,
  647. VideoType = VideoType.VideoFile
  648. };
  649. }
  650. else
  651. {
  652. item = new LiveTvAudioRecording
  653. {
  654. Name = info.Name,
  655. Id = id,
  656. DateCreated = DateTime.UtcNow,
  657. DateModified = DateTime.UtcNow
  658. };
  659. }
  660. isNew = true;
  661. }
  662. item.ChannelId = _tvDtoService.GetInternalChannelId(serviceName, info.ChannelId).ToString("N");
  663. item.CommunityRating = info.CommunityRating;
  664. item.OfficialRating = info.OfficialRating;
  665. item.Overview = info.Overview;
  666. item.EndDate = info.EndDate;
  667. item.Genres = info.Genres;
  668. item.PremiereDate = info.OriginalAirDate;
  669. var recording = (ILiveTvRecording)item;
  670. recording.ExternalId = info.Id;
  671. var dataChanged = false;
  672. recording.Audio = info.Audio;
  673. recording.EndDate = info.EndDate;
  674. recording.EpisodeTitle = info.EpisodeTitle;
  675. recording.IsHD = info.IsHD;
  676. recording.IsKids = info.IsKids;
  677. recording.IsLive = info.IsLive;
  678. recording.IsMovie = info.IsMovie;
  679. recording.IsNews = info.IsNews;
  680. recording.IsPremiere = info.IsPremiere;
  681. recording.IsRepeat = info.IsRepeat;
  682. recording.IsSports = info.IsSports;
  683. recording.SeriesTimerId = info.SeriesTimerId;
  684. recording.TimerId = info.TimerId;
  685. recording.StartDate = info.StartDate;
  686. if (!dataChanged)
  687. {
  688. dataChanged = recording.IsSeries != info.IsSeries;
  689. }
  690. recording.IsSeries = info.IsSeries;
  691. if (!item.ParentId.Equals(parentFolderId))
  692. {
  693. dataChanged = true;
  694. }
  695. item.ParentId = parentFolderId;
  696. if (!item.HasImage(ImageType.Primary))
  697. {
  698. if (!string.IsNullOrWhiteSpace(info.ImagePath))
  699. {
  700. item.SetImage(new ItemImageInfo
  701. {
  702. Path = info.ImagePath,
  703. Type = ImageType.Primary,
  704. IsPlaceholder = true
  705. }, 0);
  706. }
  707. else if (!string.IsNullOrWhiteSpace(info.ImageUrl))
  708. {
  709. item.SetImage(new ItemImageInfo
  710. {
  711. Path = info.ImageUrl,
  712. Type = ImageType.Primary,
  713. IsPlaceholder = true
  714. }, 0);
  715. }
  716. }
  717. var statusChanged = info.Status != recording.Status;
  718. recording.Status = info.Status;
  719. recording.ServiceName = serviceName;
  720. if (!string.IsNullOrEmpty(info.Path))
  721. {
  722. if (!dataChanged)
  723. {
  724. dataChanged = !string.Equals(item.Path, info.Path);
  725. }
  726. var fileInfo = _fileSystem.GetFileInfo(info.Path);
  727. recording.DateCreated = _fileSystem.GetCreationTimeUtc(fileInfo);
  728. recording.DateModified = _fileSystem.GetLastWriteTimeUtc(fileInfo);
  729. item.Path = info.Path;
  730. }
  731. else if (!string.IsNullOrEmpty(info.Url))
  732. {
  733. if (!dataChanged)
  734. {
  735. dataChanged = !string.Equals(item.Path, info.Url);
  736. }
  737. item.Path = info.Url;
  738. }
  739. var metadataRefreshMode = MetadataRefreshMode.Default;
  740. if (isNew)
  741. {
  742. await _libraryManager.CreateItem(item, cancellationToken).ConfigureAwait(false);
  743. }
  744. else if (dataChanged || info.DateLastUpdated > recording.DateLastSaved || statusChanged)
  745. {
  746. metadataRefreshMode = MetadataRefreshMode.FullRefresh;
  747. await _libraryManager.UpdateItem(item, ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
  748. }
  749. if (info.Status != RecordingStatus.InProgress)
  750. {
  751. _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem)
  752. {
  753. MetadataRefreshMode = metadataRefreshMode
  754. }, RefreshPriority.Normal);
  755. }
  756. return item.Id;
  757. }
  758. public async Task<BaseItemDto> GetProgram(string id, CancellationToken cancellationToken, User user = null)
  759. {
  760. var program = GetInternalProgram(id);
  761. var dto = _dtoService.GetBaseItemDto(program, new DtoOptions(), user);
  762. var list = new List<Tuple<BaseItemDto, string, string, string>>();
  763. var externalSeriesId = program.ExternalSeriesId;
  764. list.Add(new Tuple<BaseItemDto, string, string, string>(dto, program.ServiceName, GetItemExternalId(program), externalSeriesId));
  765. await AddRecordingInfo(list, cancellationToken).ConfigureAwait(false);
  766. return dto;
  767. }
  768. public async Task<QueryResult<BaseItemDto>> GetPrograms(ProgramQuery query, DtoOptions options, CancellationToken cancellationToken)
  769. {
  770. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  771. var topFolder = await GetInternalLiveTvFolder(cancellationToken).ConfigureAwait(false);
  772. if (query.SortBy.Length == 0)
  773. {
  774. // Unless something else was specified, order by start date to take advantage of a specialized index
  775. query.SortBy = new[] { ItemSortBy.StartDate };
  776. }
  777. RemoveFields(options);
  778. var internalQuery = new InternalItemsQuery(user)
  779. {
  780. IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
  781. MinEndDate = query.MinEndDate,
  782. MinStartDate = query.MinStartDate,
  783. MaxEndDate = query.MaxEndDate,
  784. MaxStartDate = query.MaxStartDate,
  785. ChannelIds = query.ChannelIds,
  786. IsMovie = query.IsMovie,
  787. IsSeries = query.IsSeries,
  788. IsSports = query.IsSports,
  789. IsKids = query.IsKids,
  790. IsNews = query.IsNews,
  791. Genres = query.Genres,
  792. StartIndex = query.StartIndex,
  793. Limit = query.Limit,
  794. SortBy = query.SortBy,
  795. SortOrder = query.SortOrder ?? SortOrder.Ascending,
  796. EnableTotalRecordCount = query.EnableTotalRecordCount,
  797. TopParentIds = new[] { topFolder.Id.ToString("N") },
  798. Name = query.Name,
  799. DtoOptions = options
  800. };
  801. if (!string.IsNullOrWhiteSpace(query.SeriesTimerId))
  802. {
  803. var seriesTimers = await GetSeriesTimersInternal(new SeriesTimerQuery { }, cancellationToken).ConfigureAwait(false);
  804. var seriesTimer = seriesTimers.Items.FirstOrDefault(i => string.Equals(_tvDtoService.GetInternalSeriesTimerId(i.ServiceName, i.Id).ToString("N"), query.SeriesTimerId, StringComparison.OrdinalIgnoreCase));
  805. if (seriesTimer != null)
  806. {
  807. internalQuery.ExternalSeriesId = seriesTimer.SeriesId;
  808. if (string.IsNullOrWhiteSpace(seriesTimer.SeriesId))
  809. {
  810. // Better to return nothing than every program in the database
  811. return new QueryResult<BaseItemDto>();
  812. }
  813. }
  814. else
  815. {
  816. // Better to return nothing than every program in the database
  817. return new QueryResult<BaseItemDto>();
  818. }
  819. }
  820. if (query.HasAired.HasValue)
  821. {
  822. if (query.HasAired.Value)
  823. {
  824. internalQuery.MaxEndDate = DateTime.UtcNow;
  825. }
  826. else
  827. {
  828. internalQuery.MinEndDate = DateTime.UtcNow;
  829. }
  830. }
  831. var queryResult = _libraryManager.QueryItems(internalQuery);
  832. var returnArray = (await _dtoService.GetBaseItemDtos(queryResult.Items, options, user)
  833. .ConfigureAwait(false));
  834. var result = new QueryResult<BaseItemDto>
  835. {
  836. Items = returnArray,
  837. TotalRecordCount = queryResult.TotalRecordCount
  838. };
  839. return result;
  840. }
  841. public async Task<QueryResult<BaseItem>> GetRecommendedProgramsInternal(RecommendedProgramQuery query, DtoOptions options, CancellationToken cancellationToken)
  842. {
  843. var user = _userManager.GetUserById(query.UserId);
  844. var topFolder = await GetInternalLiveTvFolder(cancellationToken).ConfigureAwait(false);
  845. var internalQuery = new InternalItemsQuery(user)
  846. {
  847. IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
  848. IsAiring = query.IsAiring,
  849. IsNews = query.IsNews,
  850. IsMovie = query.IsMovie,
  851. IsSeries = query.IsSeries,
  852. IsSports = query.IsSports,
  853. IsKids = query.IsKids,
  854. EnableTotalRecordCount = query.EnableTotalRecordCount,
  855. SortBy = new[] { ItemSortBy.StartDate },
  856. TopParentIds = new[] { topFolder.Id.ToString("N") },
  857. DtoOptions = options
  858. };
  859. if (query.Limit.HasValue)
  860. {
  861. internalQuery.Limit = Math.Max(query.Limit.Value * 4, 200);
  862. }
  863. if (query.HasAired.HasValue)
  864. {
  865. if (query.HasAired.Value)
  866. {
  867. internalQuery.MaxEndDate = DateTime.UtcNow;
  868. }
  869. else
  870. {
  871. internalQuery.MinEndDate = DateTime.UtcNow;
  872. }
  873. }
  874. var programList = _libraryManager.QueryItems(internalQuery).Items;
  875. var totalCount = programList.Length;
  876. IOrderedEnumerable<LiveTvProgram> orderedPrograms = programList.Cast<LiveTvProgram>().OrderBy(i => i.StartDate.Date);
  877. if (query.IsAiring ?? false)
  878. {
  879. orderedPrograms = orderedPrograms
  880. .ThenByDescending(i => GetRecommendationScore(i, user.Id, true));
  881. }
  882. IEnumerable<BaseItem> programs = orderedPrograms;
  883. if (query.Limit.HasValue)
  884. {
  885. programs = programs.Take(query.Limit.Value);
  886. }
  887. var result = new QueryResult<BaseItem>
  888. {
  889. Items = programs.ToArray(),
  890. TotalRecordCount = totalCount
  891. };
  892. return result;
  893. }
  894. public async Task<QueryResult<BaseItemDto>> GetRecommendedPrograms(RecommendedProgramQuery query, DtoOptions options, CancellationToken cancellationToken)
  895. {
  896. RemoveFields(options);
  897. var internalResult = await GetRecommendedProgramsInternal(query, options, cancellationToken).ConfigureAwait(false);
  898. var user = _userManager.GetUserById(query.UserId);
  899. var returnArray = (await _dtoService.GetBaseItemDtos(internalResult.Items, options, user)
  900. .ConfigureAwait(false));
  901. var result = new QueryResult<BaseItemDto>
  902. {
  903. Items = returnArray,
  904. TotalRecordCount = internalResult.TotalRecordCount
  905. };
  906. return result;
  907. }
  908. private int GetRecommendationScore(LiveTvProgram program, Guid userId, bool factorChannelWatchCount)
  909. {
  910. var score = 0;
  911. if (program.IsLive)
  912. {
  913. score++;
  914. }
  915. if (program.IsSeries && !program.IsRepeat)
  916. {
  917. score++;
  918. }
  919. var channel = GetInternalChannel(program.ChannelId);
  920. if (channel != null)
  921. {
  922. var channelUserdata = _userDataManager.GetUserData(userId, channel);
  923. if (channelUserdata.Likes ?? false)
  924. {
  925. score += 2;
  926. }
  927. else if (!(channelUserdata.Likes ?? true))
  928. {
  929. score -= 2;
  930. }
  931. if (channelUserdata.IsFavorite)
  932. {
  933. score += 3;
  934. }
  935. if (factorChannelWatchCount)
  936. {
  937. score += channelUserdata.PlayCount;
  938. }
  939. }
  940. return score;
  941. }
  942. private async Task AddRecordingInfo(IEnumerable<Tuple<BaseItemDto, string, string, string>> programs, CancellationToken cancellationToken)
  943. {
  944. var timers = new Dictionary<string, List<TimerInfo>>();
  945. var seriesTimers = new Dictionary<string, List<SeriesTimerInfo>>();
  946. foreach (var programTuple in programs)
  947. {
  948. var program = programTuple.Item1;
  949. var serviceName = programTuple.Item2;
  950. var externalProgramId = programTuple.Item3;
  951. string externalSeriesId = programTuple.Item4;
  952. if (string.IsNullOrWhiteSpace(serviceName))
  953. {
  954. continue;
  955. }
  956. List<TimerInfo> timerList;
  957. if (!timers.TryGetValue(serviceName, out timerList))
  958. {
  959. try
  960. {
  961. var tempTimers = await GetService(serviceName).GetTimersAsync(cancellationToken).ConfigureAwait(false);
  962. timers[serviceName] = timerList = tempTimers.ToList();
  963. }
  964. catch (Exception ex)
  965. {
  966. _logger.ErrorException("Error getting timer infos", ex);
  967. timers[serviceName] = timerList = new List<TimerInfo>();
  968. }
  969. }
  970. var timer = timerList.FirstOrDefault(i => string.Equals(i.ProgramId, externalProgramId, StringComparison.OrdinalIgnoreCase));
  971. var foundSeriesTimer = false;
  972. if (timer != null)
  973. {
  974. if (timer.Status != RecordingStatus.Cancelled && timer.Status != RecordingStatus.Error)
  975. {
  976. program.TimerId = _tvDtoService.GetInternalTimerId(serviceName, timer.Id)
  977. .ToString("N");
  978. program.Status = timer.Status.ToString();
  979. }
  980. if (!string.IsNullOrEmpty(timer.SeriesTimerId))
  981. {
  982. program.SeriesTimerId = _tvDtoService.GetInternalSeriesTimerId(serviceName, timer.SeriesTimerId)
  983. .ToString("N");
  984. foundSeriesTimer = true;
  985. }
  986. }
  987. if (foundSeriesTimer || string.IsNullOrWhiteSpace(externalSeriesId))
  988. {
  989. continue;
  990. }
  991. List<SeriesTimerInfo> seriesTimerList;
  992. if (!seriesTimers.TryGetValue(serviceName, out seriesTimerList))
  993. {
  994. try
  995. {
  996. var tempTimers = await GetService(serviceName).GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false);
  997. seriesTimers[serviceName] = seriesTimerList = tempTimers.ToList();
  998. }
  999. catch (Exception ex)
  1000. {
  1001. _logger.ErrorException("Error getting series timer infos", ex);
  1002. seriesTimers[serviceName] = seriesTimerList = new List<SeriesTimerInfo>();
  1003. }
  1004. }
  1005. var seriesTimer = seriesTimerList.FirstOrDefault(i => string.Equals(i.SeriesId, externalSeriesId, StringComparison.OrdinalIgnoreCase));
  1006. if (seriesTimer != null)
  1007. {
  1008. program.SeriesTimerId = _tvDtoService.GetInternalSeriesTimerId(serviceName, seriesTimer.Id)
  1009. .ToString("N");
  1010. }
  1011. }
  1012. }
  1013. internal Task RefreshChannels(IProgress<double> progress, CancellationToken cancellationToken)
  1014. {
  1015. return RefreshChannelsInternal(progress, cancellationToken);
  1016. }
  1017. private async Task RefreshChannelsInternal(IProgress<double> progress, CancellationToken cancellationToken)
  1018. {
  1019. EmbyTV.EmbyTV.Current.CreateRecordingFolders();
  1020. await EmbyTV.EmbyTV.Current.ScanForTunerDeviceChanges(cancellationToken).ConfigureAwait(false);
  1021. var numComplete = 0;
  1022. double progressPerService = _services.Count == 0
  1023. ? 0
  1024. : 1 / _services.Count;
  1025. var newChannelIdList = new List<Guid>();
  1026. var newProgramIdList = new List<Guid>();
  1027. foreach (var service in _services)
  1028. {
  1029. cancellationToken.ThrowIfCancellationRequested();
  1030. _logger.Debug("Refreshing guide from {0}", service.Name);
  1031. try
  1032. {
  1033. var innerProgress = new ActionableProgress<double>();
  1034. innerProgress.RegisterAction(p => progress.Report(p * progressPerService));
  1035. var idList = await RefreshChannelsInternal(service, innerProgress, cancellationToken).ConfigureAwait(false);
  1036. newChannelIdList.AddRange(idList.Item1);
  1037. newProgramIdList.AddRange(idList.Item2);
  1038. }
  1039. catch (OperationCanceledException)
  1040. {
  1041. throw;
  1042. }
  1043. catch (Exception ex)
  1044. {
  1045. _logger.ErrorException("Error refreshing channels for service", ex);
  1046. }
  1047. numComplete++;
  1048. double percent = numComplete;
  1049. percent /= _services.Count;
  1050. progress.Report(100 * percent);
  1051. }
  1052. await CleanDatabaseInternal(newChannelIdList.ToArray(), new[] { typeof(LiveTvChannel).Name }, progress, cancellationToken).ConfigureAwait(false);
  1053. await CleanDatabaseInternal(newProgramIdList.ToArray(), new[] { typeof(LiveTvProgram).Name }, progress, cancellationToken).ConfigureAwait(false);
  1054. var coreService = _services.OfType<EmbyTV.EmbyTV>().FirstOrDefault();
  1055. if (coreService != null)
  1056. {
  1057. await coreService.RefreshSeriesTimers(cancellationToken, new SimpleProgress<double>()).ConfigureAwait(false);
  1058. await coreService.RefreshTimers(cancellationToken, new SimpleProgress<double>()).ConfigureAwait(false);
  1059. }
  1060. // Load these now which will prefetch metadata
  1061. var dtoOptions = new DtoOptions();
  1062. var fields = dtoOptions.Fields.ToList();
  1063. fields.Remove(ItemFields.SyncInfo);
  1064. fields.Remove(ItemFields.BasicSyncInfo);
  1065. dtoOptions.Fields = fields.ToArray(fields.Count);
  1066. await GetRecordings(new RecordingQuery(), dtoOptions, cancellationToken).ConfigureAwait(false);
  1067. progress.Report(100);
  1068. }
  1069. private async Task<Tuple<List<Guid>, List<Guid>>> RefreshChannelsInternal(ILiveTvService service, IProgress<double> progress, CancellationToken cancellationToken)
  1070. {
  1071. progress.Report(10);
  1072. var allChannels = await GetChannels(service, cancellationToken).ConfigureAwait(false);
  1073. var allChannelsList = allChannels.ToList();
  1074. var list = new List<LiveTvChannel>();
  1075. var numComplete = 0;
  1076. var parentFolder = await GetInternalLiveTvFolder(cancellationToken).ConfigureAwait(false);
  1077. var parentFolderId = parentFolder.Id;
  1078. foreach (var channelInfo in allChannelsList)
  1079. {
  1080. cancellationToken.ThrowIfCancellationRequested();
  1081. try
  1082. {
  1083. var item = await GetChannel(channelInfo.Item2, channelInfo.Item1, parentFolderId, cancellationToken).ConfigureAwait(false);
  1084. list.Add(item);
  1085. }
  1086. catch (OperationCanceledException)
  1087. {
  1088. throw;
  1089. }
  1090. catch (Exception ex)
  1091. {
  1092. _logger.ErrorException("Error getting channel information for {0}", ex, channelInfo.Item2.Name);
  1093. }
  1094. numComplete++;
  1095. double percent = numComplete;
  1096. percent /= allChannelsList.Count;
  1097. progress.Report(5 * percent + 10);
  1098. }
  1099. progress.Report(15);
  1100. numComplete = 0;
  1101. var programs = new List<Guid>();
  1102. var channels = new List<Guid>();
  1103. var guideDays = GetGuideDays();
  1104. _logger.Info("Refreshing guide with {0} days of guide data", guideDays);
  1105. cancellationToken.ThrowIfCancellationRequested();
  1106. foreach (var currentChannel in list)
  1107. {
  1108. channels.Add(currentChannel.Id);
  1109. cancellationToken.ThrowIfCancellationRequested();
  1110. try
  1111. {
  1112. var start = DateTime.UtcNow.AddHours(-1);
  1113. var end = start.AddDays(guideDays);
  1114. var isMovie = false;
  1115. var isSports = false;
  1116. var isNews = false;
  1117. var isKids = false;
  1118. var iSSeries = false;
  1119. var channelPrograms = (await service.GetProgramsAsync(GetItemExternalId(currentChannel), start, end, cancellationToken).ConfigureAwait(false)).ToList();
  1120. var existingPrograms = _libraryManager.GetItemList(new InternalItemsQuery
  1121. {
  1122. IncludeItemTypes = new string[] { typeof(LiveTvProgram).Name },
  1123. ChannelIds = new string[] { currentChannel.Id.ToString("N") },
  1124. DtoOptions = new DtoOptions(true)
  1125. }).Cast<LiveTvProgram>().ToDictionary(i => i.Id);
  1126. var newPrograms = new List<LiveTvProgram>();
  1127. var updatedPrograms = new List<LiveTvProgram>();
  1128. foreach (var program in channelPrograms)
  1129. {
  1130. var programTuple = GetProgram(program, existingPrograms, currentChannel, currentChannel.ChannelType, service.Name, cancellationToken);
  1131. var programItem = programTuple.Item1;
  1132. if (programTuple.Item2)
  1133. {
  1134. newPrograms.Add(programItem);
  1135. }
  1136. else if (programTuple.Item3)
  1137. {
  1138. updatedPrograms.Add(programItem);
  1139. }
  1140. programs.Add(programItem.Id);
  1141. if (program.IsMovie)
  1142. {
  1143. isMovie = true;
  1144. }
  1145. if (program.IsSeries)
  1146. {
  1147. iSSeries = true;
  1148. }
  1149. if (program.IsSports)
  1150. {
  1151. isSports = true;
  1152. }
  1153. if (program.IsNews)
  1154. {
  1155. isNews = true;
  1156. }
  1157. if (program.IsKids)
  1158. {
  1159. isKids = true;
  1160. }
  1161. }
  1162. _logger.Debug("Channel {0} has {1} new programs and {2} updated programs", currentChannel.Name, newPrograms.Count, updatedPrograms.Count);
  1163. if (newPrograms.Count > 0)
  1164. {
  1165. await _libraryManager.CreateItems(newPrograms, cancellationToken).ConfigureAwait(false);
  1166. }
  1167. // TODO: Do this in bulk
  1168. foreach (var program in updatedPrograms)
  1169. {
  1170. await _libraryManager.UpdateItem(program, ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
  1171. }
  1172. currentChannel.IsMovie = isMovie;
  1173. currentChannel.IsNews = isNews;
  1174. currentChannel.IsSports = isSports;
  1175. currentChannel.IsKids = isKids;
  1176. currentChannel.IsSeries = iSSeries;
  1177. await currentChannel.UpdateToRepository(ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
  1178. }
  1179. catch (OperationCanceledException)
  1180. {
  1181. throw;
  1182. }
  1183. catch (Exception ex)
  1184. {
  1185. _logger.ErrorException("Error getting programs for channel {0}", ex, currentChannel.Name);
  1186. }
  1187. numComplete++;
  1188. double percent = numComplete;
  1189. percent /= allChannelsList.Count;
  1190. progress.Report(85 * percent + 15);
  1191. }
  1192. progress.Report(100);
  1193. return new Tuple<List<Guid>, List<Guid>>(channels, programs);
  1194. }
  1195. private async Task CleanDatabaseInternal(Guid[] currentIdList, string[] validTypes, IProgress<double> progress, CancellationToken cancellationToken)
  1196. {
  1197. var list = _itemRepo.GetItemIdsList(new InternalItemsQuery
  1198. {
  1199. IncludeItemTypes = validTypes,
  1200. DtoOptions = new DtoOptions(false)
  1201. });
  1202. var numComplete = 0;
  1203. foreach (var itemId in list)
  1204. {
  1205. cancellationToken.ThrowIfCancellationRequested();
  1206. if (itemId == Guid.Empty)
  1207. {
  1208. // Somehow some invalid data got into the db. It probably predates the boundary checking
  1209. continue;
  1210. }
  1211. if (!currentIdList.Contains(itemId))
  1212. {
  1213. var item = _libraryManager.GetItemById(itemId);
  1214. if (item != null)
  1215. {
  1216. await _libraryManager.DeleteItem(item, new DeleteOptions
  1217. {
  1218. DeleteFileLocation = false
  1219. }).ConfigureAwait(false);
  1220. }
  1221. }
  1222. numComplete++;
  1223. double percent = numComplete;
  1224. percent /= list.Count;
  1225. progress.Report(100 * percent);
  1226. }
  1227. }
  1228. private const int MaxGuideDays = 14;
  1229. private double GetGuideDays()
  1230. {
  1231. var config = GetConfiguration();
  1232. if (config.GuideDays.HasValue)
  1233. {
  1234. return Math.Max(1, Math.Min(config.GuideDays.Value, MaxGuideDays));
  1235. }
  1236. return 7;
  1237. }
  1238. private async Task<IEnumerable<Tuple<string, ChannelInfo>>> GetChannels(ILiveTvService service, CancellationToken cancellationToken)
  1239. {
  1240. var channels = await service.GetChannelsAsync(cancellationToken).ConfigureAwait(false);
  1241. return channels.Select(i => new Tuple<string, ChannelInfo>(service.Name, i));
  1242. }
  1243. private DateTime _lastRecordingRefreshTime;
  1244. private async Task RefreshRecordings(Guid internalLiveTvFolderId, CancellationToken cancellationToken)
  1245. {
  1246. const int cacheMinutes = 2;
  1247. await _refreshRecordingsLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  1248. try
  1249. {
  1250. if ((DateTime.UtcNow - _lastRecordingRefreshTime).TotalMinutes < cacheMinutes)
  1251. {
  1252. return;
  1253. }
  1254. var tasks = _services.Select(async i =>
  1255. {
  1256. try
  1257. {
  1258. var recs = await i.GetRecordingsAsync(cancellationToken).ConfigureAwait(false);
  1259. return recs.Select(r => new Tuple<RecordingInfo, ILiveTvService>(r, i));
  1260. }
  1261. catch (Exception ex)
  1262. {
  1263. _logger.ErrorException("Error getting recordings", ex);
  1264. return new List<Tuple<RecordingInfo, ILiveTvService>>();
  1265. }
  1266. });
  1267. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  1268. var recordingTasks = results.SelectMany(i => i.ToList()).Select(i => CreateRecordingRecord(i.Item1, i.Item2.Name, internalLiveTvFolderId, cancellationToken));
  1269. var idList = await Task.WhenAll(recordingTasks).ConfigureAwait(false);
  1270. await CleanDatabaseInternal(idList, new[] { typeof(LiveTvVideoRecording).Name, typeof(LiveTvAudioRecording).Name }, new SimpleProgress<double>(), cancellationToken).ConfigureAwait(false);
  1271. _lastRecordingRefreshTime = DateTime.UtcNow;
  1272. }
  1273. finally
  1274. {
  1275. _refreshRecordingsLock.Release();
  1276. }
  1277. }
  1278. private QueryResult<BaseItem> GetEmbyRecordings(RecordingQuery query, DtoOptions dtoOptions, Guid internalLiveTvFolderId, User user)
  1279. {
  1280. if (user == null)
  1281. {
  1282. return new QueryResult<BaseItem>();
  1283. }
  1284. if ((query.IsInProgress ?? false))
  1285. {
  1286. return new QueryResult<BaseItem>();
  1287. }
  1288. var folderIds = EmbyTV.EmbyTV.Current.GetRecordingFolders()
  1289. .SelectMany(i => i.Locations)
  1290. .Distinct(StringComparer.OrdinalIgnoreCase)
  1291. .Select(i => _libraryManager.FindByPath(i, true))
  1292. .Where(i => i != null)
  1293. .Where(i => i.IsVisibleStandalone(user))
  1294. .Select(i => i.Id)
  1295. .ToList();
  1296. var excludeItemTypes = new List<string>();
  1297. if (!query.IsInProgress.HasValue)
  1298. {
  1299. folderIds.Add(internalLiveTvFolderId);
  1300. excludeItemTypes.Add(typeof(LiveTvChannel).Name);
  1301. excludeItemTypes.Add(typeof(LiveTvProgram).Name);
  1302. }
  1303. if (folderIds.Count == 0)
  1304. {
  1305. return new QueryResult<BaseItem>();
  1306. }
  1307. var includeItemTypes = new List<string>();
  1308. var genres = new List<string>();
  1309. if (query.IsMovie.HasValue)
  1310. {
  1311. if (query.IsMovie.Value)
  1312. {
  1313. includeItemTypes.Add(typeof(Movie).Name);
  1314. }
  1315. else
  1316. {
  1317. excludeItemTypes.Add(typeof(Movie).Name);
  1318. }
  1319. }
  1320. if (query.IsSeries.HasValue)
  1321. {
  1322. if (query.IsSeries.Value)
  1323. {
  1324. includeItemTypes.Add(typeof(Episode).Name);
  1325. }
  1326. else
  1327. {
  1328. excludeItemTypes.Add(typeof(Episode).Name);
  1329. }
  1330. }
  1331. if (query.IsSports.HasValue)
  1332. {
  1333. if (query.IsSports.Value)
  1334. {
  1335. genres.Add("Sports");
  1336. }
  1337. }
  1338. if (query.IsKids.HasValue)
  1339. {
  1340. if (query.IsKids.Value)
  1341. {
  1342. genres.Add("Kids");
  1343. genres.Add("Children");
  1344. genres.Add("Family");
  1345. }
  1346. }
  1347. return _libraryManager.GetItemsResult(new InternalItemsQuery(user)
  1348. {
  1349. MediaTypes = new[] { MediaType.Video },
  1350. Recursive = true,
  1351. AncestorIds = folderIds.Select(i => i.ToString("N")).ToArray(folderIds.Count),
  1352. IsFolder = false,
  1353. IsVirtualItem = false,
  1354. Limit = query.Limit,
  1355. StartIndex = query.StartIndex,
  1356. SortBy = new[] { ItemSortBy.DateCreated },
  1357. SortOrder = SortOrder.Descending,
  1358. EnableTotalRecordCount = query.EnableTotalRecordCount,
  1359. IncludeItemTypes = includeItemTypes.ToArray(includeItemTypes.Count),
  1360. ExcludeItemTypes = excludeItemTypes.ToArray(excludeItemTypes.Count),
  1361. Genres = genres.ToArray(genres.Count),
  1362. DtoOptions = dtoOptions
  1363. });
  1364. }
  1365. public async Task<QueryResult<BaseItemDto>> GetRecordingSeries(RecordingQuery query, DtoOptions options, CancellationToken cancellationToken)
  1366. {
  1367. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  1368. if (user != null && !IsLiveTvEnabled(user))
  1369. {
  1370. return new QueryResult<BaseItemDto>();
  1371. }
  1372. if (_services.Count > 1)
  1373. {
  1374. return new QueryResult<BaseItemDto>();
  1375. }
  1376. if (user == null || (query.IsInProgress ?? false))
  1377. {
  1378. return new QueryResult<BaseItemDto>();
  1379. }
  1380. var folders = EmbyTV.EmbyTV.Current.GetRecordingFolders()
  1381. .SelectMany(i => i.Locations)
  1382. .Distinct(StringComparer.OrdinalIgnoreCase)
  1383. .Select(i => _libraryManager.FindByPath(i, true))
  1384. .Where(i => i != null)
  1385. .Where(i => i.IsVisibleStandalone(user))
  1386. .ToList();
  1387. if (folders.Count == 0)
  1388. {
  1389. return new QueryResult<BaseItemDto>();
  1390. }
  1391. var includeItemTypes = new List<string>();
  1392. var excludeItemTypes = new List<string>();
  1393. includeItemTypes.Add(typeof(Series).Name);
  1394. RemoveFields(options);
  1395. var internalResult = _libraryManager.GetItemsResult(new InternalItemsQuery(user)
  1396. {
  1397. Recursive = true,
  1398. AncestorIds = folders.Select(i => i.Id.ToString("N")).ToArray(folders.Count),
  1399. Limit = query.Limit,
  1400. SortBy = new[] { ItemSortBy.DateCreated },
  1401. SortOrder = SortOrder.Descending,
  1402. EnableTotalRecordCount = query.EnableTotalRecordCount,
  1403. IncludeItemTypes = includeItemTypes.ToArray(includeItemTypes.Count),
  1404. ExcludeItemTypes = excludeItemTypes.ToArray(excludeItemTypes.Count),
  1405. DtoOptions = options
  1406. });
  1407. var returnArray = (await _dtoService.GetBaseItemDtos(internalResult.Items, options, user)
  1408. .ConfigureAwait(false));
  1409. return new QueryResult<BaseItemDto>
  1410. {
  1411. Items = returnArray,
  1412. TotalRecordCount = internalResult.TotalRecordCount
  1413. };
  1414. }
  1415. public async Task<QueryResult<BaseItem>> GetInternalRecordings(RecordingQuery query, DtoOptions options, CancellationToken cancellationToken)
  1416. {
  1417. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  1418. if (user != null && !IsLiveTvEnabled(user))
  1419. {
  1420. return new QueryResult<BaseItem>();
  1421. }
  1422. var folder = await GetInternalLiveTvFolder(cancellationToken).ConfigureAwait(false);
  1423. if (_services.Count == 1 && (!query.IsInProgress.HasValue || !query.IsInProgress.Value) && (!query.IsLibraryItem.HasValue || query.IsLibraryItem.Value))
  1424. {
  1425. if (!query.IsInProgress.HasValue)
  1426. {
  1427. await RefreshRecordings(folder.Id, cancellationToken).ConfigureAwait(false);
  1428. }
  1429. return GetEmbyRecordings(query, options, folder.Id, user);
  1430. }
  1431. return await GetInternalRecordingsFromServices(query, user, options, folder.Id, cancellationToken).ConfigureAwait(false);
  1432. }
  1433. private async Task<QueryResult<BaseItem>> GetInternalRecordingsFromServices(RecordingQuery query, User user, DtoOptions options, Guid internalLiveTvFolderId, CancellationToken cancellationToken)
  1434. {
  1435. await RefreshRecordings(internalLiveTvFolderId, cancellationToken).ConfigureAwait(false);
  1436. var internalQuery = new InternalItemsQuery(user)
  1437. {
  1438. IncludeItemTypes = new[] { typeof(LiveTvVideoRecording).Name, typeof(LiveTvAudioRecording).Name },
  1439. DtoOptions = options
  1440. };
  1441. if (!string.IsNullOrEmpty(query.ChannelId))
  1442. {
  1443. internalQuery.ChannelIds = new[] { query.ChannelId };
  1444. }
  1445. var queryResult = _libraryManager.GetItemList(internalQuery);
  1446. IEnumerable<ILiveTvRecording> recordings = queryResult.Cast<ILiveTvRecording>();
  1447. if (!string.IsNullOrWhiteSpace(query.Id))
  1448. {
  1449. var guid = new Guid(query.Id);
  1450. recordings = recordings
  1451. .Where(i => i.Id == guid);
  1452. }
  1453. if (!string.IsNullOrWhiteSpace(query.GroupId))
  1454. {
  1455. var guid = new Guid(query.GroupId);
  1456. recordings = recordings.Where(i => GetRecordingGroupIds(i).Contains(guid));
  1457. }
  1458. if (query.IsInProgress.HasValue)
  1459. {
  1460. var val = query.IsInProgress.Value;
  1461. recordings = recordings.Where(i => i.Status == RecordingStatus.InProgress == val);
  1462. }
  1463. if (query.Status.HasValue)
  1464. {
  1465. var val = query.Status.Value;
  1466. recordings = recordings.Where(i => i.Status == val);
  1467. }
  1468. if (query.IsMovie.HasValue)
  1469. {
  1470. var val = query.IsMovie.Value;
  1471. recordings = recordings.Where(i => i.IsMovie == val);
  1472. }
  1473. if (query.IsNews.HasValue)
  1474. {
  1475. var val = query.IsNews.Value;
  1476. recordings = recordings.Where(i => i.IsNews == val);
  1477. }
  1478. if (query.IsSeries.HasValue)
  1479. {
  1480. var val = query.IsSeries.Value;
  1481. recordings = recordings.Where(i => i.IsSeries == val);
  1482. }
  1483. if (query.IsKids.HasValue)
  1484. {
  1485. var val = query.IsKids.Value;
  1486. recordings = recordings.Where(i => i.IsKids == val);
  1487. }
  1488. if (query.IsSports.HasValue)
  1489. {
  1490. var val = query.IsSports.Value;
  1491. recordings = recordings.Where(i => i.IsSports == val);
  1492. }
  1493. if (!string.IsNullOrEmpty(query.SeriesTimerId))
  1494. {
  1495. var guid = new Guid(query.SeriesTimerId);
  1496. recordings = recordings
  1497. .Where(i => _tvDtoService.GetInternalSeriesTimerId(i.ServiceName, i.SeriesTimerId) == guid);
  1498. }
  1499. recordings = recordings.OrderByDescending(i => i.StartDate);
  1500. var entityList = recordings.ToList();
  1501. IEnumerable<ILiveTvRecording> entities = entityList;
  1502. if (query.StartIndex.HasValue)
  1503. {
  1504. entities = entities.Skip(query.StartIndex.Value);
  1505. }
  1506. if (query.Limit.HasValue)
  1507. {
  1508. entities = entities.Take(query.Limit.Value);
  1509. }
  1510. return new QueryResult<BaseItem>
  1511. {
  1512. Items = entities.Cast<BaseItem>().ToArray(),
  1513. TotalRecordCount = entityList.Count
  1514. };
  1515. }
  1516. public async Task AddInfoToProgramDto(List<Tuple<BaseItem, BaseItemDto>> tuples, ItemFields[] fields, User user = null)
  1517. {
  1518. var programTuples = new List<Tuple<BaseItemDto, string, string, string>>();
  1519. var hasChannelImage = fields.Contains(ItemFields.ChannelImage);
  1520. var hasChannelInfo = fields.Contains(ItemFields.ChannelInfo);
  1521. var hasServiceName = fields.Contains(ItemFields.ServiceName);
  1522. foreach (var tuple in tuples)
  1523. {
  1524. var program = (LiveTvProgram)tuple.Item1;
  1525. var dto = tuple.Item2;
  1526. dto.StartDate = program.StartDate;
  1527. dto.EpisodeTitle = program.EpisodeTitle;
  1528. if (program.IsRepeat)
  1529. {
  1530. dto.IsRepeat = program.IsRepeat;
  1531. }
  1532. if (program.IsMovie)
  1533. {
  1534. dto.IsMovie = program.IsMovie;
  1535. }
  1536. if (program.IsSeries)
  1537. {
  1538. dto.IsSeries = program.IsSeries;
  1539. }
  1540. if (program.IsSports)
  1541. {
  1542. dto.IsSports = program.IsSports;
  1543. }
  1544. if (program.IsLive)
  1545. {
  1546. dto.IsLive = program.IsLive;
  1547. }
  1548. if (program.IsNews)
  1549. {
  1550. dto.IsNews = program.IsNews;
  1551. }
  1552. if (program.IsKids)
  1553. {
  1554. dto.IsKids = program.IsKids;
  1555. }
  1556. if (program.IsPremiere)
  1557. {
  1558. dto.IsPremiere = program.IsPremiere;
  1559. }
  1560. if (hasChannelInfo || hasChannelImage)
  1561. {
  1562. var channel = GetInternalChannel(program.ChannelId);
  1563. if (channel != null)
  1564. {
  1565. dto.ChannelName = channel.Name;
  1566. dto.MediaType = channel.MediaType;
  1567. dto.ChannelNumber = channel.Number;
  1568. if (hasChannelImage && channel.HasImage(ImageType.Primary))
  1569. {
  1570. dto.ChannelPrimaryImageTag = _tvDtoService.GetImageTag(channel);
  1571. }
  1572. }
  1573. }
  1574. var serviceName = program.ServiceName;
  1575. if (hasServiceName)
  1576. {
  1577. dto.ServiceName = serviceName;
  1578. }
  1579. var externalSeriesId = program.ExternalSeriesId;
  1580. programTuples.Add(new Tuple<BaseItemDto, string, string, string>(dto, serviceName, GetItemExternalId(program), externalSeriesId));
  1581. }
  1582. await AddRecordingInfo(programTuples, CancellationToken.None).ConfigureAwait(false);
  1583. }
  1584. public void AddInfoToRecordingDto(BaseItem item, BaseItemDto dto, User user = null)
  1585. {
  1586. var recording = (ILiveTvRecording)item;
  1587. var service = GetService(recording);
  1588. var channel = string.IsNullOrWhiteSpace(recording.ChannelId) ? null : GetInternalChannel(recording.ChannelId);
  1589. var info = recording;
  1590. dto.SeriesTimerId = string.IsNullOrEmpty(info.SeriesTimerId)
  1591. ? null
  1592. : _tvDtoService.GetInternalSeriesTimerId(service.Name, info.SeriesTimerId).ToString("N");
  1593. dto.TimerId = string.IsNullOrEmpty(info.TimerId)
  1594. ? null
  1595. : _tvDtoService.GetInternalTimerId(service.Name, info.TimerId).ToString("N");
  1596. dto.StartDate = info.StartDate;
  1597. dto.Status = info.Status.ToString();
  1598. dto.IsRepeat = info.IsRepeat;
  1599. dto.EpisodeTitle = info.EpisodeTitle;
  1600. dto.IsMovie = info.IsMovie;
  1601. dto.IsSeries = info.IsSeries;
  1602. dto.IsSports = info.IsSports;
  1603. dto.IsLive = info.IsLive;
  1604. dto.IsNews = info.IsNews;
  1605. dto.IsKids = info.IsKids;
  1606. dto.IsPremiere = info.IsPremiere;
  1607. dto.CanDelete = user == null
  1608. ? recording.CanDelete()
  1609. : recording.CanDelete(user);
  1610. if (dto.MediaSources == null)
  1611. {
  1612. dto.MediaSources = recording.GetMediaSources(true);
  1613. }
  1614. if (dto.MediaStreams == null)
  1615. {
  1616. dto.MediaStreams = dto.MediaSources.SelectMany(i => i.MediaStreams).ToArray();
  1617. }
  1618. if (info.Status == RecordingStatus.InProgress && info.EndDate.HasValue)
  1619. {
  1620. var now = DateTime.UtcNow.Ticks;
  1621. var start = info.StartDate.Ticks;
  1622. var end = info.EndDate.Value.Ticks;
  1623. var pct = now - start;
  1624. pct /= end;
  1625. pct *= 100;
  1626. dto.CompletionPercentage = pct;
  1627. }
  1628. if (channel != null)
  1629. {
  1630. dto.ChannelName = channel.Name;
  1631. if (channel.HasImage(ImageType.Primary))
  1632. {
  1633. dto.ChannelPrimaryImageTag = _tvDtoService.GetImageTag(channel);
  1634. }
  1635. }
  1636. }
  1637. public async Task<QueryResult<BaseItemDto>> GetRecordings(RecordingQuery query, DtoOptions options, CancellationToken cancellationToken)
  1638. {
  1639. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  1640. RemoveFields(options);
  1641. var internalResult = await GetInternalRecordings(query, options, cancellationToken).ConfigureAwait(false);
  1642. var returnArray = (await _dtoService.GetBaseItemDtos(internalResult.Items, options, user)
  1643. .ConfigureAwait(false));
  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(returnList.Count);
  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. }) : 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.ToArray();
  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. groups.AddRange(series.OrderByString(i => i.Key).Select(i => new BaseItemDto
  2178. {
  2179. Name = i.Key,
  2180. RecordingCount = i.Count()
  2181. }));
  2182. groups.Add(new BaseItemDto
  2183. {
  2184. Name = "Kids",
  2185. RecordingCount = recordings.Count(i => i.IsKids)
  2186. });
  2187. groups.Add(new BaseItemDto
  2188. {
  2189. Name = "Movies",
  2190. RecordingCount = recordings.Count(i => i.IsMovie)
  2191. });
  2192. groups.Add(new BaseItemDto
  2193. {
  2194. Name = "News",
  2195. RecordingCount = recordings.Count(i => i.IsNews)
  2196. });
  2197. groups.Add(new BaseItemDto
  2198. {
  2199. Name = "Sports",
  2200. RecordingCount = recordings.Count(i => i.IsSports)
  2201. });
  2202. groups.Add(new BaseItemDto
  2203. {
  2204. Name = "Others",
  2205. RecordingCount = recordings.Count(i => !i.IsSports && !i.IsNews && !i.IsMovie && !i.IsKids && !i.IsSeries)
  2206. });
  2207. groups = groups
  2208. .Where(i => i.RecordingCount > 0)
  2209. .ToList();
  2210. foreach (var group in groups)
  2211. {
  2212. group.Id = group.Name.ToLower().GetMD5().ToString("N");
  2213. }
  2214. return new QueryResult<BaseItemDto>
  2215. {
  2216. Items = groups.ToArray(groups.Count),
  2217. TotalRecordCount = groups.Count
  2218. };
  2219. }
  2220. public async Task CloseLiveStream(string id)
  2221. {
  2222. var parts = id.Split(new[] { '_' }, 2);
  2223. var service = _services.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N"), parts[0], StringComparison.OrdinalIgnoreCase));
  2224. if (service == null)
  2225. {
  2226. throw new ArgumentException("Service not found.");
  2227. }
  2228. id = parts[1];
  2229. _logger.Info("Closing live stream from {0}, stream Id: {1}", service.Name, id);
  2230. await service.CloseLiveStream(id, CancellationToken.None).ConfigureAwait(false);
  2231. }
  2232. public GuideInfo GetGuideInfo()
  2233. {
  2234. var startDate = DateTime.UtcNow;
  2235. var endDate = startDate.AddDays(GetGuideDays());
  2236. return new GuideInfo
  2237. {
  2238. StartDate = startDate,
  2239. EndDate = endDate
  2240. };
  2241. }
  2242. /// <summary>
  2243. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  2244. /// </summary>
  2245. public void Dispose()
  2246. {
  2247. Dispose(true);
  2248. }
  2249. private bool _isDisposed = false;
  2250. /// <summary>
  2251. /// Releases unmanaged and - optionally - managed resources.
  2252. /// </summary>
  2253. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  2254. protected virtual void Dispose(bool dispose)
  2255. {
  2256. if (dispose)
  2257. {
  2258. _isDisposed = true;
  2259. }
  2260. }
  2261. private async Task<LiveTvServiceInfo[]> GetServiceInfos(CancellationToken cancellationToken)
  2262. {
  2263. var tasks = Services.Select(i => GetServiceInfo(i, cancellationToken));
  2264. return await Task.WhenAll(tasks).ConfigureAwait(false);
  2265. }
  2266. private async Task<LiveTvServiceInfo> GetServiceInfo(ILiveTvService service, CancellationToken cancellationToken)
  2267. {
  2268. var info = new LiveTvServiceInfo
  2269. {
  2270. Name = service.Name
  2271. };
  2272. var tunerIdPrefix = service.GetType().FullName.GetMD5().ToString("N") + "_";
  2273. try
  2274. {
  2275. var statusInfo = await service.GetStatusInfoAsync(cancellationToken).ConfigureAwait(false);
  2276. info.Status = statusInfo.Status;
  2277. info.StatusMessage = statusInfo.StatusMessage;
  2278. info.Version = statusInfo.Version;
  2279. info.HasUpdateAvailable = statusInfo.HasUpdateAvailable;
  2280. info.HomePageUrl = service.HomePageUrl;
  2281. info.IsVisible = statusInfo.IsVisible;
  2282. info.Tuners = statusInfo.Tuners.Select(i =>
  2283. {
  2284. string channelName = null;
  2285. if (!string.IsNullOrEmpty(i.ChannelId))
  2286. {
  2287. var internalChannelId = _tvDtoService.GetInternalChannelId(service.Name, i.ChannelId);
  2288. var channel = GetInternalChannel(internalChannelId);
  2289. channelName = channel == null ? null : channel.Name;
  2290. }
  2291. var dto = _tvDtoService.GetTunerInfoDto(service.Name, i, channelName);
  2292. dto.Id = tunerIdPrefix + dto.Id;
  2293. return dto;
  2294. }).ToArray();
  2295. }
  2296. catch (Exception ex)
  2297. {
  2298. _logger.ErrorException("Error getting service status info from {0}", ex, service.Name ?? string.Empty);
  2299. info.Status = LiveTvServiceStatus.Unavailable;
  2300. info.StatusMessage = ex.Message;
  2301. }
  2302. return info;
  2303. }
  2304. public async Task<LiveTvInfo> GetLiveTvInfo(CancellationToken cancellationToken)
  2305. {
  2306. var services = await GetServiceInfos(CancellationToken.None).ConfigureAwait(false);
  2307. var info = new LiveTvInfo
  2308. {
  2309. Services = services,
  2310. IsEnabled = services.Length > 0
  2311. };
  2312. info.EnabledUsers = _userManager.Users
  2313. .Where(IsLiveTvEnabled)
  2314. .Select(i => i.Id.ToString("N"))
  2315. .ToArray();
  2316. return info;
  2317. }
  2318. private bool IsLiveTvEnabled(User user)
  2319. {
  2320. return user.Policy.EnableLiveTvAccess && (Services.Count > 1 || GetConfiguration().TunerHosts.Length > 0);
  2321. }
  2322. public IEnumerable<User> GetEnabledUsers()
  2323. {
  2324. return _userManager.Users
  2325. .Where(IsLiveTvEnabled);
  2326. }
  2327. /// <summary>
  2328. /// Resets the tuner.
  2329. /// </summary>
  2330. /// <param name="id">The identifier.</param>
  2331. /// <param name="cancellationToken">The cancellation token.</param>
  2332. /// <returns>Task.</returns>
  2333. public Task ResetTuner(string id, CancellationToken cancellationToken)
  2334. {
  2335. var parts = id.Split(new[] { '_' }, 2);
  2336. var service = _services.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N"), parts[0], StringComparison.OrdinalIgnoreCase));
  2337. if (service == null)
  2338. {
  2339. throw new ArgumentException("Service not found.");
  2340. }
  2341. return service.ResetTuner(parts[1], cancellationToken);
  2342. }
  2343. public async Task<BaseItemDto> GetLiveTvFolder(string userId, CancellationToken cancellationToken)
  2344. {
  2345. var user = string.IsNullOrEmpty(userId) ? null : _userManager.GetUserById(userId);
  2346. var folder = await GetInternalLiveTvFolder(cancellationToken).ConfigureAwait(false);
  2347. return _dtoService.GetBaseItemDto(folder, new DtoOptions(), user);
  2348. }
  2349. private void RemoveFields(DtoOptions options)
  2350. {
  2351. var fields = options.Fields.ToList();
  2352. fields.Remove(ItemFields.CanDelete);
  2353. fields.Remove(ItemFields.CanDownload);
  2354. fields.Remove(ItemFields.DisplayPreferencesId);
  2355. fields.Remove(ItemFields.Etag);
  2356. options.Fields = fields.ToArray(fields.Count);
  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 list = config.TunerHosts.ToList();
  2378. var index = list.FindIndex(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase));
  2379. if (index == -1 || string.IsNullOrWhiteSpace(info.Id))
  2380. {
  2381. info.Id = Guid.NewGuid().ToString("N");
  2382. list.Add(info);
  2383. config.TunerHosts = list.ToArray(list.Count);
  2384. }
  2385. else
  2386. {
  2387. config.TunerHosts[index] = info;
  2388. }
  2389. _config.SaveConfiguration("livetv", config);
  2390. if (dataSourceChanged)
  2391. {
  2392. _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
  2393. }
  2394. return info;
  2395. }
  2396. public async Task<ListingsProviderInfo> SaveListingProvider(ListingsProviderInfo info, bool validateLogin, bool validateListings)
  2397. {
  2398. info = _jsonSerializer.DeserializeFromString<ListingsProviderInfo>(_jsonSerializer.SerializeToString(info));
  2399. var provider = _listingProviders.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  2400. if (provider == null)
  2401. {
  2402. throw new ResourceNotFoundException();
  2403. }
  2404. await provider.Validate(info, validateLogin, validateListings).ConfigureAwait(false);
  2405. var config = GetConfiguration();
  2406. var list = config.ListingProviders.ToList();
  2407. var index = list.FindIndex(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase));
  2408. if (index == -1 || string.IsNullOrWhiteSpace(info.Id))
  2409. {
  2410. info.Id = Guid.NewGuid().ToString("N");
  2411. list.Add(info);
  2412. config.ListingProviders = list.ToArray(list.Count);
  2413. info.EnableNewProgramIds = true;
  2414. }
  2415. else
  2416. {
  2417. config.ListingProviders[index] = info;
  2418. }
  2419. _config.SaveConfiguration("livetv", config);
  2420. _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
  2421. return info;
  2422. }
  2423. public void DeleteListingsProvider(string id)
  2424. {
  2425. var config = GetConfiguration();
  2426. config.ListingProviders = config.ListingProviders.Where(i => !string.Equals(id, i.Id, StringComparison.OrdinalIgnoreCase)).ToArray();
  2427. _config.SaveConfiguration("livetv", config);
  2428. _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
  2429. }
  2430. public async Task<TunerChannelMapping> SetChannelMapping(string providerId, string tunerChannelId, string providerChannelId)
  2431. {
  2432. var config = GetConfiguration();
  2433. var listingsProviderInfo = config.ListingProviders.First(i => string.Equals(providerId, i.Id, StringComparison.OrdinalIgnoreCase));
  2434. listingsProviderInfo.ChannelMappings = listingsProviderInfo.ChannelMappings.Where(i => !string.Equals(i.Name, tunerChannelId, StringComparison.OrdinalIgnoreCase)).ToArray();
  2435. if (!string.Equals(tunerChannelId, providerChannelId, StringComparison.OrdinalIgnoreCase))
  2436. {
  2437. var list = listingsProviderInfo.ChannelMappings.ToList();
  2438. list.Add(new NameValuePair
  2439. {
  2440. Name = tunerChannelId,
  2441. Value = providerChannelId
  2442. });
  2443. listingsProviderInfo.ChannelMappings = list.ToArray(list.Count);
  2444. }
  2445. _config.SaveConfiguration("livetv", config);
  2446. var tunerChannels = await GetChannelsForListingsProvider(providerId, CancellationToken.None)
  2447. .ConfigureAwait(false);
  2448. var providerChannels = await GetChannelsFromListingsProviderData(providerId, CancellationToken.None)
  2449. .ConfigureAwait(false);
  2450. var mappings = listingsProviderInfo.ChannelMappings;
  2451. var tunerChannelMappings =
  2452. tunerChannels.Select(i => GetTunerChannelMapping(i, mappings, providerChannels)).ToList();
  2453. _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
  2454. return tunerChannelMappings.First(i => string.Equals(i.Id, tunerChannelId, StringComparison.OrdinalIgnoreCase));
  2455. }
  2456. public TunerChannelMapping GetTunerChannelMapping(ChannelInfo tunerChannel, NameValuePair[] mappings, List<ChannelInfo> epgChannels)
  2457. {
  2458. var result = new TunerChannelMapping
  2459. {
  2460. Name = tunerChannel.Name,
  2461. Id = tunerChannel.Id
  2462. };
  2463. if (!string.IsNullOrWhiteSpace(tunerChannel.Number))
  2464. {
  2465. result.Name = tunerChannel.Number + " " + result.Name;
  2466. }
  2467. var providerChannel = EmbyTV.EmbyTV.Current.GetEpgChannelFromTunerChannel(mappings, tunerChannel, epgChannels);
  2468. if (providerChannel != null)
  2469. {
  2470. result.ProviderChannelName = providerChannel.Name;
  2471. result.ProviderChannelId = providerChannel.Id;
  2472. }
  2473. return result;
  2474. }
  2475. public Task<List<NameIdPair>> GetLineups(string providerType, string providerId, string country, string location)
  2476. {
  2477. var config = GetConfiguration();
  2478. if (string.IsNullOrWhiteSpace(providerId))
  2479. {
  2480. var provider = _listingProviders.FirstOrDefault(i => string.Equals(providerType, i.Type, StringComparison.OrdinalIgnoreCase));
  2481. if (provider == null)
  2482. {
  2483. throw new ResourceNotFoundException();
  2484. }
  2485. return provider.GetLineups(null, country, location);
  2486. }
  2487. else
  2488. {
  2489. var info = config.ListingProviders.FirstOrDefault(i => string.Equals(i.Id, providerId, StringComparison.OrdinalIgnoreCase));
  2490. var provider = _listingProviders.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  2491. if (provider == null)
  2492. {
  2493. throw new ResourceNotFoundException();
  2494. }
  2495. return provider.GetLineups(info, country, location);
  2496. }
  2497. }
  2498. public Task<MBRegistrationRecord> GetRegistrationInfo(string feature)
  2499. {
  2500. if (string.Equals(feature, "seriesrecordings", StringComparison.OrdinalIgnoreCase))
  2501. {
  2502. feature = "embytvseriesrecordings";
  2503. }
  2504. if (string.Equals(feature, "dvr-l", StringComparison.OrdinalIgnoreCase))
  2505. {
  2506. var config = GetConfiguration();
  2507. if (config.TunerHosts.Length > 0 &&
  2508. config.ListingProviders.Count(i => (i.EnableAllTuners || i.EnabledTuners.Length > 0) && string.Equals(i.Type, SchedulesDirect.TypeName, StringComparison.OrdinalIgnoreCase)) > 0)
  2509. {
  2510. return Task.FromResult(new MBRegistrationRecord
  2511. {
  2512. IsRegistered = true,
  2513. IsValid = true
  2514. });
  2515. }
  2516. }
  2517. return _security.GetRegistrationStatus(feature);
  2518. }
  2519. public Task<List<ChannelInfo>> GetChannelsForListingsProvider(string id, CancellationToken cancellationToken)
  2520. {
  2521. var info = GetConfiguration().ListingProviders.First(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
  2522. return EmbyTV.EmbyTV.Current.GetChannelsForListingsProvider(info, cancellationToken);
  2523. }
  2524. public Task<List<ChannelInfo>> GetChannelsFromListingsProviderData(string id, CancellationToken cancellationToken)
  2525. {
  2526. var info = GetConfiguration().ListingProviders.First(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
  2527. var provider = _listingProviders.First(i => string.Equals(i.Type, info.Type, StringComparison.OrdinalIgnoreCase));
  2528. return provider.GetChannels(info, cancellationToken);
  2529. }
  2530. }
  2531. }