LiveTvManager.cs 116 KB

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