LiveTvManager.cs 64 KB

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