LiveTvManager.cs 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774
  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. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(new Guid(query.UserId));
  808. var recordings = await service.GetRecordingsAsync(cancellationToken).ConfigureAwait(false);
  809. if (!string.IsNullOrEmpty(query.ChannelId))
  810. {
  811. var guid = new Guid(query.ChannelId);
  812. var currentServiceName = service.Name;
  813. recordings = recordings
  814. .Where(i => _tvDtoService.GetInternalChannelId(currentServiceName, i.ChannelId) == guid);
  815. }
  816. if (!string.IsNullOrEmpty(query.Id))
  817. {
  818. var guid = new Guid(query.Id);
  819. var currentServiceName = service.Name;
  820. recordings = recordings
  821. .Where(i => _tvDtoService.GetInternalRecordingId(currentServiceName, i.Id) == guid);
  822. }
  823. if (!string.IsNullOrEmpty(query.GroupId))
  824. {
  825. var guid = new Guid(query.GroupId);
  826. recordings = recordings.Where(i => GetRecordingGroupIds(i).Contains(guid));
  827. }
  828. if (query.IsInProgress.HasValue)
  829. {
  830. var val = query.IsInProgress.Value;
  831. recordings = recordings.Where(i => (i.Status == RecordingStatus.InProgress) == val);
  832. }
  833. if (query.Status.HasValue)
  834. {
  835. var val = query.Status.Value;
  836. recordings = recordings.Where(i => (i.Status == val));
  837. }
  838. if (!string.IsNullOrEmpty(query.SeriesTimerId))
  839. {
  840. var guid = new Guid(query.SeriesTimerId);
  841. var currentServiceName = service.Name;
  842. recordings = recordings
  843. .Where(i => _tvDtoService.GetInternalSeriesTimerId(currentServiceName, i.SeriesTimerId) == guid);
  844. }
  845. recordings = recordings.OrderByDescending(i => i.StartDate);
  846. IEnumerable<ILiveTvRecording> entities = await GetEntities(recordings, service.Name, cancellationToken).ConfigureAwait(false);
  847. if (user != null)
  848. {
  849. var currentUser = user;
  850. entities = entities.Where(i => i.IsParentalAllowed(currentUser));
  851. }
  852. var entityList = entities.ToList();
  853. entities = entityList;
  854. if (query.StartIndex.HasValue)
  855. {
  856. entities = entities.Skip(query.StartIndex.Value);
  857. }
  858. if (query.Limit.HasValue)
  859. {
  860. entities = entities.Take(query.Limit.Value);
  861. }
  862. var returnArray = entities
  863. .Select(i =>
  864. {
  865. var channel = string.IsNullOrEmpty(i.RecordingInfo.ChannelId) ? null : GetInternalChannel(_tvDtoService.GetInternalChannelId(service.Name, i.RecordingInfo.ChannelId));
  866. return _tvDtoService.GetRecordingInfoDto(i, channel, service, user);
  867. })
  868. .ToArray();
  869. return new QueryResult<RecordingInfoDto>
  870. {
  871. Items = returnArray,
  872. TotalRecordCount = entityList.Count
  873. };
  874. }
  875. private Task<ILiveTvRecording[]> GetEntities(IEnumerable<RecordingInfo> recordings, string serviceName, CancellationToken cancellationToken)
  876. {
  877. var tasks = recordings.Select(i => GetRecording(i, serviceName, cancellationToken));
  878. return Task.WhenAll(tasks);
  879. }
  880. private IEnumerable<ILiveTvService> GetServices(string serviceName, string channelId)
  881. {
  882. IEnumerable<ILiveTvService> services = _services;
  883. if (string.IsNullOrEmpty(serviceName) && !string.IsNullOrEmpty(channelId))
  884. {
  885. var channel = GetInternalChannel(channelId);
  886. if (channel != null)
  887. {
  888. serviceName = channel.ServiceName;
  889. }
  890. }
  891. if (!string.IsNullOrEmpty(serviceName))
  892. {
  893. services = services.Where(i => string.Equals(i.Name, serviceName, StringComparison.OrdinalIgnoreCase));
  894. }
  895. return services;
  896. }
  897. public async Task<QueryResult<TimerInfoDto>> GetTimers(TimerQuery query, CancellationToken cancellationToken)
  898. {
  899. var service = ActiveService;
  900. var timers = await service.GetTimersAsync(cancellationToken).ConfigureAwait(false);
  901. if (!string.IsNullOrEmpty(query.ChannelId))
  902. {
  903. var guid = new Guid(query.ChannelId);
  904. timers = timers.Where(i => guid == _tvDtoService.GetInternalChannelId(service.Name, i.ChannelId));
  905. }
  906. if (!string.IsNullOrEmpty(query.SeriesTimerId))
  907. {
  908. var guid = new Guid(query.SeriesTimerId);
  909. var currentServiceName = service.Name;
  910. timers = timers
  911. .Where(i => _tvDtoService.GetInternalSeriesTimerId(currentServiceName, i.SeriesTimerId) == guid);
  912. }
  913. var returnList = new List<TimerInfoDto>();
  914. foreach (var i in timers)
  915. {
  916. var program = string.IsNullOrEmpty(i.ProgramId) ?
  917. null :
  918. await GetInternalProgram(_tvDtoService.GetInternalProgramId(service.Name, i.ProgramId).ToString("N"), cancellationToken).ConfigureAwait(false);
  919. var channel = string.IsNullOrEmpty(i.ChannelId) ? null : GetInternalChannel(_tvDtoService.GetInternalChannelId(service.Name, i.ChannelId));
  920. returnList.Add(_tvDtoService.GetTimerInfoDto(i, service, program, channel));
  921. }
  922. var returnArray = returnList
  923. .OrderBy(i => i.StartDate)
  924. .ToArray();
  925. return new QueryResult<TimerInfoDto>
  926. {
  927. Items = returnArray,
  928. TotalRecordCount = returnArray.Length
  929. };
  930. }
  931. public async Task DeleteRecording(string recordingId)
  932. {
  933. var recording = await GetRecording(recordingId, CancellationToken.None).ConfigureAwait(false);
  934. if (recording == null)
  935. {
  936. throw new ResourceNotFoundException(string.Format("Recording with Id {0} not found", recordingId));
  937. }
  938. var service = GetServices(recording.ServiceName, null)
  939. .First();
  940. await service.DeleteRecordingAsync(recording.ExternalId, CancellationToken.None).ConfigureAwait(false);
  941. }
  942. public async Task CancelTimer(string id)
  943. {
  944. var timer = await GetTimer(id, CancellationToken.None).ConfigureAwait(false);
  945. if (timer == null)
  946. {
  947. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  948. }
  949. var service = GetServices(timer.ServiceName, null)
  950. .First();
  951. await service.CancelTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  952. }
  953. public async Task CancelSeriesTimer(string id)
  954. {
  955. var timer = await GetSeriesTimer(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.CancelSeriesTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  963. }
  964. public async Task<RecordingInfoDto> GetRecording(string id, CancellationToken cancellationToken, User user = null)
  965. {
  966. var results = await GetRecordings(new RecordingQuery
  967. {
  968. UserId = user == null ? null : user.Id.ToString("N"),
  969. Id = id
  970. }, cancellationToken).ConfigureAwait(false);
  971. return results.Items.FirstOrDefault();
  972. }
  973. public async Task<TimerInfoDto> GetTimer(string id, CancellationToken cancellationToken)
  974. {
  975. var results = await GetTimers(new TimerQuery(), cancellationToken).ConfigureAwait(false);
  976. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.CurrentCulture));
  977. }
  978. public async Task<SeriesTimerInfoDto> GetSeriesTimer(string id, CancellationToken cancellationToken)
  979. {
  980. var results = await GetSeriesTimers(new SeriesTimerQuery(), cancellationToken).ConfigureAwait(false);
  981. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.CurrentCulture));
  982. }
  983. public async Task<QueryResult<SeriesTimerInfoDto>> GetSeriesTimers(SeriesTimerQuery query, CancellationToken cancellationToken)
  984. {
  985. var service = ActiveService;
  986. var timers = await service.GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false);
  987. if (string.Equals(query.SortBy, "Priority", StringComparison.OrdinalIgnoreCase))
  988. {
  989. timers = query.SortOrder == SortOrder.Descending ?
  990. timers.OrderBy(i => i.Priority).ThenByStringDescending(i => i.Name) :
  991. timers.OrderByDescending(i => i.Priority).ThenByString(i => i.Name);
  992. }
  993. else
  994. {
  995. timers = query.SortOrder == SortOrder.Descending ?
  996. timers.OrderByStringDescending(i => i.Name) :
  997. timers.OrderByString(i => i.Name);
  998. }
  999. var returnArray = timers
  1000. .Select(i =>
  1001. {
  1002. string channelName = null;
  1003. if (!string.IsNullOrEmpty(i.ChannelId))
  1004. {
  1005. var internalChannelId = _tvDtoService.GetInternalChannelId(service.Name, i.ChannelId);
  1006. var channel = GetInternalChannel(internalChannelId);
  1007. channelName = channel == null ? null : channel.Name;
  1008. }
  1009. return _tvDtoService.GetSeriesTimerInfoDto(i, service, channelName);
  1010. })
  1011. .ToArray();
  1012. return new QueryResult<SeriesTimerInfoDto>
  1013. {
  1014. Items = returnArray,
  1015. TotalRecordCount = returnArray.Length
  1016. };
  1017. }
  1018. public async Task<ChannelInfoDto> GetChannel(string id, CancellationToken cancellationToken, User user = null)
  1019. {
  1020. var channel = GetInternalChannel(id);
  1021. var currentProgram = await GetCurrentProgram(channel.ExternalId, cancellationToken).ConfigureAwait(false);
  1022. var dto = _tvDtoService.GetChannelInfoDto(channel, currentProgram, user);
  1023. return dto;
  1024. }
  1025. private async Task<LiveTvProgram> GetCurrentProgram(string externalChannelId, CancellationToken cancellationToken)
  1026. {
  1027. var now = DateTime.UtcNow;
  1028. var program = _programs.Values
  1029. .Where(i => string.Equals(externalChannelId, i.ExternalChannelId, StringComparison.OrdinalIgnoreCase))
  1030. .OrderBy(i => i.StartDate)
  1031. .SkipWhile(i => now >= (i.EndDate ?? DateTime.MinValue))
  1032. .FirstOrDefault();
  1033. if (program != null)
  1034. {
  1035. await RefreshIfNeeded(program, cancellationToken).ConfigureAwait(false);
  1036. }
  1037. return program;
  1038. }
  1039. private async Task<SeriesTimerInfo> GetNewTimerDefaultsInternal(CancellationToken cancellationToken, LiveTvProgram program = null)
  1040. {
  1041. ProgramInfo programInfo = null;
  1042. if (program != null)
  1043. {
  1044. programInfo = new ProgramInfo
  1045. {
  1046. Audio = program.Audio,
  1047. ChannelId = program.ExternalChannelId,
  1048. CommunityRating = program.CommunityRating,
  1049. EndDate = program.EndDate ?? DateTime.MinValue,
  1050. EpisodeTitle = program.EpisodeTitle,
  1051. Genres = program.Genres,
  1052. HasImage = program.HasProviderImage,
  1053. Id = program.ExternalId,
  1054. IsHD = program.IsHD,
  1055. IsKids = program.IsKids,
  1056. IsLive = program.IsLive,
  1057. IsMovie = program.IsMovie,
  1058. IsNews = program.IsNews,
  1059. IsPremiere = program.IsPremiere,
  1060. IsRepeat = program.IsRepeat,
  1061. IsSeries = program.IsSeries,
  1062. IsSports = program.IsSports,
  1063. OriginalAirDate = program.PremiereDate,
  1064. Overview = program.Overview,
  1065. StartDate = program.StartDate,
  1066. ImagePath = program.ProviderImagePath,
  1067. ImageUrl = program.ProviderImageUrl,
  1068. Name = program.Name,
  1069. OfficialRating = program.OfficialRating
  1070. };
  1071. }
  1072. var info = await ActiveService.GetNewTimerDefaultsAsync(cancellationToken, programInfo).ConfigureAwait(false);
  1073. info.Id = null;
  1074. return info;
  1075. }
  1076. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(CancellationToken cancellationToken)
  1077. {
  1078. var info = await GetNewTimerDefaultsInternal(cancellationToken).ConfigureAwait(false);
  1079. var obj = _tvDtoService.GetSeriesTimerInfoDto(info, ActiveService, null);
  1080. return obj;
  1081. }
  1082. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(string programId, CancellationToken cancellationToken)
  1083. {
  1084. var program = await GetInternalProgram(programId, cancellationToken).ConfigureAwait(false);
  1085. var programDto = await GetProgram(programId, cancellationToken).ConfigureAwait(false);
  1086. var defaults = await GetNewTimerDefaultsInternal(cancellationToken, program).ConfigureAwait(false);
  1087. var info = _tvDtoService.GetSeriesTimerInfoDto(defaults, ActiveService, null);
  1088. info.Days = new List<DayOfWeek>
  1089. {
  1090. program.StartDate.ToLocalTime().DayOfWeek
  1091. };
  1092. info.DayPattern = _tvDtoService.GetDayPattern(info.Days);
  1093. info.Name = program.Name;
  1094. info.ChannelId = programDto.ChannelId;
  1095. info.ChannelName = programDto.ChannelName;
  1096. info.StartDate = program.StartDate;
  1097. info.Name = program.Name;
  1098. info.Overview = program.Overview;
  1099. info.ProgramId = programDto.Id;
  1100. info.ExternalProgramId = programDto.ExternalId;
  1101. if (program.EndDate.HasValue)
  1102. {
  1103. info.EndDate = program.EndDate.Value;
  1104. }
  1105. return info;
  1106. }
  1107. public async Task CreateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  1108. {
  1109. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  1110. var info = await _tvDtoService.GetTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  1111. // Set priority from default values
  1112. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  1113. info.Priority = defaultValues.Priority;
  1114. await service.CreateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1115. }
  1116. public async Task CreateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  1117. {
  1118. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  1119. var info = await _tvDtoService.GetSeriesTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  1120. // Set priority from default values
  1121. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  1122. info.Priority = defaultValues.Priority;
  1123. await service.CreateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1124. }
  1125. public async Task UpdateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  1126. {
  1127. var info = await _tvDtoService.GetTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  1128. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  1129. await service.UpdateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1130. }
  1131. public async Task UpdateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  1132. {
  1133. var info = await _tvDtoService.GetSeriesTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  1134. var service = string.IsNullOrEmpty(timer.ServiceName) ? ActiveService : GetServices(timer.ServiceName, null).First();
  1135. await service.UpdateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1136. }
  1137. private IEnumerable<string> GetRecordingGroupNames(RecordingInfo recording)
  1138. {
  1139. var list = new List<string>();
  1140. if (recording.IsSeries)
  1141. {
  1142. list.Add(recording.Name);
  1143. }
  1144. if (recording.IsKids)
  1145. {
  1146. list.Add("Kids");
  1147. }
  1148. if (recording.IsMovie)
  1149. {
  1150. list.Add("Movies");
  1151. }
  1152. if (recording.IsNews)
  1153. {
  1154. list.Add("News");
  1155. }
  1156. if (recording.IsSports)
  1157. {
  1158. list.Add("Sports");
  1159. }
  1160. if (!recording.IsSports && !recording.IsNews && !recording.IsMovie && !recording.IsKids && !recording.IsSeries)
  1161. {
  1162. list.Add("Others");
  1163. }
  1164. return list;
  1165. }
  1166. private List<Guid> GetRecordingGroupIds(RecordingInfo recording)
  1167. {
  1168. return GetRecordingGroupNames(recording).Select(i => i.ToLower()
  1169. .GetMD5())
  1170. .ToList();
  1171. }
  1172. public async Task<QueryResult<RecordingGroupDto>> GetRecordingGroups(RecordingGroupQuery query, CancellationToken cancellationToken)
  1173. {
  1174. var recordingResult = await GetRecordings(new RecordingQuery
  1175. {
  1176. UserId = query.UserId
  1177. }, cancellationToken).ConfigureAwait(false);
  1178. var recordings = recordingResult.Items;
  1179. var groups = new List<RecordingGroupDto>();
  1180. var series = recordings
  1181. .Where(i => i.IsSeries)
  1182. .ToLookup(i => i.Name, StringComparer.OrdinalIgnoreCase)
  1183. .ToList();
  1184. groups.AddRange(series.OrderByString(i => i.Key).Select(i => new RecordingGroupDto
  1185. {
  1186. Name = i.Key,
  1187. RecordingCount = i.Count()
  1188. }));
  1189. groups.Add(new RecordingGroupDto
  1190. {
  1191. Name = "Kids",
  1192. RecordingCount = recordings.Count(i => i.IsKids)
  1193. });
  1194. groups.Add(new RecordingGroupDto
  1195. {
  1196. Name = "Movies",
  1197. RecordingCount = recordings.Count(i => i.IsMovie)
  1198. });
  1199. groups.Add(new RecordingGroupDto
  1200. {
  1201. Name = "News",
  1202. RecordingCount = recordings.Count(i => i.IsNews)
  1203. });
  1204. groups.Add(new RecordingGroupDto
  1205. {
  1206. Name = "Sports",
  1207. RecordingCount = recordings.Count(i => i.IsSports)
  1208. });
  1209. groups.Add(new RecordingGroupDto
  1210. {
  1211. Name = "Others",
  1212. RecordingCount = recordings.Count(i => !i.IsSports && !i.IsNews && !i.IsMovie && !i.IsKids && !i.IsSeries)
  1213. });
  1214. groups = groups
  1215. .Where(i => i.RecordingCount > 0)
  1216. .ToList();
  1217. foreach (var group in groups)
  1218. {
  1219. group.Id = group.Name.ToLower().GetMD5().ToString("N");
  1220. }
  1221. return new QueryResult<RecordingGroupDto>
  1222. {
  1223. Items = groups.ToArray(),
  1224. TotalRecordCount = groups.Count
  1225. };
  1226. }
  1227. public async Task CloseLiveStream(string id, CancellationToken cancellationToken)
  1228. {
  1229. await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  1230. var service = ActiveService;
  1231. _logger.Info("Closing live stream from {0}, stream Id: {1}", service.Name, id);
  1232. try
  1233. {
  1234. await service.CloseLiveStream(id, cancellationToken).ConfigureAwait(false);
  1235. LiveStreamInfo removed;
  1236. _openStreams.TryRemove(id, out removed);
  1237. }
  1238. catch (Exception ex)
  1239. {
  1240. _logger.ErrorException("Error closing live stream", ex);
  1241. throw;
  1242. }
  1243. finally
  1244. {
  1245. _liveStreamSemaphore.Release();
  1246. }
  1247. }
  1248. public GuideInfo GetGuideInfo()
  1249. {
  1250. var programs = _programs.ToList();
  1251. var startDate = _programs.Count == 0 ? DateTime.MinValue :
  1252. programs.Select(i => i.Value.StartDate).Min();
  1253. var endDate = programs.Count == 0 ? DateTime.MinValue :
  1254. programs.Select(i => i.Value.StartDate).Max();
  1255. return new GuideInfo
  1256. {
  1257. StartDate = startDate,
  1258. EndDate = endDate
  1259. };
  1260. }
  1261. /// <summary>
  1262. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1263. /// </summary>
  1264. public void Dispose()
  1265. {
  1266. Dispose(true);
  1267. }
  1268. private readonly object _disposeLock = new object();
  1269. /// <summary>
  1270. /// Releases unmanaged and - optionally - managed resources.
  1271. /// </summary>
  1272. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1273. protected virtual void Dispose(bool dispose)
  1274. {
  1275. if (dispose)
  1276. {
  1277. lock (_disposeLock)
  1278. {
  1279. foreach (var stream in _openStreams.Values.ToList())
  1280. {
  1281. var task = CloseLiveStream(stream.Id, CancellationToken.None);
  1282. Task.WaitAll(task);
  1283. }
  1284. _openStreams.Clear();
  1285. }
  1286. }
  1287. }
  1288. private async Task<IEnumerable<LiveTvServiceInfo>> GetServiceInfos(CancellationToken cancellationToken)
  1289. {
  1290. var tasks = Services.Select(i => GetServiceInfo(i, cancellationToken));
  1291. return await Task.WhenAll(tasks).ConfigureAwait(false);
  1292. }
  1293. private async Task<LiveTvServiceInfo> GetServiceInfo(ILiveTvService service, CancellationToken cancellationToken)
  1294. {
  1295. var info = new LiveTvServiceInfo
  1296. {
  1297. Name = service.Name
  1298. };
  1299. try
  1300. {
  1301. var statusInfo = await service.GetStatusInfoAsync(cancellationToken).ConfigureAwait(false);
  1302. info.Status = statusInfo.Status;
  1303. info.StatusMessage = statusInfo.StatusMessage;
  1304. info.Version = statusInfo.Version;
  1305. info.HasUpdateAvailable = statusInfo.HasUpdateAvailable;
  1306. info.HomePageUrl = service.HomePageUrl;
  1307. info.Tuners = statusInfo.Tuners.Select(i =>
  1308. {
  1309. string channelName = null;
  1310. if (!string.IsNullOrEmpty(i.ChannelId))
  1311. {
  1312. var internalChannelId = _tvDtoService.GetInternalChannelId(service.Name, i.ChannelId);
  1313. var channel = GetInternalChannel(internalChannelId);
  1314. channelName = channel == null ? null : channel.Name;
  1315. }
  1316. return _tvDtoService.GetTunerInfoDto(service.Name, i, channelName);
  1317. }).ToList();
  1318. }
  1319. catch (Exception ex)
  1320. {
  1321. _logger.ErrorException("Error getting service status info from {0}", ex, service.Name ?? string.Empty);
  1322. info.Status = LiveTvServiceStatus.Unavailable;
  1323. info.StatusMessage = ex.Message;
  1324. }
  1325. return info;
  1326. }
  1327. public async Task<LiveTvInfo> GetLiveTvInfo(CancellationToken cancellationToken)
  1328. {
  1329. var services = await GetServiceInfos(CancellationToken.None).ConfigureAwait(false);
  1330. var servicesList = services.ToList();
  1331. var activeServiceInfo = ActiveService == null ? null :
  1332. servicesList.FirstOrDefault(i => string.Equals(i.Name, ActiveService.Name, StringComparison.OrdinalIgnoreCase));
  1333. var info = new LiveTvInfo
  1334. {
  1335. Services = servicesList.ToList(),
  1336. ActiveServiceName = activeServiceInfo == null ? null : activeServiceInfo.Name,
  1337. IsEnabled = ActiveService != null,
  1338. Status = activeServiceInfo == null ? LiveTvServiceStatus.Unavailable : activeServiceInfo.Status,
  1339. StatusMessage = activeServiceInfo == null ? null : activeServiceInfo.StatusMessage
  1340. };
  1341. info.EnabledUsers = _userManager.Users
  1342. .Where(i => i.Configuration.EnableLiveTvAccess && info.IsEnabled)
  1343. .Select(i => i.Id.ToString("N"))
  1344. .ToList();
  1345. return info;
  1346. }
  1347. public IEnumerable<User> GetEnabledUsers()
  1348. {
  1349. var service = ActiveService;
  1350. return _userManager.Users
  1351. .Where(i => i.Configuration.EnableLiveTvAccess && service != null);
  1352. }
  1353. /// <summary>
  1354. /// Resets the tuner.
  1355. /// </summary>
  1356. /// <param name="id">The identifier.</param>
  1357. /// <param name="cancellationToken">The cancellation token.</param>
  1358. /// <returns>Task.</returns>
  1359. public Task ResetTuner(string id, CancellationToken cancellationToken)
  1360. {
  1361. return ActiveService.ResetTuner(id, cancellationToken);
  1362. }
  1363. public async Task<BaseItemDto> GetLiveTvFolder(string userId, CancellationToken cancellationToken)
  1364. {
  1365. var user = string.IsNullOrEmpty(userId) ? null : _userManager.GetUserById(new Guid(userId));
  1366. // Get everything
  1367. var fields = Enum.GetNames(typeof(ItemFields)).Select(i => (ItemFields)Enum.Parse(typeof(ItemFields), i, true)).ToList();
  1368. var folder = await GetInternalLiveTvFolder(userId, cancellationToken).ConfigureAwait(false);
  1369. return _dtoService.GetBaseItemDto(folder, fields, user);
  1370. }
  1371. public async Task<Folder> GetInternalLiveTvFolder(string userId, CancellationToken cancellationToken)
  1372. {
  1373. var name = _localization.GetLocalizedString("ViewTypeLiveTV");
  1374. return await _libraryManager.GetNamedView(name, "livetv", "zz_" + name, cancellationToken).ConfigureAwait(false);
  1375. }
  1376. }
  1377. }