LiveTvManager.cs 72 KB

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