LiveTvManager.cs 69 KB

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