LiveTvManager.cs 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046
  1. using MediaBrowser.Common;
  2. using MediaBrowser.Common.Configuration;
  3. using MediaBrowser.Common.Extensions;
  4. using MediaBrowser.Common.Progress;
  5. using MediaBrowser.Common.ScheduledTasks;
  6. using MediaBrowser.Controller.Configuration;
  7. using MediaBrowser.Controller.Drawing;
  8. using MediaBrowser.Controller.Dto;
  9. using MediaBrowser.Controller.Entities;
  10. using MediaBrowser.Controller.Library;
  11. using MediaBrowser.Controller.LiveTv;
  12. using MediaBrowser.Controller.Localization;
  13. using MediaBrowser.Controller.Persistence;
  14. using MediaBrowser.Controller.Providers;
  15. using MediaBrowser.Controller.Sorting;
  16. using MediaBrowser.Model.Dto;
  17. using MediaBrowser.Model.Entities;
  18. using MediaBrowser.Model.LiveTv;
  19. using MediaBrowser.Model.Logging;
  20. using MediaBrowser.Model.Querying;
  21. using MediaBrowser.Model.Serialization;
  22. using System;
  23. using System.Collections.Concurrent;
  24. using System.Collections.Generic;
  25. using System.Linq;
  26. using System.Threading;
  27. using System.Threading.Tasks;
  28. namespace MediaBrowser.Server.Implementations.LiveTv
  29. {
  30. /// <summary>
  31. /// Class LiveTvManager
  32. /// </summary>
  33. public class LiveTvManager : ILiveTvManager, IDisposable
  34. {
  35. private readonly IServerConfigurationManager _config;
  36. private readonly ILogger _logger;
  37. private readonly IItemRepository _itemRepo;
  38. private readonly IUserManager _userManager;
  39. private readonly IUserDataManager _userDataManager;
  40. private readonly ILibraryManager _libraryManager;
  41. private readonly ITaskManager _taskManager;
  42. private readonly IJsonSerializer _jsonSerializer;
  43. private readonly IProviderManager _providerManager;
  44. private readonly IDtoService _dtoService;
  45. private readonly ILocalizationManager _localization;
  46. private readonly LiveTvDtoService _tvDtoService;
  47. private readonly List<ILiveTvService> _services = new List<ILiveTvService>();
  48. private readonly ConcurrentDictionary<string, LiveStreamData> _openStreams =
  49. new ConcurrentDictionary<string, LiveStreamData>();
  50. private List<Guid> _channelIdList = new List<Guid>();
  51. private Dictionary<Guid, LiveTvProgram> _programs;
  52. private readonly ConcurrentDictionary<Guid, bool> _refreshedPrograms = new ConcurrentDictionary<Guid, bool>();
  53. 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)
  54. {
  55. _config = config;
  56. _logger = logger;
  57. _itemRepo = itemRepo;
  58. _userManager = userManager;
  59. _libraryManager = libraryManager;
  60. _taskManager = taskManager;
  61. _localization = localization;
  62. _jsonSerializer = jsonSerializer;
  63. _providerManager = providerManager;
  64. _dtoService = dtoService;
  65. _userDataManager = userDataManager;
  66. _tvDtoService = new LiveTvDtoService(dtoService, userDataManager, imageProcessor, logger, appHost);
  67. }
  68. /// <summary>
  69. /// Gets the services.
  70. /// </summary>
  71. /// <value>The services.</value>
  72. public IReadOnlyList<ILiveTvService> Services
  73. {
  74. get { return _services; }
  75. }
  76. private LiveTvOptions GetConfiguration()
  77. {
  78. return _config.GetConfiguration<LiveTvOptions>("livetv");
  79. }
  80. /// <summary>
  81. /// Adds the parts.
  82. /// </summary>
  83. /// <param name="services">The services.</param>
  84. public void AddParts(IEnumerable<ILiveTvService> services)
  85. {
  86. _services.AddRange(services);
  87. foreach (var service in _services)
  88. {
  89. service.DataSourceChanged += service_DataSourceChanged;
  90. }
  91. }
  92. void service_DataSourceChanged(object sender, EventArgs e)
  93. {
  94. _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
  95. }
  96. private readonly object _programsDataLock = new object();
  97. private Dictionary<Guid, LiveTvProgram> GetProgramsDictionary()
  98. {
  99. if (_programs == null)
  100. {
  101. lock (_programsDataLock)
  102. {
  103. if (_programs == null)
  104. {
  105. var dict = new Dictionary<Guid, LiveTvProgram>();
  106. foreach (var item in _itemRepo.GetItemsOfType(typeof (LiveTvProgram))
  107. .Cast<LiveTvProgram>()
  108. .ToList())
  109. {
  110. dict[item.Id] = item;
  111. }
  112. _programs = dict;
  113. }
  114. }
  115. }
  116. return _programs;
  117. }
  118. private IEnumerable<LiveTvProgram> GetPrograms()
  119. {
  120. return GetProgramsDictionary().Values;
  121. }
  122. public async Task<QueryResult<LiveTvChannel>> GetInternalChannels(LiveTvChannelQuery query, CancellationToken cancellationToken)
  123. {
  124. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  125. var channels = _channelIdList.Select(_libraryManager.GetItemById)
  126. .Where(i => i != null)
  127. .OfType<LiveTvChannel>();
  128. if (user != null)
  129. {
  130. // Avoid implicitly captured closure
  131. var currentUser = user;
  132. channels = channels
  133. .Where(i => i.IsVisible(currentUser))
  134. .OrderBy(i =>
  135. {
  136. double number = 0;
  137. if (!string.IsNullOrEmpty(i.Number))
  138. {
  139. double.TryParse(i.Number, out number);
  140. }
  141. return number;
  142. });
  143. if (query.IsFavorite.HasValue)
  144. {
  145. var val = query.IsFavorite.Value;
  146. channels = channels
  147. .Where(i => _userDataManager.GetUserData(user.Id, i.GetUserDataKey()).IsFavorite == val);
  148. }
  149. if (query.IsLiked.HasValue)
  150. {
  151. var val = query.IsLiked.Value;
  152. channels = channels
  153. .Where(i =>
  154. {
  155. var likes = _userDataManager.GetUserData(user.Id, i.GetUserDataKey()).Likes;
  156. return likes.HasValue && likes.Value == val;
  157. });
  158. }
  159. if (query.IsDisliked.HasValue)
  160. {
  161. var val = query.IsDisliked.Value;
  162. channels = channels
  163. .Where(i =>
  164. {
  165. var likes = _userDataManager.GetUserData(user.Id, i.GetUserDataKey()).Likes;
  166. return likes.HasValue && likes.Value != val;
  167. });
  168. }
  169. }
  170. var enableFavoriteSorting = query.EnableFavoriteSorting;
  171. channels = channels.OrderBy(i =>
  172. {
  173. if (enableFavoriteSorting)
  174. {
  175. var userData = _userDataManager.GetUserData(user.Id, i.GetUserDataKey());
  176. if (userData.IsFavorite)
  177. {
  178. return 0;
  179. }
  180. if (userData.Likes.HasValue)
  181. {
  182. if (!userData.Likes.Value)
  183. {
  184. return 3;
  185. }
  186. return 1;
  187. }
  188. }
  189. return 2;
  190. });
  191. var allChannels = channels.ToList();
  192. IEnumerable<LiveTvChannel> allEnumerable = allChannels;
  193. if (query.StartIndex.HasValue)
  194. {
  195. allEnumerable = allEnumerable.Skip(query.StartIndex.Value);
  196. }
  197. if (query.Limit.HasValue)
  198. {
  199. allEnumerable = allEnumerable.Take(query.Limit.Value);
  200. }
  201. var result = new QueryResult<LiveTvChannel>
  202. {
  203. Items = allEnumerable.ToArray(),
  204. TotalRecordCount = allChannels.Count
  205. };
  206. return result;
  207. }
  208. public async Task<QueryResult<ChannelInfoDto>> GetChannels(LiveTvChannelQuery query, CancellationToken cancellationToken)
  209. {
  210. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  211. var internalResult = await GetInternalChannels(query, cancellationToken).ConfigureAwait(false);
  212. var returnList = new List<ChannelInfoDto>();
  213. foreach (var channel in internalResult.Items)
  214. {
  215. var currentProgram = GetCurrentProgram(channel.ExternalId);
  216. returnList.Add(_tvDtoService.GetChannelInfoDto(channel, currentProgram, user));
  217. }
  218. var result = new QueryResult<ChannelInfoDto>
  219. {
  220. Items = returnList.ToArray(),
  221. TotalRecordCount = internalResult.TotalRecordCount
  222. };
  223. return result;
  224. }
  225. public LiveTvChannel GetInternalChannel(string id)
  226. {
  227. return GetInternalChannel(new Guid(id));
  228. }
  229. private LiveTvChannel GetInternalChannel(Guid id)
  230. {
  231. return _libraryManager.GetItemById(id) as LiveTvChannel;
  232. }
  233. private LiveTvProgram GetInternalProgram(string id)
  234. {
  235. var guid = new Guid(id);
  236. LiveTvProgram obj = null;
  237. GetProgramsDictionary().TryGetValue(guid, out obj);
  238. if (obj != null)
  239. {
  240. RefreshIfNeeded(obj);
  241. }
  242. return obj;
  243. }
  244. private void RefreshIfNeeded(LiveTvProgram program)
  245. {
  246. if (!_refreshedPrograms.ContainsKey(program.Id))
  247. {
  248. _refreshedPrograms.TryAdd(program.Id, true);
  249. _providerManager.QueueRefresh(program.Id, new MetadataRefreshOptions());
  250. }
  251. }
  252. private void RefreshIfNeeded(IEnumerable<LiveTvProgram> programs)
  253. {
  254. foreach (var program in programs)
  255. {
  256. RefreshIfNeeded(program);
  257. }
  258. }
  259. public async Task<ILiveTvRecording> GetInternalRecording(string id, CancellationToken cancellationToken)
  260. {
  261. var result = await GetInternalRecordings(new RecordingQuery
  262. {
  263. Id = id
  264. }, cancellationToken).ConfigureAwait(false);
  265. return result.Items.FirstOrDefault() as ILiveTvRecording;
  266. }
  267. private readonly SemaphoreSlim _liveStreamSemaphore = new SemaphoreSlim(1, 1);
  268. public async Task<MediaSourceInfo> GetRecordingStream(string id, CancellationToken cancellationToken)
  269. {
  270. return await GetLiveStream(id, false, cancellationToken).ConfigureAwait(false);
  271. }
  272. public async Task<MediaSourceInfo> GetChannelStream(string id, CancellationToken cancellationToken)
  273. {
  274. return await GetLiveStream(id, true, cancellationToken).ConfigureAwait(false);
  275. }
  276. public async Task<IEnumerable<MediaSourceInfo>> GetRecordingMediaSources(string id, CancellationToken cancellationToken)
  277. {
  278. var item = await GetInternalRecording(id, cancellationToken).ConfigureAwait(false);
  279. var service = GetService(item);
  280. return await service.GetRecordingStreamMediaSources(id, cancellationToken).ConfigureAwait(false);
  281. }
  282. public async Task<IEnumerable<MediaSourceInfo>> GetChannelMediaSources(string id, CancellationToken cancellationToken)
  283. {
  284. var item = GetInternalChannel(id);
  285. var service = GetService(item);
  286. return await service.GetChannelStreamMediaSources(id, cancellationToken).ConfigureAwait(false);
  287. }
  288. private ILiveTvService GetService(ILiveTvItem item)
  289. {
  290. return GetService(item.ServiceName);
  291. }
  292. private ILiveTvService GetService(string name)
  293. {
  294. return _services.FirstOrDefault(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase));
  295. }
  296. private async Task<MediaSourceInfo> GetLiveStream(string id, bool isChannel, CancellationToken cancellationToken)
  297. {
  298. await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  299. try
  300. {
  301. MediaSourceInfo info;
  302. bool isVideo;
  303. if (isChannel)
  304. {
  305. var channel = GetInternalChannel(id);
  306. isVideo = channel.ChannelType == ChannelType.TV;
  307. var service = GetService(channel);
  308. _logger.Info("Opening channel stream from {0}, external channel Id: {1}", service.Name, channel.ExternalId);
  309. info = await service.GetChannelStream(channel.ExternalId, null, cancellationToken).ConfigureAwait(false);
  310. info.RequiresClosing = true;
  311. if (info.RequiresClosing)
  312. {
  313. var idPrefix = service.GetType().FullName.GetMD5().ToString("N") + "_";
  314. info.LiveStreamId = idPrefix + info.Id;
  315. }
  316. }
  317. else
  318. {
  319. var recording = await GetInternalRecording(id, cancellationToken).ConfigureAwait(false);
  320. isVideo = !string.Equals(recording.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase);
  321. var service = GetService(recording);
  322. _logger.Info("Opening recording stream from {0}, external recording Id: {1}", service.Name, recording.RecordingInfo.Id);
  323. info = await service.GetRecordingStream(recording.RecordingInfo.Id, null, cancellationToken).ConfigureAwait(false);
  324. info.RequiresClosing = true;
  325. if (info.RequiresClosing)
  326. {
  327. var idPrefix = service.GetType().FullName.GetMD5().ToString("N") + "_";
  328. info.LiveStreamId = idPrefix + info.Id;
  329. }
  330. }
  331. _logger.Info("Live stream info: {0}", _jsonSerializer.SerializeToString(info));
  332. Normalize(info, isVideo);
  333. var data = new LiveStreamData
  334. {
  335. Info = info,
  336. IsChannel = isChannel,
  337. ItemId = id
  338. };
  339. _openStreams.AddOrUpdate(info.Id, data, (key, i) => data);
  340. return info;
  341. }
  342. catch (Exception ex)
  343. {
  344. _logger.ErrorException("Error getting channel stream", ex);
  345. throw;
  346. }
  347. finally
  348. {
  349. _liveStreamSemaphore.Release();
  350. }
  351. }
  352. private void Normalize(MediaSourceInfo mediaSource, bool isVideo)
  353. {
  354. if (mediaSource.MediaStreams.Count == 0)
  355. {
  356. if (isVideo)
  357. {
  358. mediaSource.MediaStreams.AddRange(new List<MediaStream>
  359. {
  360. new MediaStream
  361. {
  362. Type = MediaStreamType.Video,
  363. // Set the index to -1 because we don't know the exact index of the video stream within the container
  364. Index = -1,
  365. // Set to true if unknown to enable deinterlacing
  366. IsInterlaced = true
  367. },
  368. new MediaStream
  369. {
  370. Type = MediaStreamType.Audio,
  371. // Set the index to -1 because we don't know the exact index of the audio stream within the container
  372. Index = -1
  373. }
  374. });
  375. }
  376. else
  377. {
  378. mediaSource.MediaStreams.AddRange(new List<MediaStream>
  379. {
  380. new MediaStream
  381. {
  382. Type = MediaStreamType.Audio,
  383. // Set the index to -1 because we don't know the exact index of the audio stream within the container
  384. Index = -1
  385. }
  386. });
  387. }
  388. }
  389. // Clean some bad data coming from providers
  390. foreach (var stream in mediaSource.MediaStreams)
  391. {
  392. if (stream.BitRate.HasValue && stream.BitRate <= 0)
  393. {
  394. stream.BitRate = null;
  395. }
  396. if (stream.Channels.HasValue && stream.Channels <= 0)
  397. {
  398. stream.Channels = null;
  399. }
  400. if (stream.AverageFrameRate.HasValue && stream.AverageFrameRate <= 0)
  401. {
  402. stream.AverageFrameRate = null;
  403. }
  404. if (stream.RealFrameRate.HasValue && stream.RealFrameRate <= 0)
  405. {
  406. stream.RealFrameRate = null;
  407. }
  408. if (stream.Width.HasValue && stream.Width <= 0)
  409. {
  410. stream.Width = null;
  411. }
  412. if (stream.Height.HasValue && stream.Height <= 0)
  413. {
  414. stream.Height = null;
  415. }
  416. if (stream.SampleRate.HasValue && stream.SampleRate <= 0)
  417. {
  418. stream.SampleRate = null;
  419. }
  420. if (stream.Level.HasValue && stream.Level <= 0)
  421. {
  422. stream.Level = null;
  423. }
  424. }
  425. var indexes = mediaSource.MediaStreams.Select(i => i.Index).Distinct().ToList();
  426. // If there are duplicate stream indexes, set them all to unknown
  427. if (indexes.Count != mediaSource.MediaStreams.Count)
  428. {
  429. foreach (var stream in mediaSource.MediaStreams)
  430. {
  431. stream.Index = -1;
  432. }
  433. }
  434. }
  435. private async Task<LiveTvChannel> GetChannel(ChannelInfo channelInfo, string serviceName, CancellationToken cancellationToken)
  436. {
  437. var isNew = false;
  438. var id = _tvDtoService.GetInternalChannelId(serviceName, channelInfo.Id);
  439. var item = _itemRepo.RetrieveItem(id) as LiveTvChannel;
  440. if (item == null)
  441. {
  442. item = new LiveTvChannel
  443. {
  444. Name = channelInfo.Name,
  445. Id = id,
  446. DateCreated = DateTime.UtcNow,
  447. };
  448. isNew = true;
  449. }
  450. item.ChannelType = channelInfo.ChannelType;
  451. item.ExternalId = channelInfo.Id;
  452. item.ServiceName = serviceName;
  453. item.Number = channelInfo.Number;
  454. var replaceImages = new List<ImageType>();
  455. if (!string.Equals(item.ProviderImageUrl, channelInfo.ImageUrl, StringComparison.OrdinalIgnoreCase))
  456. {
  457. isNew = true;
  458. replaceImages.Add(ImageType.Primary);
  459. }
  460. if (!string.Equals(item.ProviderImagePath, channelInfo.ImagePath, StringComparison.OrdinalIgnoreCase))
  461. {
  462. isNew = true;
  463. replaceImages.Add(ImageType.Primary);
  464. }
  465. item.ProviderImageUrl = channelInfo.ImageUrl;
  466. item.HasProviderImage = channelInfo.HasImage;
  467. item.ProviderImagePath = channelInfo.ImagePath;
  468. if (string.IsNullOrEmpty(item.Name))
  469. {
  470. item.Name = channelInfo.Name;
  471. }
  472. await item.RefreshMetadata(new MetadataRefreshOptions
  473. {
  474. ForceSave = isNew,
  475. ReplaceImages = replaceImages.Distinct().ToList()
  476. }, cancellationToken);
  477. return item;
  478. }
  479. private async Task<LiveTvProgram> GetProgram(ProgramInfo info, ChannelType channelType, string serviceName, CancellationToken cancellationToken)
  480. {
  481. var id = _tvDtoService.GetInternalProgramId(serviceName, info.Id);
  482. var item = _libraryManager.GetItemById(id) as LiveTvProgram;
  483. if (item == null)
  484. {
  485. item = new LiveTvProgram
  486. {
  487. Name = info.Name,
  488. Id = id,
  489. DateCreated = DateTime.UtcNow,
  490. DateModified = DateTime.UtcNow
  491. };
  492. }
  493. item.ChannelType = channelType;
  494. item.ServiceName = serviceName;
  495. item.Audio = info.Audio;
  496. item.ExternalChannelId = info.ChannelId;
  497. item.CommunityRating = info.CommunityRating;
  498. item.EndDate = info.EndDate;
  499. item.EpisodeTitle = info.EpisodeTitle;
  500. item.ExternalId = info.Id;
  501. item.Genres = info.Genres;
  502. item.HasProviderImage = info.HasImage;
  503. item.IsHD = info.IsHD;
  504. item.IsKids = info.IsKids;
  505. item.IsLive = info.IsLive;
  506. item.IsMovie = info.IsMovie;
  507. item.IsNews = info.IsNews;
  508. item.IsPremiere = info.IsPremiere;
  509. item.IsRepeat = info.IsRepeat;
  510. item.IsSeries = info.IsSeries;
  511. item.IsSports = info.IsSports;
  512. item.Name = info.Name;
  513. item.OfficialRating = info.OfficialRating;
  514. item.Overview = info.Overview;
  515. item.OriginalAirDate = info.OriginalAirDate;
  516. item.ProviderImagePath = info.ImagePath;
  517. item.ProviderImageUrl = info.ImageUrl;
  518. item.RunTimeTicks = (info.EndDate - info.StartDate).Ticks;
  519. item.StartDate = info.StartDate;
  520. item.ProductionYear = info.ProductionYear;
  521. item.PremiereDate = item.PremiereDate ?? info.OriginalAirDate;
  522. await item.UpdateToRepository(ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
  523. return item;
  524. }
  525. private async Task<ILiveTvRecording> GetRecording(RecordingInfo info, string serviceName, CancellationToken cancellationToken)
  526. {
  527. var isNew = false;
  528. var id = _tvDtoService.GetInternalRecordingId(serviceName, info.Id);
  529. var item = _itemRepo.RetrieveItem(id) as ILiveTvRecording;
  530. if (item == null)
  531. {
  532. if (info.ChannelType == ChannelType.TV)
  533. {
  534. item = new LiveTvVideoRecording
  535. {
  536. Name = info.Name,
  537. Id = id,
  538. DateCreated = DateTime.UtcNow,
  539. DateModified = DateTime.UtcNow,
  540. VideoType = VideoType.VideoFile
  541. };
  542. }
  543. else
  544. {
  545. item = new LiveTvAudioRecording
  546. {
  547. Name = info.Name,
  548. Id = id,
  549. DateCreated = DateTime.UtcNow,
  550. DateModified = DateTime.UtcNow
  551. };
  552. }
  553. isNew = true;
  554. }
  555. item.RecordingInfo = info;
  556. item.ServiceName = serviceName;
  557. var originalPath = item.Path;
  558. if (!string.IsNullOrEmpty(info.Path))
  559. {
  560. item.Path = info.Path;
  561. }
  562. else if (!string.IsNullOrEmpty(info.Url))
  563. {
  564. item.Path = info.Url;
  565. }
  566. var pathChanged = !string.Equals(originalPath, item.Path);
  567. await item.RefreshMetadata(new MetadataRefreshOptions
  568. {
  569. ForceSave = isNew || pathChanged
  570. }, cancellationToken);
  571. _libraryManager.RegisterItem((BaseItem)item);
  572. return item;
  573. }
  574. private LiveTvChannel GetChannel(LiveTvProgram program)
  575. {
  576. var programChannelId = program.ExternalChannelId;
  577. if (string.IsNullOrWhiteSpace(programChannelId)) return null;
  578. var internalProgramChannelId = _tvDtoService.GetInternalChannelId(program.ServiceName, programChannelId);
  579. return GetInternalChannel(internalProgramChannelId);
  580. }
  581. public async Task<ProgramInfoDto> GetProgram(string id, CancellationToken cancellationToken, User user = null)
  582. {
  583. var program = GetInternalProgram(id);
  584. var channel = GetChannel(program);
  585. var dto = _tvDtoService.GetProgramInfoDto(program, channel, user);
  586. await AddRecordingInfo(new[] { dto }, cancellationToken).ConfigureAwait(false);
  587. return dto;
  588. }
  589. public async Task<QueryResult<ProgramInfoDto>> GetPrograms(ProgramQuery query, CancellationToken cancellationToken)
  590. {
  591. IEnumerable<LiveTvProgram> programs = GetPrograms();
  592. if (query.MinEndDate.HasValue)
  593. {
  594. var val = query.MinEndDate.Value;
  595. programs = programs.Where(i => i.EndDate.HasValue && i.EndDate.Value >= val);
  596. }
  597. if (query.MinStartDate.HasValue)
  598. {
  599. var val = query.MinStartDate.Value;
  600. programs = programs.Where(i => i.StartDate >= val);
  601. }
  602. if (query.MaxEndDate.HasValue)
  603. {
  604. var val = query.MaxEndDate.Value;
  605. programs = programs.Where(i => i.EndDate.HasValue && i.EndDate.Value <= val);
  606. }
  607. if (query.MaxStartDate.HasValue)
  608. {
  609. var val = query.MaxStartDate.Value;
  610. programs = programs.Where(i => i.StartDate <= val);
  611. }
  612. if (query.HasAired.HasValue)
  613. {
  614. var val = query.HasAired.Value;
  615. programs = programs.Where(i => i.HasAired == val);
  616. }
  617. if (query.ChannelIds.Length > 0)
  618. {
  619. var guids = query.ChannelIds.Select(i => new Guid(i)).ToList();
  620. programs = programs.Where(i =>
  621. {
  622. var programChannelId = i.ExternalChannelId;
  623. var service = GetService(i);
  624. var internalProgramChannelId = _tvDtoService.GetInternalChannelId(service.Name, programChannelId);
  625. return guids.Contains(internalProgramChannelId);
  626. });
  627. }
  628. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  629. if (user != null)
  630. {
  631. // Avoid implicitly captured closure
  632. var currentUser = user;
  633. programs = programs.Where(i => i.IsVisible(currentUser));
  634. }
  635. // Apply genre filter
  636. if (query.Genres.Length > 0)
  637. {
  638. programs = programs.Where(p => p.Genres.Any(g => query.Genres.Contains(g, StringComparer.OrdinalIgnoreCase)));
  639. }
  640. if (query.IsMovie.HasValue)
  641. {
  642. programs = programs.Where(p => p.IsMovie == query.IsMovie);
  643. }
  644. if (query.IsSports.HasValue)
  645. {
  646. programs = programs.Where(p => p.IsSports == query.IsSports);
  647. }
  648. programs = _libraryManager.Sort(programs, user, query.SortBy, query.SortOrder ?? SortOrder.Ascending)
  649. .Cast<LiveTvProgram>();
  650. var programList = programs.ToList();
  651. IEnumerable<LiveTvProgram> returnPrograms = programList;
  652. if (query.StartIndex.HasValue)
  653. {
  654. returnPrograms = returnPrograms.Skip(query.StartIndex.Value);
  655. }
  656. if (query.Limit.HasValue)
  657. {
  658. returnPrograms = returnPrograms.Take(query.Limit.Value);
  659. }
  660. var returnArray = returnPrograms
  661. .Select(i =>
  662. {
  663. var channel = GetChannel(i);
  664. return _tvDtoService.GetProgramInfoDto(i, channel, user);
  665. })
  666. .ToArray();
  667. RefreshIfNeeded(programList);
  668. await AddRecordingInfo(returnArray, cancellationToken).ConfigureAwait(false);
  669. var result = new QueryResult<ProgramInfoDto>
  670. {
  671. Items = returnArray,
  672. TotalRecordCount = programList.Count
  673. };
  674. return result;
  675. }
  676. public async Task<QueryResult<LiveTvProgram>> GetRecommendedProgramsInternal(RecommendedProgramQuery query, CancellationToken cancellationToken)
  677. {
  678. IEnumerable<LiveTvProgram> programs = GetPrograms();
  679. var user = _userManager.GetUserById(query.UserId);
  680. // Avoid implicitly captured closure
  681. var currentUser = user;
  682. programs = programs.Where(i => i.IsVisible(currentUser));
  683. if (query.IsAiring.HasValue)
  684. {
  685. var val = query.IsAiring.Value;
  686. programs = programs.Where(i => i.IsAiring == val);
  687. }
  688. if (query.HasAired.HasValue)
  689. {
  690. var val = query.HasAired.Value;
  691. programs = programs.Where(i => i.HasAired == val);
  692. }
  693. if (query.IsMovie.HasValue)
  694. {
  695. programs = programs.Where(p => p.IsMovie == query.IsMovie.Value);
  696. }
  697. if (query.IsSports.HasValue)
  698. {
  699. programs = programs.Where(p => p.IsSports == query.IsSports.Value);
  700. }
  701. var programList = programs.ToList();
  702. var genres = programList.SelectMany(i => i.Genres)
  703. .DistinctNames()
  704. .Select(i => _libraryManager.GetGenre(i))
  705. .ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);
  706. programs = programList.OrderBy(i => i.HasImage(ImageType.Primary) ? 0 : 1)
  707. .ThenByDescending(i => GetRecommendationScore(i, user.Id, genres))
  708. .ThenBy(i => i.StartDate);
  709. if (query.Limit.HasValue)
  710. {
  711. programs = programs.Take(query.Limit.Value)
  712. .OrderBy(i => i.StartDate);
  713. }
  714. programList = programs.ToList();
  715. RefreshIfNeeded(programList);
  716. var returnArray = programList.ToArray();
  717. var result = new QueryResult<LiveTvProgram>
  718. {
  719. Items = returnArray,
  720. TotalRecordCount = returnArray.Length
  721. };
  722. return result;
  723. }
  724. public async Task<QueryResult<ProgramInfoDto>> GetRecommendedPrograms(RecommendedProgramQuery query, CancellationToken cancellationToken)
  725. {
  726. var internalResult = await GetRecommendedProgramsInternal(query, cancellationToken).ConfigureAwait(false);
  727. var user = _userManager.GetUserById(query.UserId);
  728. var returnArray = internalResult.Items
  729. .Select(i =>
  730. {
  731. var channel = GetChannel(i);
  732. return _tvDtoService.GetProgramInfoDto(i, channel, user);
  733. })
  734. .ToArray();
  735. await AddRecordingInfo(returnArray, cancellationToken).ConfigureAwait(false);
  736. var result = new QueryResult<ProgramInfoDto>
  737. {
  738. Items = returnArray,
  739. TotalRecordCount = internalResult.TotalRecordCount
  740. };
  741. return result;
  742. }
  743. private int GetRecommendationScore(LiveTvProgram program, Guid userId, Dictionary<string, Genre> genres)
  744. {
  745. var score = 0;
  746. if (program.IsLive)
  747. {
  748. score++;
  749. }
  750. if (program.IsSeries && !program.IsRepeat)
  751. {
  752. score++;
  753. }
  754. var internalChannelId = _tvDtoService.GetInternalChannelId(program.ServiceName, program.ExternalChannelId);
  755. var channel = GetInternalChannel(internalChannelId);
  756. var channelUserdata = _userDataManager.GetUserData(userId, channel.GetUserDataKey());
  757. if ((channelUserdata.Likes ?? false))
  758. {
  759. score += 2;
  760. }
  761. else if (!(channelUserdata.Likes ?? true))
  762. {
  763. score -= 2;
  764. }
  765. if (channelUserdata.IsFavorite)
  766. {
  767. score += 3;
  768. }
  769. score += GetGenreScore(program.Genres, userId, genres);
  770. return score;
  771. }
  772. private int GetGenreScore(IEnumerable<string> programGenres, Guid userId, Dictionary<string, Genre> genres)
  773. {
  774. return programGenres.Select(i =>
  775. {
  776. var score = 0;
  777. Genre genre;
  778. if (genres.TryGetValue(i, out genre))
  779. {
  780. var genreUserdata = _userDataManager.GetUserData(userId, genre.GetUserDataKey());
  781. if ((genreUserdata.Likes ?? false))
  782. {
  783. score++;
  784. }
  785. else if (!(genreUserdata.Likes ?? true))
  786. {
  787. score--;
  788. }
  789. if (genreUserdata.IsFavorite)
  790. {
  791. score += 2;
  792. }
  793. }
  794. return score;
  795. }).Sum();
  796. }
  797. private async Task AddRecordingInfo(IEnumerable<ProgramInfoDto> programs, CancellationToken cancellationToken)
  798. {
  799. var timers = new Dictionary<string, List<TimerInfo>>();
  800. foreach (var program in programs)
  801. {
  802. List<TimerInfo> timerList;
  803. if (!timers.TryGetValue(program.ServiceName, out timerList))
  804. {
  805. try
  806. {
  807. var tempTimers = await GetService(program.ServiceName).GetTimersAsync(cancellationToken).ConfigureAwait(false);
  808. timers[program.ServiceName] = timerList = tempTimers.ToList();
  809. }
  810. catch (Exception ex)
  811. {
  812. _logger.ErrorException("Error getting timer infos", ex);
  813. timers[program.ServiceName] = timerList = new List<TimerInfo>();
  814. }
  815. }
  816. var timer = timerList.FirstOrDefault(i => string.Equals(i.ProgramId, program.ExternalId, StringComparison.OrdinalIgnoreCase));
  817. if (timer != null)
  818. {
  819. program.TimerId = _tvDtoService.GetInternalTimerId(program.ServiceName, timer.Id)
  820. .ToString("N");
  821. if (!string.IsNullOrEmpty(timer.SeriesTimerId))
  822. {
  823. program.SeriesTimerId = _tvDtoService.GetInternalSeriesTimerId(program.ServiceName, timer.SeriesTimerId)
  824. .ToString("N");
  825. }
  826. }
  827. }
  828. }
  829. internal async Task RefreshChannels(IProgress<double> progress, CancellationToken cancellationToken)
  830. {
  831. var innerProgress = new ActionableProgress<double>();
  832. innerProgress.RegisterAction(p => progress.Report(p * .9));
  833. await RefreshChannelsInternal(innerProgress, cancellationToken).ConfigureAwait(false);
  834. innerProgress = new ActionableProgress<double>();
  835. innerProgress.RegisterAction(p => progress.Report(90 + (p * .1)));
  836. await CleanDatabaseInternal(progress, cancellationToken).ConfigureAwait(false);
  837. RefreshIfNeeded(GetPrograms().ToList());
  838. }
  839. private async Task RefreshChannelsInternal(IProgress<double> progress, CancellationToken cancellationToken)
  840. {
  841. var numComplete = 0;
  842. double progressPerService = _services.Count == 0
  843. ? 0
  844. : 1 / _services.Count;
  845. foreach (var service in _services)
  846. {
  847. cancellationToken.ThrowIfCancellationRequested();
  848. try
  849. {
  850. var innerProgress = new ActionableProgress<double>();
  851. innerProgress.RegisterAction(p => progress.Report(p * progressPerService));
  852. await RefreshChannelsInternal(service, innerProgress, cancellationToken).ConfigureAwait(false);
  853. }
  854. catch (OperationCanceledException)
  855. {
  856. throw;
  857. }
  858. catch (Exception ex)
  859. {
  860. _logger.ErrorException("Error refreshing channels for service", ex);
  861. }
  862. numComplete++;
  863. double percent = numComplete;
  864. percent /= _services.Count;
  865. progress.Report(100 * percent);
  866. }
  867. progress.Report(100);
  868. }
  869. private async Task RefreshChannelsInternal(ILiveTvService service, IProgress<double> progress, CancellationToken cancellationToken)
  870. {
  871. progress.Report(10);
  872. var allChannels = await GetChannels(service, cancellationToken).ConfigureAwait(false);
  873. var allChannelsList = allChannels.ToList();
  874. var list = new List<LiveTvChannel>();
  875. var numComplete = 0;
  876. foreach (var channelInfo in allChannelsList)
  877. {
  878. cancellationToken.ThrowIfCancellationRequested();
  879. try
  880. {
  881. var item = await GetChannel(channelInfo.Item2, channelInfo.Item1, cancellationToken).ConfigureAwait(false);
  882. list.Add(item);
  883. _libraryManager.RegisterItem(item);
  884. }
  885. catch (OperationCanceledException)
  886. {
  887. throw;
  888. }
  889. catch (Exception ex)
  890. {
  891. _logger.ErrorException("Error getting channel information for {0}", ex, channelInfo.Item2.Name);
  892. }
  893. numComplete++;
  894. double percent = numComplete;
  895. percent /= allChannelsList.Count;
  896. progress.Report(5 * percent + 10);
  897. }
  898. _channelIdList = list.Select(i => i.Id).ToList();
  899. progress.Report(15);
  900. numComplete = 0;
  901. var programs = new List<LiveTvProgram>();
  902. var guideDays = GetGuideDays(list.Count);
  903. cancellationToken.ThrowIfCancellationRequested();
  904. foreach (var item in list)
  905. {
  906. cancellationToken.ThrowIfCancellationRequested();
  907. // Avoid implicitly captured closure
  908. var currentChannel = item;
  909. try
  910. {
  911. var start = DateTime.UtcNow.AddHours(-1);
  912. var end = start.AddDays(guideDays);
  913. var channelPrograms = await service.GetProgramsAsync(currentChannel.ExternalId, start, end, cancellationToken).ConfigureAwait(false);
  914. foreach (var program in channelPrograms)
  915. {
  916. programs.Add(await GetProgram(program, currentChannel.ChannelType, service.Name, cancellationToken).ConfigureAwait(false));
  917. }
  918. }
  919. catch (OperationCanceledException)
  920. {
  921. throw;
  922. }
  923. catch (Exception ex)
  924. {
  925. _logger.ErrorException("Error getting programs for channel {0}", ex, currentChannel.Name);
  926. }
  927. numComplete++;
  928. double percent = numComplete;
  929. percent /= allChannelsList.Count;
  930. progress.Report(80 * percent + 10);
  931. }
  932. lock (_programsDataLock)
  933. {
  934. _programs = programs.ToDictionary(i => i.Id);
  935. }
  936. _refreshedPrograms.Clear();
  937. progress.Report(90);
  938. // Load these now which will prefetch metadata
  939. var dtoOptions = new DtoOptions();
  940. dtoOptions.Fields.Remove(ItemFields.SyncInfo);
  941. await GetRecordings(new RecordingQuery(), dtoOptions, cancellationToken).ConfigureAwait(false);
  942. progress.Report(100);
  943. }
  944. private Task CleanDatabaseInternal(IProgress<double> progress, CancellationToken cancellationToken)
  945. {
  946. return DeleteOldPrograms(GetProgramsDictionary().Keys.ToList(), progress, cancellationToken);
  947. }
  948. private async Task DeleteOldPrograms(List<Guid> currentIdList, IProgress<double> progress, CancellationToken cancellationToken)
  949. {
  950. var list = _itemRepo.GetItemIdsOfType(typeof(LiveTvProgram)).ToList();
  951. var numComplete = 0;
  952. foreach (var programId in list)
  953. {
  954. cancellationToken.ThrowIfCancellationRequested();
  955. if (!currentIdList.Contains(programId))
  956. {
  957. var program = _libraryManager.GetItemById(programId);
  958. if (program != null)
  959. {
  960. await _libraryManager.DeleteItem(program).ConfigureAwait(false);
  961. }
  962. }
  963. numComplete++;
  964. double percent = numComplete;
  965. percent /= list.Count;
  966. progress.Report(100 * percent);
  967. }
  968. }
  969. private double GetGuideDays(int channelCount)
  970. {
  971. var config = GetConfiguration();
  972. if (config.GuideDays.HasValue)
  973. {
  974. return config.GuideDays.Value;
  975. }
  976. var programsPerDay = channelCount * 48;
  977. const int maxPrograms = 24000;
  978. var days = Math.Round(((double)maxPrograms) / programsPerDay);
  979. return Math.Max(3, Math.Min(days, 14));
  980. }
  981. private async Task<IEnumerable<Tuple<string, ChannelInfo>>> GetChannels(ILiveTvService service, CancellationToken cancellationToken)
  982. {
  983. var channels = await service.GetChannelsAsync(cancellationToken).ConfigureAwait(false);
  984. return channels.Select(i => new Tuple<string, ChannelInfo>(service.Name, i));
  985. }
  986. public async Task<QueryResult<BaseItem>> GetInternalRecordings(RecordingQuery query, CancellationToken cancellationToken)
  987. {
  988. var tasks = _services.Select(async i =>
  989. {
  990. try
  991. {
  992. var recs = await i.GetRecordingsAsync(cancellationToken).ConfigureAwait(false);
  993. return recs.Select(r => new Tuple<RecordingInfo, ILiveTvService>(r, i));
  994. }
  995. catch (Exception ex)
  996. {
  997. _logger.ErrorException("Error getting recordings", ex);
  998. return new List<Tuple<RecordingInfo, ILiveTvService>>();
  999. }
  1000. });
  1001. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  1002. var recordings = results.SelectMany(i => i.ToList());
  1003. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  1004. if (user != null && !IsLiveTvEnabled(user))
  1005. {
  1006. recordings = new List<Tuple<RecordingInfo, ILiveTvService>>();
  1007. }
  1008. if (!string.IsNullOrEmpty(query.ChannelId))
  1009. {
  1010. var guid = new Guid(query.ChannelId);
  1011. recordings = recordings
  1012. .Where(i => _tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId) == guid);
  1013. }
  1014. if (!string.IsNullOrEmpty(query.Id))
  1015. {
  1016. var guid = new Guid(query.Id);
  1017. recordings = recordings
  1018. .Where(i => _tvDtoService.GetInternalRecordingId(i.Item2.Name, i.Item1.Id) == guid);
  1019. }
  1020. if (!string.IsNullOrEmpty(query.GroupId))
  1021. {
  1022. var guid = new Guid(query.GroupId);
  1023. recordings = recordings.Where(i => GetRecordingGroupIds(i.Item1).Contains(guid));
  1024. }
  1025. if (query.IsInProgress.HasValue)
  1026. {
  1027. var val = query.IsInProgress.Value;
  1028. recordings = recordings.Where(i => (i.Item1.Status == RecordingStatus.InProgress) == val);
  1029. }
  1030. if (query.Status.HasValue)
  1031. {
  1032. var val = query.Status.Value;
  1033. recordings = recordings.Where(i => (i.Item1.Status == val));
  1034. }
  1035. if (!string.IsNullOrEmpty(query.SeriesTimerId))
  1036. {
  1037. var guid = new Guid(query.SeriesTimerId);
  1038. recordings = recordings
  1039. .Where(i => _tvDtoService.GetInternalSeriesTimerId(i.Item2.Name, i.Item1.SeriesTimerId) == guid);
  1040. }
  1041. recordings = recordings.OrderByDescending(i => i.Item1.StartDate);
  1042. IEnumerable<ILiveTvRecording> entities = await GetEntities(recordings, cancellationToken).ConfigureAwait(false);
  1043. if (user != null)
  1044. {
  1045. var currentUser = user;
  1046. entities = entities.Where(i => i.IsParentalAllowed(currentUser));
  1047. }
  1048. var entityList = entities.ToList();
  1049. entities = entityList;
  1050. if (query.StartIndex.HasValue)
  1051. {
  1052. entities = entities.Skip(query.StartIndex.Value);
  1053. }
  1054. if (query.Limit.HasValue)
  1055. {
  1056. entities = entities.Take(query.Limit.Value);
  1057. }
  1058. return new QueryResult<BaseItem>
  1059. {
  1060. Items = entities.Cast<BaseItem>().ToArray(),
  1061. TotalRecordCount = entityList.Count
  1062. };
  1063. }
  1064. public async Task<QueryResult<RecordingInfoDto>> GetRecordings(RecordingQuery query, DtoOptions options, CancellationToken cancellationToken)
  1065. {
  1066. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  1067. var internalResult = await GetInternalRecordings(query, cancellationToken).ConfigureAwait(false);
  1068. var returnArray = internalResult.Items.Cast<ILiveTvRecording>()
  1069. .Select(i =>
  1070. {
  1071. var service = GetService(i);
  1072. var channel = string.IsNullOrEmpty(i.RecordingInfo.ChannelId) ? null : GetInternalChannel(_tvDtoService.GetInternalChannelId(service.Name, i.RecordingInfo.ChannelId));
  1073. return _tvDtoService.GetRecordingInfoDto(i, channel, service, user);
  1074. })
  1075. .ToArray();
  1076. if (user != null)
  1077. {
  1078. _dtoService.FillSyncInfo(returnArray, new DtoOptions(), user);
  1079. }
  1080. return new QueryResult<RecordingInfoDto>
  1081. {
  1082. Items = returnArray,
  1083. TotalRecordCount = internalResult.TotalRecordCount
  1084. };
  1085. }
  1086. private Task<ILiveTvRecording[]> GetEntities(IEnumerable<Tuple<RecordingInfo, ILiveTvService>> recordings, CancellationToken cancellationToken)
  1087. {
  1088. var tasks = recordings.Select(i => GetRecording(i.Item1, i.Item2.Name, cancellationToken));
  1089. return Task.WhenAll(tasks);
  1090. }
  1091. public async Task<QueryResult<TimerInfoDto>> GetTimers(TimerQuery query, CancellationToken cancellationToken)
  1092. {
  1093. var tasks = _services.Select(async i =>
  1094. {
  1095. try
  1096. {
  1097. var recs = await i.GetTimersAsync(cancellationToken).ConfigureAwait(false);
  1098. return recs.Select(r => new Tuple<TimerInfo, ILiveTvService>(r, i));
  1099. }
  1100. catch (Exception ex)
  1101. {
  1102. _logger.ErrorException("Error getting recordings", ex);
  1103. return new List<Tuple<TimerInfo, ILiveTvService>>();
  1104. }
  1105. });
  1106. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  1107. var timers = results.SelectMany(i => i.ToList());
  1108. if (!string.IsNullOrEmpty(query.ChannelId))
  1109. {
  1110. var guid = new Guid(query.ChannelId);
  1111. timers = timers.Where(i => guid == _tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId));
  1112. }
  1113. if (!string.IsNullOrEmpty(query.SeriesTimerId))
  1114. {
  1115. var guid = new Guid(query.SeriesTimerId);
  1116. timers = timers
  1117. .Where(i => _tvDtoService.GetInternalSeriesTimerId(i.Item2.Name, i.Item1.SeriesTimerId) == guid);
  1118. }
  1119. var returnList = new List<TimerInfoDto>();
  1120. foreach (var i in timers)
  1121. {
  1122. var program = string.IsNullOrEmpty(i.Item1.ProgramId) ?
  1123. null :
  1124. GetInternalProgram(_tvDtoService.GetInternalProgramId(i.Item2.Name, i.Item1.ProgramId).ToString("N"));
  1125. var channel = string.IsNullOrEmpty(i.Item1.ChannelId) ? null : GetInternalChannel(_tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId));
  1126. returnList.Add(_tvDtoService.GetTimerInfoDto(i.Item1, i.Item2, program, channel));
  1127. }
  1128. var returnArray = returnList
  1129. .OrderBy(i => i.StartDate)
  1130. .ToArray();
  1131. return new QueryResult<TimerInfoDto>
  1132. {
  1133. Items = returnArray,
  1134. TotalRecordCount = returnArray.Length
  1135. };
  1136. }
  1137. public async Task DeleteRecording(string recordingId)
  1138. {
  1139. var dtoOptions = new DtoOptions();
  1140. dtoOptions.Fields.Remove(ItemFields.SyncInfo);
  1141. var recording = await GetRecording(recordingId, dtoOptions, CancellationToken.None).ConfigureAwait(false);
  1142. if (recording == null)
  1143. {
  1144. throw new ResourceNotFoundException(string.Format("Recording with Id {0} not found", recordingId));
  1145. }
  1146. var service = GetService(recording.ServiceName);
  1147. await service.DeleteRecordingAsync(recording.ExternalId, CancellationToken.None).ConfigureAwait(false);
  1148. }
  1149. public async Task CancelTimer(string id)
  1150. {
  1151. var timer = await GetTimer(id, CancellationToken.None).ConfigureAwait(false);
  1152. if (timer == null)
  1153. {
  1154. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  1155. }
  1156. var service = GetService(timer.ServiceName);
  1157. await service.CancelTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  1158. }
  1159. public async Task CancelSeriesTimer(string id)
  1160. {
  1161. var timer = await GetSeriesTimer(id, CancellationToken.None).ConfigureAwait(false);
  1162. if (timer == null)
  1163. {
  1164. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  1165. }
  1166. var service = GetService(timer.ServiceName);
  1167. await service.CancelSeriesTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  1168. }
  1169. public async Task<RecordingInfoDto> GetRecording(string id, DtoOptions options, CancellationToken cancellationToken, User user = null)
  1170. {
  1171. var results = await GetRecordings(new RecordingQuery
  1172. {
  1173. UserId = user == null ? null : user.Id.ToString("N"),
  1174. Id = id
  1175. }, options, cancellationToken).ConfigureAwait(false);
  1176. return results.Items.FirstOrDefault();
  1177. }
  1178. public async Task<TimerInfoDto> GetTimer(string id, CancellationToken cancellationToken)
  1179. {
  1180. var results = await GetTimers(new TimerQuery(), cancellationToken).ConfigureAwait(false);
  1181. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
  1182. }
  1183. public async Task<SeriesTimerInfoDto> GetSeriesTimer(string id, CancellationToken cancellationToken)
  1184. {
  1185. var results = await GetSeriesTimers(new SeriesTimerQuery(), cancellationToken).ConfigureAwait(false);
  1186. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
  1187. }
  1188. public async Task<QueryResult<SeriesTimerInfoDto>> GetSeriesTimers(SeriesTimerQuery query, CancellationToken cancellationToken)
  1189. {
  1190. var tasks = _services.Select(async i =>
  1191. {
  1192. try
  1193. {
  1194. var recs = await i.GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false);
  1195. return recs.Select(r => new Tuple<SeriesTimerInfo, ILiveTvService>(r, i));
  1196. }
  1197. catch (Exception ex)
  1198. {
  1199. _logger.ErrorException("Error getting recordings", ex);
  1200. return new List<Tuple<SeriesTimerInfo, ILiveTvService>>();
  1201. }
  1202. });
  1203. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  1204. var timers = results.SelectMany(i => i.ToList());
  1205. if (string.Equals(query.SortBy, "Priority", StringComparison.OrdinalIgnoreCase))
  1206. {
  1207. timers = query.SortOrder == SortOrder.Descending ?
  1208. timers.OrderBy(i => i.Item1.Priority).ThenByStringDescending(i => i.Item1.Name) :
  1209. timers.OrderByDescending(i => i.Item1.Priority).ThenByString(i => i.Item1.Name);
  1210. }
  1211. else
  1212. {
  1213. timers = query.SortOrder == SortOrder.Descending ?
  1214. timers.OrderByStringDescending(i => i.Item1.Name) :
  1215. timers.OrderByString(i => i.Item1.Name);
  1216. }
  1217. var returnArray = timers
  1218. .Select(i =>
  1219. {
  1220. string channelName = null;
  1221. if (!string.IsNullOrEmpty(i.Item1.ChannelId))
  1222. {
  1223. var internalChannelId = _tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId);
  1224. var channel = GetInternalChannel(internalChannelId);
  1225. channelName = channel == null ? null : channel.Name;
  1226. }
  1227. return _tvDtoService.GetSeriesTimerInfoDto(i.Item1, i.Item2, channelName);
  1228. })
  1229. .ToArray();
  1230. return new QueryResult<SeriesTimerInfoDto>
  1231. {
  1232. Items = returnArray,
  1233. TotalRecordCount = returnArray.Length
  1234. };
  1235. }
  1236. public async Task<ChannelInfoDto> GetChannel(string id, CancellationToken cancellationToken, User user = null)
  1237. {
  1238. var channel = GetInternalChannel(id);
  1239. var currentProgram = GetCurrentProgram(channel.ExternalId);
  1240. var dto = _tvDtoService.GetChannelInfoDto(channel, currentProgram, user);
  1241. return dto;
  1242. }
  1243. private LiveTvProgram GetCurrentProgram(string externalChannelId)
  1244. {
  1245. var now = DateTime.UtcNow;
  1246. var program = GetPrograms()
  1247. .Where(i => string.Equals(externalChannelId, i.ExternalChannelId, StringComparison.OrdinalIgnoreCase))
  1248. .OrderBy(i => i.StartDate)
  1249. .SkipWhile(i => now >= (i.EndDate ?? DateTime.MinValue))
  1250. .FirstOrDefault();
  1251. if (program != null)
  1252. {
  1253. RefreshIfNeeded(program);
  1254. }
  1255. return program;
  1256. }
  1257. private async Task<Tuple<SeriesTimerInfo, ILiveTvService>> GetNewTimerDefaultsInternal(CancellationToken cancellationToken, LiveTvProgram program = null)
  1258. {
  1259. var service = program != null && !string.IsNullOrWhiteSpace(program.ServiceName) ?
  1260. GetService(program) :
  1261. _services.FirstOrDefault();
  1262. ProgramInfo programInfo = null;
  1263. if (program != null)
  1264. {
  1265. programInfo = new ProgramInfo
  1266. {
  1267. Audio = program.Audio,
  1268. ChannelId = program.ExternalChannelId,
  1269. CommunityRating = program.CommunityRating,
  1270. EndDate = program.EndDate ?? DateTime.MinValue,
  1271. EpisodeTitle = program.EpisodeTitle,
  1272. Genres = program.Genres,
  1273. HasImage = program.HasProviderImage,
  1274. Id = program.ExternalId,
  1275. IsHD = program.IsHD,
  1276. IsKids = program.IsKids,
  1277. IsLive = program.IsLive,
  1278. IsMovie = program.IsMovie,
  1279. IsNews = program.IsNews,
  1280. IsPremiere = program.IsPremiere,
  1281. IsRepeat = program.IsRepeat,
  1282. IsSeries = program.IsSeries,
  1283. IsSports = program.IsSports,
  1284. OriginalAirDate = program.PremiereDate,
  1285. Overview = program.Overview,
  1286. StartDate = program.StartDate,
  1287. ImagePath = program.ProviderImagePath,
  1288. ImageUrl = program.ProviderImageUrl,
  1289. Name = program.Name,
  1290. OfficialRating = program.OfficialRating
  1291. };
  1292. }
  1293. var info = await service.GetNewTimerDefaultsAsync(cancellationToken, programInfo).ConfigureAwait(false);
  1294. info.Id = null;
  1295. return new Tuple<SeriesTimerInfo, ILiveTvService>(info, service);
  1296. }
  1297. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(CancellationToken cancellationToken)
  1298. {
  1299. var info = await GetNewTimerDefaultsInternal(cancellationToken).ConfigureAwait(false);
  1300. var obj = _tvDtoService.GetSeriesTimerInfoDto(info.Item1, info.Item2, null);
  1301. return obj;
  1302. }
  1303. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(string programId, CancellationToken cancellationToken)
  1304. {
  1305. var program = GetInternalProgram(programId);
  1306. var programDto = await GetProgram(programId, cancellationToken).ConfigureAwait(false);
  1307. var defaults = await GetNewTimerDefaultsInternal(cancellationToken, program).ConfigureAwait(false);
  1308. var info = _tvDtoService.GetSeriesTimerInfoDto(defaults.Item1, defaults.Item2, null);
  1309. info.Days = new List<DayOfWeek>
  1310. {
  1311. program.StartDate.ToLocalTime().DayOfWeek
  1312. };
  1313. info.DayPattern = _tvDtoService.GetDayPattern(info.Days);
  1314. info.Name = program.Name;
  1315. info.ChannelId = programDto.ChannelId;
  1316. info.ChannelName = programDto.ChannelName;
  1317. info.StartDate = program.StartDate;
  1318. info.Name = program.Name;
  1319. info.Overview = program.Overview;
  1320. info.ProgramId = programDto.Id;
  1321. info.ExternalProgramId = programDto.ExternalId;
  1322. if (program.EndDate.HasValue)
  1323. {
  1324. info.EndDate = program.EndDate.Value;
  1325. }
  1326. return info;
  1327. }
  1328. public async Task CreateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  1329. {
  1330. var service = GetService(timer.ServiceName);
  1331. var info = await _tvDtoService.GetTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  1332. // Set priority from default values
  1333. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  1334. info.Priority = defaultValues.Priority;
  1335. await service.CreateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1336. }
  1337. public async Task CreateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  1338. {
  1339. var service = GetService(timer.ServiceName);
  1340. var info = await _tvDtoService.GetSeriesTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  1341. // Set priority from default values
  1342. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  1343. info.Priority = defaultValues.Priority;
  1344. await service.CreateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1345. }
  1346. public async Task UpdateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  1347. {
  1348. var info = await _tvDtoService.GetTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  1349. var service = GetService(timer.ServiceName);
  1350. await service.UpdateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1351. }
  1352. public async Task UpdateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  1353. {
  1354. var info = await _tvDtoService.GetSeriesTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  1355. var service = GetService(timer.ServiceName);
  1356. await service.UpdateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1357. }
  1358. private IEnumerable<string> GetRecordingGroupNames(RecordingInfo recording)
  1359. {
  1360. var list = new List<string>();
  1361. if (recording.IsSeries)
  1362. {
  1363. list.Add(recording.Name);
  1364. }
  1365. if (recording.IsKids)
  1366. {
  1367. list.Add("Kids");
  1368. }
  1369. if (recording.IsMovie)
  1370. {
  1371. list.Add("Movies");
  1372. }
  1373. if (recording.IsNews)
  1374. {
  1375. list.Add("News");
  1376. }
  1377. if (recording.IsSports)
  1378. {
  1379. list.Add("Sports");
  1380. }
  1381. if (!recording.IsSports && !recording.IsNews && !recording.IsMovie && !recording.IsKids && !recording.IsSeries)
  1382. {
  1383. list.Add("Others");
  1384. }
  1385. return list;
  1386. }
  1387. private List<Guid> GetRecordingGroupIds(RecordingInfo recording)
  1388. {
  1389. return GetRecordingGroupNames(recording).Select(i => i.ToLower()
  1390. .GetMD5())
  1391. .ToList();
  1392. }
  1393. public async Task<QueryResult<RecordingGroupDto>> GetRecordingGroups(RecordingGroupQuery query, CancellationToken cancellationToken)
  1394. {
  1395. var dtoOptions = new DtoOptions();
  1396. dtoOptions.Fields.Remove(ItemFields.SyncInfo);
  1397. var recordingResult = await GetRecordings(new RecordingQuery
  1398. {
  1399. UserId = query.UserId
  1400. }, dtoOptions, cancellationToken).ConfigureAwait(false);
  1401. var recordings = recordingResult.Items;
  1402. var groups = new List<RecordingGroupDto>();
  1403. var series = recordings
  1404. .Where(i => i.IsSeries)
  1405. .ToLookup(i => i.Name, StringComparer.OrdinalIgnoreCase)
  1406. .ToList();
  1407. groups.AddRange(series.OrderByString(i => i.Key).Select(i => new RecordingGroupDto
  1408. {
  1409. Name = i.Key,
  1410. RecordingCount = i.Count()
  1411. }));
  1412. groups.Add(new RecordingGroupDto
  1413. {
  1414. Name = "Kids",
  1415. RecordingCount = recordings.Count(i => i.IsKids)
  1416. });
  1417. groups.Add(new RecordingGroupDto
  1418. {
  1419. Name = "Movies",
  1420. RecordingCount = recordings.Count(i => i.IsMovie)
  1421. });
  1422. groups.Add(new RecordingGroupDto
  1423. {
  1424. Name = "News",
  1425. RecordingCount = recordings.Count(i => i.IsNews)
  1426. });
  1427. groups.Add(new RecordingGroupDto
  1428. {
  1429. Name = "Sports",
  1430. RecordingCount = recordings.Count(i => i.IsSports)
  1431. });
  1432. groups.Add(new RecordingGroupDto
  1433. {
  1434. Name = "Others",
  1435. RecordingCount = recordings.Count(i => !i.IsSports && !i.IsNews && !i.IsMovie && !i.IsKids && !i.IsSeries)
  1436. });
  1437. groups = groups
  1438. .Where(i => i.RecordingCount > 0)
  1439. .ToList();
  1440. foreach (var group in groups)
  1441. {
  1442. group.Id = group.Name.ToLower().GetMD5().ToString("N");
  1443. }
  1444. return new QueryResult<RecordingGroupDto>
  1445. {
  1446. Items = groups.ToArray(),
  1447. TotalRecordCount = groups.Count
  1448. };
  1449. }
  1450. class LiveStreamData
  1451. {
  1452. internal MediaSourceInfo Info;
  1453. internal string ItemId;
  1454. internal bool IsChannel;
  1455. }
  1456. public async Task CloseLiveStream(string id, CancellationToken cancellationToken)
  1457. {
  1458. await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  1459. try
  1460. {
  1461. var parts = id.Split(new[] { '_' }, 2);
  1462. var service = _services.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N"), parts[0], StringComparison.OrdinalIgnoreCase));
  1463. if (service == null)
  1464. {
  1465. throw new ArgumentException("Service not found.");
  1466. }
  1467. id = parts[1];
  1468. LiveStreamData data;
  1469. _openStreams.TryRemove(id, out data);
  1470. _logger.Info("Closing live stream from {0}, stream Id: {1}", service.Name, id);
  1471. await service.CloseLiveStream(id, cancellationToken).ConfigureAwait(false);
  1472. }
  1473. catch (Exception ex)
  1474. {
  1475. _logger.ErrorException("Error closing live stream", ex);
  1476. throw;
  1477. }
  1478. finally
  1479. {
  1480. _liveStreamSemaphore.Release();
  1481. }
  1482. }
  1483. public GuideInfo GetGuideInfo()
  1484. {
  1485. var programs = GetPrograms().OrderBy(i => i.StartDate).ToList();
  1486. var startDate = programs.Count == 0 ?
  1487. DateTime.MinValue :
  1488. programs[0].StartDate;
  1489. var endDate = programs.Count == 0 ?
  1490. DateTime.MinValue :
  1491. programs[programs.Count - 1].StartDate;
  1492. return new GuideInfo
  1493. {
  1494. StartDate = startDate,
  1495. EndDate = endDate
  1496. };
  1497. }
  1498. /// <summary>
  1499. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1500. /// </summary>
  1501. public void Dispose()
  1502. {
  1503. Dispose(true);
  1504. }
  1505. private readonly object _disposeLock = new object();
  1506. /// <summary>
  1507. /// Releases unmanaged and - optionally - managed resources.
  1508. /// </summary>
  1509. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1510. protected virtual void Dispose(bool dispose)
  1511. {
  1512. if (dispose)
  1513. {
  1514. lock (_disposeLock)
  1515. {
  1516. foreach (var stream in _openStreams.Values.ToList())
  1517. {
  1518. var task = CloseLiveStream(stream.Info.Id, CancellationToken.None);
  1519. Task.WaitAll(task);
  1520. }
  1521. _openStreams.Clear();
  1522. }
  1523. }
  1524. }
  1525. private async Task<IEnumerable<LiveTvServiceInfo>> GetServiceInfos(CancellationToken cancellationToken)
  1526. {
  1527. var tasks = Services.Select(i => GetServiceInfo(i, cancellationToken));
  1528. return await Task.WhenAll(tasks).ConfigureAwait(false);
  1529. }
  1530. private async Task<LiveTvServiceInfo> GetServiceInfo(ILiveTvService service, CancellationToken cancellationToken)
  1531. {
  1532. var info = new LiveTvServiceInfo
  1533. {
  1534. Name = service.Name
  1535. };
  1536. var tunerIdPrefix = service.GetType().FullName.GetMD5().ToString("N") + "_";
  1537. try
  1538. {
  1539. var statusInfo = await service.GetStatusInfoAsync(cancellationToken).ConfigureAwait(false);
  1540. info.Status = statusInfo.Status;
  1541. info.StatusMessage = statusInfo.StatusMessage;
  1542. info.Version = statusInfo.Version;
  1543. info.HasUpdateAvailable = statusInfo.HasUpdateAvailable;
  1544. info.HomePageUrl = service.HomePageUrl;
  1545. info.Tuners = statusInfo.Tuners.Select(i =>
  1546. {
  1547. string channelName = null;
  1548. if (!string.IsNullOrEmpty(i.ChannelId))
  1549. {
  1550. var internalChannelId = _tvDtoService.GetInternalChannelId(service.Name, i.ChannelId);
  1551. var channel = GetInternalChannel(internalChannelId);
  1552. channelName = channel == null ? null : channel.Name;
  1553. }
  1554. var dto = _tvDtoService.GetTunerInfoDto(service.Name, i, channelName);
  1555. dto.Id = tunerIdPrefix + dto.Id;
  1556. return dto;
  1557. }).ToList();
  1558. }
  1559. catch (Exception ex)
  1560. {
  1561. _logger.ErrorException("Error getting service status info from {0}", ex, service.Name ?? string.Empty);
  1562. info.Status = LiveTvServiceStatus.Unavailable;
  1563. info.StatusMessage = ex.Message;
  1564. }
  1565. return info;
  1566. }
  1567. public async Task<LiveTvInfo> GetLiveTvInfo(CancellationToken cancellationToken)
  1568. {
  1569. var services = await GetServiceInfos(CancellationToken.None).ConfigureAwait(false);
  1570. var servicesList = services.ToList();
  1571. var info = new LiveTvInfo
  1572. {
  1573. Services = servicesList.ToList(),
  1574. IsEnabled = servicesList.Count > 0
  1575. };
  1576. info.EnabledUsers = _userManager.Users
  1577. .Where(IsLiveTvEnabled)
  1578. .Select(i => i.Id.ToString("N"))
  1579. .ToList();
  1580. return info;
  1581. }
  1582. private bool IsLiveTvEnabled(User user)
  1583. {
  1584. return user.Policy.EnableLiveTvAccess && Services.Count > 0;
  1585. }
  1586. public IEnumerable<User> GetEnabledUsers()
  1587. {
  1588. return _userManager.Users
  1589. .Where(IsLiveTvEnabled);
  1590. }
  1591. /// <summary>
  1592. /// Resets the tuner.
  1593. /// </summary>
  1594. /// <param name="id">The identifier.</param>
  1595. /// <param name="cancellationToken">The cancellation token.</param>
  1596. /// <returns>Task.</returns>
  1597. public Task ResetTuner(string id, CancellationToken cancellationToken)
  1598. {
  1599. var parts = id.Split(new[] { '_' }, 2);
  1600. var service = _services.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N"), parts[0], StringComparison.OrdinalIgnoreCase));
  1601. if (service == null)
  1602. {
  1603. throw new ArgumentException("Service not found.");
  1604. }
  1605. return service.ResetTuner(parts[1], cancellationToken);
  1606. }
  1607. public async Task<BaseItemDto> GetLiveTvFolder(string userId, CancellationToken cancellationToken)
  1608. {
  1609. var user = string.IsNullOrEmpty(userId) ? null : _userManager.GetUserById(userId);
  1610. var folder = await GetInternalLiveTvFolder(userId, cancellationToken).ConfigureAwait(false);
  1611. return _dtoService.GetBaseItemDto(folder, new DtoOptions(), user);
  1612. }
  1613. public async Task<Folder> GetInternalLiveTvFolder(string userId, CancellationToken cancellationToken)
  1614. {
  1615. var name = _localization.GetLocalizedString("ViewTypeLiveTV");
  1616. var user = _userManager.GetUserById(userId);
  1617. return await _libraryManager.GetNamedView(user, name, "livetv", "zz_" + name, cancellationToken).ConfigureAwait(false);
  1618. }
  1619. }
  1620. }