LiveTvManager.cs 63 KB

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