LiveTvManager.cs 62 KB

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