LiveTvManager.cs 68 KB

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