LiveTvManager.cs 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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 System;
  11. using System.Collections.Generic;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace MediaBrowser.Server.Implementations.LiveTv
  17. {
  18. /// <summary>
  19. /// Class LiveTvManager
  20. /// </summary>
  21. public class LiveTvManager : ILiveTvManager
  22. {
  23. private readonly IServerApplicationPaths _appPaths;
  24. private readonly IFileSystem _fileSystem;
  25. private readonly ILogger _logger;
  26. private readonly IItemRepository _itemRepo;
  27. private readonly IImageProcessor _imageProcessor;
  28. private List<Channel> _channels = new List<Channel>();
  29. private readonly List<ILiveTvService> _services = new List<ILiveTvService>();
  30. public LiveTvManager(IServerApplicationPaths appPaths, IFileSystem fileSystem, ILogger logger, IItemRepository itemRepo, IImageProcessor imageProcessor)
  31. {
  32. _appPaths = appPaths;
  33. _fileSystem = fileSystem;
  34. _logger = logger;
  35. _itemRepo = itemRepo;
  36. _imageProcessor = imageProcessor;
  37. }
  38. /// <summary>
  39. /// Gets the services.
  40. /// </summary>
  41. /// <value>The services.</value>
  42. public IReadOnlyList<ILiveTvService> Services
  43. {
  44. get { return _services; }
  45. }
  46. /// <summary>
  47. /// Adds the parts.
  48. /// </summary>
  49. /// <param name="services">The services.</param>
  50. public void AddParts(IEnumerable<ILiveTvService> services)
  51. {
  52. _services.AddRange(services);
  53. }
  54. /// <summary>
  55. /// Gets the channel info dto.
  56. /// </summary>
  57. /// <param name="info">The info.</param>
  58. /// <returns>ChannelInfoDto.</returns>
  59. public ChannelInfoDto GetChannelInfoDto(Channel info)
  60. {
  61. return new ChannelInfoDto
  62. {
  63. Name = info.Name,
  64. ServiceName = info.ServiceName,
  65. ChannelType = info.ChannelType,
  66. ChannelId = info.ChannelId,
  67. Number = info.ChannelNumber,
  68. PrimaryImageTag = GetLogoImageTag(info),
  69. Type = info.GetType().Name,
  70. Id = info.Id.ToString("N")
  71. };
  72. }
  73. private Guid? GetLogoImageTag(Channel info)
  74. {
  75. var path = info.PrimaryImagePath;
  76. if (string.IsNullOrEmpty(path))
  77. {
  78. return null;
  79. }
  80. try
  81. {
  82. return _imageProcessor.GetImageCacheTag(info, ImageType.Primary, path);
  83. }
  84. catch (Exception ex)
  85. {
  86. _logger.ErrorException("Error getting channel image info for {0}", ex, info.Name);
  87. }
  88. return null;
  89. }
  90. public IEnumerable<Channel> GetChannels(ChannelQuery query)
  91. {
  92. return _channels.OrderBy(i =>
  93. {
  94. double number = 0;
  95. if (!string.IsNullOrEmpty(i.ChannelNumber))
  96. {
  97. double.TryParse(i.ChannelNumber, out number);
  98. }
  99. return number;
  100. }).ThenBy(i => i.Name);
  101. }
  102. public Channel GetChannel(string id)
  103. {
  104. var guid = new Guid(id);
  105. return _channels.FirstOrDefault(i => i.Id == guid);
  106. }
  107. internal async Task RefreshChannels(IProgress<double> progress, CancellationToken cancellationToken)
  108. {
  109. // Avoid implicitly captured closure
  110. var currentCancellationToken = cancellationToken;
  111. var tasks = _services.Select(i => i.GetChannelsAsync(currentCancellationToken));
  112. progress.Report(10);
  113. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  114. var allChannels = results.SelectMany(i => i).ToList();
  115. var list = new List<Channel>();
  116. var numComplete = 0;
  117. foreach (var channel in allChannels)
  118. {
  119. try
  120. {
  121. var item = await GetChannel(channel, cancellationToken).ConfigureAwait(false);
  122. list.Add(item);
  123. }
  124. catch (OperationCanceledException)
  125. {
  126. throw;
  127. }
  128. catch (Exception ex)
  129. {
  130. _logger.ErrorException("Error getting channel information for {0}", ex, channel.Name);
  131. }
  132. numComplete++;
  133. double percent = numComplete;
  134. percent /= allChannels.Count;
  135. progress.Report(90 * percent + 10);
  136. }
  137. _channels = list;
  138. }
  139. private async Task<Channel> GetChannel(ChannelInfo channelInfo, CancellationToken cancellationToken)
  140. {
  141. var path = Path.Combine(_appPaths.ItemsByNamePath, "channels", _fileSystem.GetValidFilename(channelInfo.ServiceName), _fileSystem.GetValidFilename(channelInfo.Name));
  142. var fileInfo = new DirectoryInfo(path);
  143. var isNew = false;
  144. if (!fileInfo.Exists)
  145. {
  146. Directory.CreateDirectory(path);
  147. fileInfo = new DirectoryInfo(path);
  148. if (!fileInfo.Exists)
  149. {
  150. throw new IOException("Path not created: " + path);
  151. }
  152. isNew = true;
  153. }
  154. var type = typeof(Channel);
  155. var id = (path + channelInfo.Number).GetMBId(type);
  156. var item = _itemRepo.RetrieveItem(id) as Channel;
  157. if (item == null)
  158. {
  159. item = new Channel
  160. {
  161. Name = channelInfo.Name,
  162. Id = id,
  163. DateCreated = _fileSystem.GetCreationTimeUtc(fileInfo),
  164. DateModified = _fileSystem.GetLastWriteTimeUtc(fileInfo),
  165. Path = path,
  166. ChannelId = channelInfo.Id,
  167. ChannelNumber = channelInfo.Number,
  168. ServiceName = channelInfo.ServiceName
  169. };
  170. isNew = true;
  171. }
  172. // Set this now so we don't cause additional file system access during provider executions
  173. item.ResetResolveArgs(fileInfo);
  174. await item.RefreshMetadata(cancellationToken, forceSave: isNew, resetResolveArgs: false);
  175. return item;
  176. }
  177. }
  178. }