LiveTvManager.cs 90 KB

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