LiveTvManager.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Controller;
  4. using MediaBrowser.Controller.Drawing;
  5. using MediaBrowser.Controller.LiveTv;
  6. using MediaBrowser.Controller.Persistence;
  7. using MediaBrowser.Model.Entities;
  8. using MediaBrowser.Model.LiveTv;
  9. using MediaBrowser.Model.Logging;
  10. using MediaBrowser.Model.Querying;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. namespace MediaBrowser.Server.Implementations.LiveTv
  18. {
  19. /// <summary>
  20. /// Class LiveTvManager
  21. /// </summary>
  22. public class LiveTvManager : ILiveTvManager
  23. {
  24. private readonly IServerApplicationPaths _appPaths;
  25. private readonly IFileSystem _fileSystem;
  26. private readonly ILogger _logger;
  27. private readonly IItemRepository _itemRepo;
  28. private readonly IImageProcessor _imageProcessor;
  29. private readonly List<ILiveTvService> _services = new List<ILiveTvService>();
  30. private List<Channel> _channels = new List<Channel>();
  31. private List<ProgramInfoDto> _programs = new List<ProgramInfoDto>();
  32. private List<RecordingInfoDto> _recordings = new List<RecordingInfoDto>();
  33. private readonly SemaphoreSlim _updateSemaphore = new SemaphoreSlim(1, 1);
  34. public LiveTvManager(IServerApplicationPaths appPaths, IFileSystem fileSystem, ILogger logger, IItemRepository itemRepo, IImageProcessor imageProcessor)
  35. {
  36. _appPaths = appPaths;
  37. _fileSystem = fileSystem;
  38. _logger = logger;
  39. _itemRepo = itemRepo;
  40. _imageProcessor = imageProcessor;
  41. }
  42. /// <summary>
  43. /// Gets the services.
  44. /// </summary>
  45. /// <value>The services.</value>
  46. public IReadOnlyList<ILiveTvService> Services
  47. {
  48. get { return _services; }
  49. }
  50. /// <summary>
  51. /// Adds the parts.
  52. /// </summary>
  53. /// <param name="services">The services.</param>
  54. public void AddParts(IEnumerable<ILiveTvService> services)
  55. {
  56. _services.AddRange(services);
  57. }
  58. /// <summary>
  59. /// Gets the channel info dto.
  60. /// </summary>
  61. /// <param name="info">The info.</param>
  62. /// <returns>ChannelInfoDto.</returns>
  63. public ChannelInfoDto GetChannelInfoDto(Channel info)
  64. {
  65. return new ChannelInfoDto
  66. {
  67. Name = info.Name,
  68. ServiceName = info.ServiceName,
  69. ChannelType = info.ChannelType,
  70. Number = info.ChannelNumber,
  71. PrimaryImageTag = GetLogoImageTag(info),
  72. Type = info.GetType().Name,
  73. Id = info.Id.ToString("N"),
  74. MediaType = info.MediaType
  75. };
  76. }
  77. private ILiveTvService GetService(ChannelInfo channel)
  78. {
  79. return _services.FirstOrDefault(i => string.Equals(channel.ServiceName, i.Name, StringComparison.OrdinalIgnoreCase));
  80. }
  81. private Guid? GetLogoImageTag(Channel info)
  82. {
  83. var path = info.PrimaryImagePath;
  84. if (string.IsNullOrEmpty(path))
  85. {
  86. return null;
  87. }
  88. try
  89. {
  90. return _imageProcessor.GetImageCacheTag(info, ImageType.Primary, path);
  91. }
  92. catch (Exception ex)
  93. {
  94. _logger.ErrorException("Error getting channel image info for {0}", ex, info.Name);
  95. }
  96. return null;
  97. }
  98. public QueryResult<ChannelInfoDto> GetChannels(ChannelQuery query)
  99. {
  100. var channels = _channels.OrderBy(i =>
  101. {
  102. double number = 0;
  103. if (!string.IsNullOrEmpty(i.ChannelNumber))
  104. {
  105. double.TryParse(i.ChannelNumber, out number);
  106. }
  107. return number;
  108. }).ThenBy(i => i.Name)
  109. .Select(GetChannelInfoDto)
  110. .ToArray();
  111. return new QueryResult<ChannelInfoDto>
  112. {
  113. Items = channels,
  114. TotalRecordCount = channels.Length
  115. };
  116. }
  117. public Channel GetChannel(string id)
  118. {
  119. var guid = new Guid(id);
  120. return _channels.FirstOrDefault(i => i.Id == guid);
  121. }
  122. private ProgramInfoDto GetProgramInfoDto(ProgramInfo program, Channel channel)
  123. {
  124. var id = GetInternalProgramIdId(channel.ServiceName, program.Id).ToString("N");
  125. return new ProgramInfoDto
  126. {
  127. ChannelId = channel.Id.ToString("N"),
  128. Description = program.Description,
  129. EndDate = program.EndDate,
  130. Genres = program.Genres,
  131. ExternalId = program.Id,
  132. Id = id,
  133. Name = program.Name,
  134. ServiceName = channel.ServiceName,
  135. StartDate = program.StartDate
  136. };
  137. }
  138. private Guid GetInternalChannelId(string serviceName, string externalChannelId)
  139. {
  140. var name = serviceName + externalChannelId;
  141. return name.ToLower().GetMBId(typeof(Channel));
  142. }
  143. private Guid GetInternalProgramIdId(string serviceName, string externalProgramId)
  144. {
  145. var name = serviceName + externalProgramId;
  146. return name.ToLower().GetMD5();
  147. }
  148. private async Task<Channel> GetChannel(ChannelInfo channelInfo, CancellationToken cancellationToken)
  149. {
  150. var path = Path.Combine(_appPaths.ItemsByNamePath, "channels", _fileSystem.GetValidFilename(channelInfo.ServiceName), _fileSystem.GetValidFilename(channelInfo.Name));
  151. var fileInfo = new DirectoryInfo(path);
  152. var isNew = false;
  153. if (!fileInfo.Exists)
  154. {
  155. Directory.CreateDirectory(path);
  156. fileInfo = new DirectoryInfo(path);
  157. if (!fileInfo.Exists)
  158. {
  159. throw new IOException("Path not created: " + path);
  160. }
  161. isNew = true;
  162. }
  163. var id = GetInternalChannelId(channelInfo.ServiceName, channelInfo.Id);
  164. var item = _itemRepo.RetrieveItem(id) as Channel;
  165. if (item == null)
  166. {
  167. item = new Channel
  168. {
  169. Name = channelInfo.Name,
  170. Id = id,
  171. DateCreated = _fileSystem.GetCreationTimeUtc(fileInfo),
  172. DateModified = _fileSystem.GetLastWriteTimeUtc(fileInfo),
  173. Path = path,
  174. ChannelId = channelInfo.Id,
  175. ChannelNumber = channelInfo.Number,
  176. ServiceName = channelInfo.ServiceName
  177. };
  178. isNew = true;
  179. }
  180. // Set this now so we don't cause additional file system access during provider executions
  181. item.ResetResolveArgs(fileInfo);
  182. await item.RefreshMetadata(cancellationToken, forceSave: isNew, resetResolveArgs: false);
  183. return item;
  184. }
  185. public QueryResult<ProgramInfoDto> GetPrograms(ProgramQuery query)
  186. {
  187. IEnumerable<ProgramInfoDto> programs = _programs
  188. .OrderBy(i => i.StartDate)
  189. .ThenBy(i => i.EndDate);
  190. if (!string.IsNullOrEmpty(query.ServiceName))
  191. {
  192. programs = programs.Where(i => string.Equals(i.ServiceName, query.ServiceName, StringComparison.OrdinalIgnoreCase));
  193. }
  194. if (query.ChannelIdList.Length > 0)
  195. {
  196. var guids = query.ChannelIdList.Select(i => new Guid(i)).ToList();
  197. programs = programs.Where(i => guids.Contains(new Guid(i.ChannelId)));
  198. }
  199. var returnArray = programs.ToArray();
  200. return new QueryResult<ProgramInfoDto>
  201. {
  202. Items = returnArray,
  203. TotalRecordCount = returnArray.Length
  204. };
  205. }
  206. internal async Task RefreshChannels(IProgress<double> progress, CancellationToken cancellationToken)
  207. {
  208. await _updateSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  209. try
  210. {
  211. await RefreshChannelsInternal(progress, cancellationToken).ConfigureAwait(false);
  212. }
  213. finally
  214. {
  215. _updateSemaphore.Release();
  216. }
  217. await RefreshRecordings(new Progress<double>(), cancellationToken).ConfigureAwait(false);
  218. }
  219. private async Task RefreshChannelsInternal(IProgress<double> progress, CancellationToken cancellationToken)
  220. {
  221. // Avoid implicitly captured closure
  222. var currentCancellationToken = cancellationToken;
  223. var channelTasks = _services.Select(i => i.GetChannelsAsync(currentCancellationToken));
  224. progress.Report(10);
  225. var results = await Task.WhenAll(channelTasks).ConfigureAwait(false);
  226. var allChannels = results.SelectMany(i => i).ToList();
  227. var list = new List<Channel>();
  228. var programs = new List<ProgramInfoDto>();
  229. var numComplete = 0;
  230. foreach (var channelInfo in allChannels)
  231. {
  232. try
  233. {
  234. var item = await GetChannel(channelInfo, cancellationToken).ConfigureAwait(false);
  235. var service = GetService(channelInfo);
  236. var channelPrograms = await service.GetProgramsAsync(channelInfo.Id, cancellationToken).ConfigureAwait(false);
  237. programs.AddRange(channelPrograms.Select(program => GetProgramInfoDto(program, item)));
  238. list.Add(item);
  239. }
  240. catch (OperationCanceledException)
  241. {
  242. throw;
  243. }
  244. catch (Exception ex)
  245. {
  246. _logger.ErrorException("Error getting channel information for {0}", ex, channelInfo.Name);
  247. }
  248. numComplete++;
  249. double percent = numComplete;
  250. percent /= allChannels.Count;
  251. progress.Report(90 * percent + 10);
  252. }
  253. _programs = programs;
  254. _channels = list;
  255. }
  256. internal async Task RefreshRecordings(IProgress<double> progress, CancellationToken cancellationToken)
  257. {
  258. await _updateSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  259. try
  260. {
  261. await RefreshRecordingsInternal(progress, cancellationToken).ConfigureAwait(false);
  262. }
  263. finally
  264. {
  265. _updateSemaphore.Release();
  266. }
  267. }
  268. private async Task RefreshRecordingsInternal(IProgress<double> progress, CancellationToken cancellationToken)
  269. {
  270. var list = new List<RecordingInfoDto>();
  271. foreach (var service in _services)
  272. {
  273. var recordings = await GetRecordings(service, cancellationToken).ConfigureAwait(false);
  274. list.AddRange(recordings);
  275. }
  276. _recordings = list;
  277. }
  278. private async Task<IEnumerable<RecordingInfoDto>> GetRecordings(ILiveTvService service, CancellationToken cancellationToken)
  279. {
  280. var recordings = await service.GetRecordingsAsync(cancellationToken).ConfigureAwait(false);
  281. return recordings.Select(i => GetRecordingInfoDto(i, service));
  282. }
  283. private RecordingInfoDto GetRecordingInfoDto(RecordingInfo info, ILiveTvService service)
  284. {
  285. var id = service.Name + info.ChannelId + info.Id;
  286. id = id.GetMD5().ToString("N");
  287. var dto = new RecordingInfoDto
  288. {
  289. ChannelName = info.ChannelName,
  290. Description = info.Description,
  291. EndDate = info.EndDate,
  292. Name = info.Name,
  293. IsRecurring = info.IsRecurring,
  294. StartDate = info.StartDate,
  295. Id = id,
  296. ExternalId = info.Id,
  297. ChannelId = GetInternalChannelId(service.Name, info.ChannelId).ToString("N")
  298. };
  299. if (!string.IsNullOrEmpty(info.ProgramId))
  300. {
  301. dto.ProgramId = GetInternalProgramIdId(service.Name, info.ProgramId).ToString("N");
  302. }
  303. return dto;
  304. }
  305. }
  306. }