BaseTunerHost.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text.Json;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using MediaBrowser.Common.Configuration;
  11. using MediaBrowser.Controller.Configuration;
  12. using MediaBrowser.Controller.Library;
  13. using MediaBrowser.Controller.LiveTv;
  14. using MediaBrowser.Model.Dto;
  15. using MediaBrowser.Model.IO;
  16. using MediaBrowser.Model.LiveTv;
  17. using Microsoft.Extensions.Caching.Memory;
  18. using Microsoft.Extensions.Logging;
  19. namespace Emby.Server.Implementations.LiveTv.TunerHosts
  20. {
  21. public abstract class BaseTunerHost
  22. {
  23. protected readonly IServerConfigurationManager Config;
  24. protected readonly ILogger<BaseTunerHost> Logger;
  25. protected readonly IFileSystem FileSystem;
  26. private readonly IMemoryCache _memoryCache;
  27. protected BaseTunerHost(IServerConfigurationManager config, ILogger<BaseTunerHost> logger, IFileSystem fileSystem, IMemoryCache memoryCache)
  28. {
  29. Config = config;
  30. Logger = logger;
  31. _memoryCache = memoryCache;
  32. FileSystem = fileSystem;
  33. }
  34. public virtual bool IsSupported => true;
  35. protected abstract Task<List<ChannelInfo>> GetChannelsInternal(TunerHostInfo tuner, CancellationToken cancellationToken);
  36. public abstract string Type { get; }
  37. public async Task<List<ChannelInfo>> GetChannels(TunerHostInfo tuner, bool enableCache, CancellationToken cancellationToken)
  38. {
  39. var key = tuner.Id;
  40. if (enableCache && !string.IsNullOrEmpty(key) && _memoryCache.TryGetValue(key, out List<ChannelInfo> cache))
  41. {
  42. return cache;
  43. }
  44. var list = await GetChannelsInternal(tuner, cancellationToken).ConfigureAwait(false);
  45. // logger.LogInformation("Channels from {0}: {1}", tuner.Url, JsonSerializer.SerializeToString(list));
  46. if (!string.IsNullOrEmpty(key) && list.Count > 0)
  47. {
  48. _memoryCache.Set(key, list);
  49. }
  50. return list;
  51. }
  52. protected virtual List<TunerHostInfo> GetTunerHosts()
  53. {
  54. return GetConfiguration().TunerHosts
  55. .Where(i => string.Equals(i.Type, Type, StringComparison.OrdinalIgnoreCase))
  56. .ToList();
  57. }
  58. public async Task<List<ChannelInfo>> GetChannels(bool enableCache, CancellationToken cancellationToken)
  59. {
  60. var list = new List<ChannelInfo>();
  61. var hosts = GetTunerHosts();
  62. foreach (var host in hosts)
  63. {
  64. var channelCacheFile = Path.Combine(Config.ApplicationPaths.CachePath, host.Id + "_channels");
  65. try
  66. {
  67. var channels = await GetChannels(host, enableCache, cancellationToken).ConfigureAwait(false);
  68. var newChannels = channels.Where(i => !list.Any(l => string.Equals(i.Id, l.Id, StringComparison.OrdinalIgnoreCase))).ToList();
  69. list.AddRange(newChannels);
  70. if (!enableCache)
  71. {
  72. try
  73. {
  74. Directory.CreateDirectory(Path.GetDirectoryName(channelCacheFile));
  75. await using var writeStream = File.OpenWrite(channelCacheFile);
  76. await JsonSerializer.SerializeAsync(writeStream, channels, cancellationToken: cancellationToken).ConfigureAwait(false);
  77. }
  78. catch (IOException)
  79. {
  80. }
  81. }
  82. }
  83. catch (Exception ex)
  84. {
  85. Logger.LogError(ex, "Error getting channel list");
  86. if (enableCache)
  87. {
  88. try
  89. {
  90. await using var readStream = File.OpenRead(channelCacheFile);
  91. var channels = await JsonSerializer.DeserializeAsync<List<ChannelInfo>>(readStream, cancellationToken: cancellationToken)
  92. .ConfigureAwait(false);
  93. list.AddRange(channels);
  94. }
  95. catch (IOException)
  96. {
  97. }
  98. }
  99. }
  100. }
  101. return list;
  102. }
  103. protected abstract Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(TunerHostInfo tuner, ChannelInfo channel, CancellationToken cancellationToken);
  104. public async Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(string channelId, CancellationToken cancellationToken)
  105. {
  106. if (string.IsNullOrEmpty(channelId))
  107. {
  108. throw new ArgumentNullException(nameof(channelId));
  109. }
  110. if (IsValidChannelId(channelId))
  111. {
  112. var hosts = GetTunerHosts();
  113. foreach (var host in hosts)
  114. {
  115. try
  116. {
  117. var channels = await GetChannels(host, true, cancellationToken).ConfigureAwait(false);
  118. var channelInfo = channels.FirstOrDefault(i => string.Equals(i.Id, channelId, StringComparison.OrdinalIgnoreCase));
  119. if (channelInfo != null)
  120. {
  121. return await GetChannelStreamMediaSources(host, channelInfo, cancellationToken).ConfigureAwait(false);
  122. }
  123. }
  124. catch (Exception ex)
  125. {
  126. Logger.LogError(ex, "Error getting channels");
  127. }
  128. }
  129. }
  130. return new List<MediaSourceInfo>();
  131. }
  132. protected abstract Task<ILiveStream> GetChannelStream(TunerHostInfo tuner, ChannelInfo channel, string streamId, List<ILiveStream> currentLiveStreams, CancellationToken cancellationToken);
  133. public async Task<ILiveStream> GetChannelStream(string channelId, string streamId, List<ILiveStream> currentLiveStreams, CancellationToken cancellationToken)
  134. {
  135. if (string.IsNullOrEmpty(channelId))
  136. {
  137. throw new ArgumentNullException(nameof(channelId));
  138. }
  139. if (!IsValidChannelId(channelId))
  140. {
  141. throw new FileNotFoundException();
  142. }
  143. var hosts = GetTunerHosts();
  144. var hostsWithChannel = new List<Tuple<TunerHostInfo, ChannelInfo>>();
  145. foreach (var host in hosts)
  146. {
  147. try
  148. {
  149. var channels = await GetChannels(host, true, cancellationToken).ConfigureAwait(false);
  150. var channelInfo = channels.FirstOrDefault(i => string.Equals(i.Id, channelId, StringComparison.OrdinalIgnoreCase));
  151. if (channelInfo != null)
  152. {
  153. hostsWithChannel.Add(new Tuple<TunerHostInfo, ChannelInfo>(host, channelInfo));
  154. }
  155. }
  156. catch (Exception ex)
  157. {
  158. Logger.LogError(ex, "Error getting channels");
  159. }
  160. }
  161. foreach (var hostTuple in hostsWithChannel)
  162. {
  163. var host = hostTuple.Item1;
  164. var channelInfo = hostTuple.Item2;
  165. try
  166. {
  167. var liveStream = await GetChannelStream(host, channelInfo, streamId, currentLiveStreams, cancellationToken).ConfigureAwait(false);
  168. var startTime = DateTime.UtcNow;
  169. await liveStream.Open(cancellationToken).ConfigureAwait(false);
  170. var endTime = DateTime.UtcNow;
  171. Logger.LogInformation("Live stream opened after {0}ms", (endTime - startTime).TotalMilliseconds);
  172. return liveStream;
  173. }
  174. catch (Exception ex)
  175. {
  176. Logger.LogError(ex, "Error opening tuner");
  177. }
  178. }
  179. throw new LiveTvConflictException();
  180. }
  181. protected virtual string ChannelIdPrefix => Type + "_";
  182. protected virtual bool IsValidChannelId(string channelId)
  183. {
  184. if (string.IsNullOrEmpty(channelId))
  185. {
  186. throw new ArgumentNullException(nameof(channelId));
  187. }
  188. return channelId.StartsWith(ChannelIdPrefix, StringComparison.OrdinalIgnoreCase);
  189. }
  190. protected LiveTvOptions GetConfiguration()
  191. {
  192. return Config.GetConfiguration<LiveTvOptions>("livetv");
  193. }
  194. }
  195. }