From ffd9460d51980a550ef5460e5df4e942b63077a7 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Thu, 23 Jul 2015 12:32:34 -0400 Subject: add hdhomerun auto-discovery --- .../Library/Resolvers/TV/SeriesResolver.cs | 9 +- .../LiveTv/Listings/SchedulesDirect.cs | 2 +- .../LiveTv/TunerHosts/HdHomerun.cs | 230 -------------------- .../TunerHosts/HdHomerun/HdHomerunDiscovery.cs | 114 ++++++++++ .../LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs | 235 +++++++++++++++++++++ .../MediaBrowser.Server.Implementations.csproj | 3 +- 6 files changed, 358 insertions(+), 235 deletions(-) delete mode 100644 MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun.cs create mode 100644 MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunDiscovery.cs create mode 100644 MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs (limited to 'MediaBrowser.Server.Implementations') diff --git a/MediaBrowser.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs b/MediaBrowser.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs index 70ab105b2..f12022dc7 100644 --- a/MediaBrowser.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs +++ b/MediaBrowser.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs @@ -125,7 +125,7 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.TV if ((attributes & FileAttributes.Directory) == FileAttributes.Directory) { - if (IsSeasonFolder(child.FullName, isTvContentType)) + if (IsSeasonFolder(child.FullName, isTvContentType, libraryManager)) { //logger.Debug("{0} is a series because of season folder {1}.", path, child.FullName); return true; @@ -188,10 +188,13 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.TV /// /// The path. /// if set to true [is tv content type]. + /// The library manager. /// true if [is season folder] [the specified path]; otherwise, false. - private static bool IsSeasonFolder(string path, bool isTvContentType) + private static bool IsSeasonFolder(string path, bool isTvContentType, ILibraryManager libraryManager) { - var seasonNumber = new SeasonPathParser(new ExtendedNamingOptions(), new RegexProvider()).Parse(path, isTvContentType, isTvContentType).SeasonNumber; + var namingOptions = ((LibraryManager)libraryManager).GetNamingOptions(); + + var seasonNumber = new SeasonPathParser(namingOptions, new RegexProvider()).Parse(path, isTvContentType, isTvContentType).SeasonNumber; return seasonNumber.HasValue; } diff --git a/MediaBrowser.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/MediaBrowser.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs index 2656397bb..668f023d2 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs @@ -350,7 +350,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.Listings { url = apiUrl + "/image/" + images.data[logoIndex].uri; } - _logger.Debug("URL for image is : " + url); + //_logger.Debug("URL for image is : " + url); } return url; } diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun.cs deleted file mode 100644 index 9aacd0c1e..000000000 --- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun.cs +++ /dev/null @@ -1,230 +0,0 @@ -using MediaBrowser.Common.Configuration; -using MediaBrowser.Common.Net; -using MediaBrowser.Controller.LiveTv; -using MediaBrowser.Model.Dto; -using MediaBrowser.Model.Entities; -using MediaBrowser.Model.LiveTv; -using MediaBrowser.Model.Logging; -using MediaBrowser.Model.MediaInfo; -using MediaBrowser.Model.Serialization; -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; - -namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts -{ - public class HdHomerun : ITunerHost - { - private readonly IHttpClient _httpClient; - private readonly ILogger _logger; - private readonly IJsonSerializer _jsonSerializer; - private readonly IConfigurationManager _config; - - public HdHomerun(IHttpClient httpClient, ILogger logger, IJsonSerializer jsonSerializer, IConfigurationManager config) - { - _httpClient = httpClient; - _logger = logger; - _jsonSerializer = jsonSerializer; - _config = config; - } - - public string Name - { - get { return "HD Homerun"; } - } - - public string Type - { - get { return "hdhomerun"; } - } - - public async Task> GetChannels(TunerHostInfo info, CancellationToken cancellationToken) - { - var options = new HttpRequestOptions - { - Url = string.Format("{0}/lineup.json", GetApiUrl(info)), - CancellationToken = cancellationToken - }; - using (var stream = await _httpClient.Get(options)) - { - var root = _jsonSerializer.DeserializeFromStream>(stream); - - if (root != null) - { - return root.Select(i => new ChannelInfo - { - Name = i.GuideName, - Number = i.GuideNumber.ToString(CultureInfo.InvariantCulture), - Id = i.GuideNumber.ToString(CultureInfo.InvariantCulture), - IsFavorite = i.Favorite - - }); - } - return new List(); - } - } - - public async Task> GetTunerInfos(TunerHostInfo info, CancellationToken cancellationToken) - { - string model = null; - - using (var stream = await _httpClient.Get(new HttpRequestOptions() - { - Url = string.Format("{0}/", GetApiUrl(info)), - CancellationToken = cancellationToken - })) - { - using (var sr = new StreamReader(stream, System.Text.Encoding.UTF8)) - { - while (!sr.EndOfStream) - { - string line = StripXML(sr.ReadLine()); - if (line.StartsWith("Model:")) { model = line.Replace("Model: ", ""); } - //if (line.StartsWith("Device ID:")) { deviceID = line.Replace("Device ID: ", ""); } - //if (line.StartsWith("Firmware:")) { firmware = line.Replace("Firmware: ", ""); } - } - } - } - - using (var stream = await _httpClient.Get(new HttpRequestOptions() - { - Url = string.Format("{0}/tuners.html", GetApiUrl(info)), - CancellationToken = cancellationToken - })) - { - var tuners = new List(); - using (var sr = new StreamReader(stream, System.Text.Encoding.UTF8)) - { - while (!sr.EndOfStream) - { - string line = StripXML(sr.ReadLine()); - if (line.Contains("Channel")) - { - LiveTvTunerStatus status; - var index = line.IndexOf("Channel", StringComparison.OrdinalIgnoreCase); - var name = line.Substring(0, index - 1); - var currentChannel = line.Substring(index + 7); - if (currentChannel != "none") { status = LiveTvTunerStatus.LiveTv; } else { status = LiveTvTunerStatus.Available; } - tuners.Add(new LiveTvTunerInfo() - { - Name = name, - SourceType = string.IsNullOrWhiteSpace(model) ? Name : model, - ProgramName = currentChannel, - Status = status - }); - } - } - } - return tuners; - } - } - - public string GetApiUrl(TunerHostInfo info) - { - var url = info.Url; - - if (!url.StartsWith("http", StringComparison.OrdinalIgnoreCase)) - { - url = "http://" + url; - } - - return url.TrimEnd('/'); - } - - private static string StripXML(string source) - { - char[] buffer = new char[source.Length]; - int bufferIndex = 0; - bool inside = false; - - for (int i = 0; i < source.Length; i++) - { - char let = source[i]; - if (let == '<') - { - inside = true; - continue; - } - if (let == '>') - { - inside = false; - continue; - } - if (!inside) - { - buffer[bufferIndex] = let; - bufferIndex++; - } - } - return new string(buffer, 0, bufferIndex); - } - - private class Channels - { - public string GuideNumber { get; set; } - public string GuideName { get; set; } - public string URL { get; set; } - public bool Favorite { get; set; } - public bool DRM { get; set; } - } - - private LiveTvOptions GetConfiguration() - { - return _config.GetConfiguration("livetv"); - } - - public List GetTunerHosts() - { - return GetConfiguration().TunerHosts.Where(i => string.Equals(i.Type, Type, StringComparison.OrdinalIgnoreCase)).ToList(); - } - - public async Task GetChannelStream(TunerHostInfo info, string channelId, string streamId, CancellationToken cancellationToken) - { - var channels = await GetChannels(info, cancellationToken).ConfigureAwait(false); - var tuners = await GetTunerInfos(info, cancellationToken).ConfigureAwait(false); - - var channel = channels.FirstOrDefault(c => string.Equals(c.Id, channelId, StringComparison.OrdinalIgnoreCase)); - if (channel != null) - { - if (tuners.FindIndex(t => t.Status == LiveTvTunerStatus.Available) >= 0) - { - return new MediaSourceInfo - { - Path = GetApiUrl(info) + "/auto/v" + channelId, - Protocol = MediaProtocol.Http, - MediaStreams = new List - { - new MediaStream - { - Type = MediaStreamType.Video, - // Set the index to -1 because we don't know the exact index of the video stream within the container - Index = -1, - IsInterlaced = true - }, - new MediaStream - { - Type = MediaStreamType.Audio, - // Set the index to -1 because we don't know the exact index of the audio stream within the container - Index = -1 - - } - } - }; - } - - throw new ApplicationException("No tuners avaliable."); - } - throw new ApplicationException("Channel not found."); - } - - - public async Task Validate(TunerHostInfo info) - { - await GetChannels(info, CancellationToken.None).ConfigureAwait(false); - } - } -} diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunDiscovery.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunDiscovery.cs new file mode 100644 index 000000000..41652ae9f --- /dev/null +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunDiscovery.cs @@ -0,0 +1,114 @@ +using MediaBrowser.Common.Configuration; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Dlna; +using MediaBrowser.Controller.LiveTv; +using MediaBrowser.Controller.Plugins; +using MediaBrowser.Model.Extensions; +using MediaBrowser.Model.LiveTv; +using MediaBrowser.Model.Logging; +using System; +using System.Linq; +using System.Threading; + +namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun +{ + public class HdHomerunDiscovery : IServerEntryPoint + { + private readonly IDeviceDiscovery _deviceDiscovery; + private readonly IServerConfigurationManager _config; + private readonly ILogger _logger; + private readonly ILiveTvManager _liveTvManager; + private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1); + + public HdHomerunDiscovery(IDeviceDiscovery deviceDiscovery, IServerConfigurationManager config, ILogger logger, ILiveTvManager liveTvManager) + { + _deviceDiscovery = deviceDiscovery; + _config = config; + _logger = logger; + _liveTvManager = liveTvManager; + } + + public void Run() + { + _deviceDiscovery.DeviceDiscovered += _deviceDiscovery_DeviceDiscovered; + } + + void _deviceDiscovery_DeviceDiscovered(object sender, SsdpMessageEventArgs e) + { + string server = null; + if (e.Headers.TryGetValue("SERVER", out server) && server.IndexOf("HDHomeRun", StringComparison.OrdinalIgnoreCase) != -1) + { + string location; + if (e.Headers.TryGetValue("Location", out location)) + { + _logger.Debug("HdHomerun found at {0}", location); + + // Just get the beginning of the url + Uri uri; + if (Uri.TryCreate(location, UriKind.Absolute, out uri)) + { + var apiUrl = location.Replace(uri.LocalPath, String.Empty, StringComparison.OrdinalIgnoreCase) + .TrimEnd('/'); + + _logger.Debug("HdHomerun api url: {0}", apiUrl); + AddDevice(apiUrl); + } + } + } + } + + private async void AddDevice(string url) + { + await _semaphore.WaitAsync().ConfigureAwait(false); + + try + { + var options = GetConfiguration(); + + if (options.TunerHosts.Any(i => + string.Equals(i.Type, HdHomerunHost.DeviceType, StringComparison.OrdinalIgnoreCase) && + UriEquals(i.Url, url))) + { + return; + } + + await _liveTvManager.SaveTunerHost(new TunerHostInfo + { + Type = HdHomerunHost.DeviceType, + Url = url + + }).ConfigureAwait(false); + } + catch (Exception ex) + { + _logger.ErrorException("Error saving device", ex); + } + finally + { + _semaphore.Release(); + } + } + + private bool UriEquals(string savedUri, string location) + { + if (!savedUri.StartsWith("http", StringComparison.OrdinalIgnoreCase)) + { + savedUri = "http://" + savedUri; + } + + savedUri = savedUri.TrimEnd('/'); + location = location.TrimEnd('/'); + + return string.Equals(location, savedUri, StringComparison.OrdinalIgnoreCase); + } + + private LiveTvOptions GetConfiguration() + { + return _config.GetConfiguration("livetv"); + } + + public void Dispose() + { + } + } +} diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs new file mode 100644 index 000000000..187569ab4 --- /dev/null +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -0,0 +1,235 @@ +using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Net; +using MediaBrowser.Controller.LiveTv; +using MediaBrowser.Model.Dto; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.LiveTv; +using MediaBrowser.Model.Logging; +using MediaBrowser.Model.MediaInfo; +using MediaBrowser.Model.Serialization; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun +{ + public class HdHomerunHost : ITunerHost + { + private readonly IHttpClient _httpClient; + private readonly ILogger _logger; + private readonly IJsonSerializer _jsonSerializer; + private readonly IConfigurationManager _config; + + public HdHomerunHost(IHttpClient httpClient, ILogger logger, IJsonSerializer jsonSerializer, IConfigurationManager config) + { + _httpClient = httpClient; + _logger = logger; + _jsonSerializer = jsonSerializer; + _config = config; + } + + public string Name + { + get { return "HD Homerun"; } + } + + public string Type + { + get { return DeviceType; } + } + + public static string DeviceType + { + get { return "hdhomerun"; } + } + + public async Task> GetChannels(TunerHostInfo info, CancellationToken cancellationToken) + { + var options = new HttpRequestOptions + { + Url = string.Format("{0}/lineup.json", GetApiUrl(info)), + CancellationToken = cancellationToken + }; + using (var stream = await _httpClient.Get(options)) + { + var root = _jsonSerializer.DeserializeFromStream>(stream); + + if (root != null) + { + return root.Select(i => new ChannelInfo + { + Name = i.GuideName, + Number = i.GuideNumber.ToString(CultureInfo.InvariantCulture), + Id = i.GuideNumber.ToString(CultureInfo.InvariantCulture), + IsFavorite = i.Favorite + + }); + } + return new List(); + } + } + + public async Task> GetTunerInfos(TunerHostInfo info, CancellationToken cancellationToken) + { + string model = null; + + using (var stream = await _httpClient.Get(new HttpRequestOptions() + { + Url = string.Format("{0}/", GetApiUrl(info)), + CancellationToken = cancellationToken + })) + { + using (var sr = new StreamReader(stream, System.Text.Encoding.UTF8)) + { + while (!sr.EndOfStream) + { + string line = StripXML(sr.ReadLine()); + if (line.StartsWith("Model:")) { model = line.Replace("Model: ", ""); } + //if (line.StartsWith("Device ID:")) { deviceID = line.Replace("Device ID: ", ""); } + //if (line.StartsWith("Firmware:")) { firmware = line.Replace("Firmware: ", ""); } + } + } + } + + using (var stream = await _httpClient.Get(new HttpRequestOptions() + { + Url = string.Format("{0}/tuners.html", GetApiUrl(info)), + CancellationToken = cancellationToken + })) + { + var tuners = new List(); + using (var sr = new StreamReader(stream, System.Text.Encoding.UTF8)) + { + while (!sr.EndOfStream) + { + string line = StripXML(sr.ReadLine()); + if (line.Contains("Channel")) + { + LiveTvTunerStatus status; + var index = line.IndexOf("Channel", StringComparison.OrdinalIgnoreCase); + var name = line.Substring(0, index - 1); + var currentChannel = line.Substring(index + 7); + if (currentChannel != "none") { status = LiveTvTunerStatus.LiveTv; } else { status = LiveTvTunerStatus.Available; } + tuners.Add(new LiveTvTunerInfo() + { + Name = name, + SourceType = string.IsNullOrWhiteSpace(model) ? Name : model, + ProgramName = currentChannel, + Status = status + }); + } + } + } + return tuners; + } + } + + public string GetApiUrl(TunerHostInfo info) + { + var url = info.Url; + + if (!url.StartsWith("http", StringComparison.OrdinalIgnoreCase)) + { + url = "http://" + url; + } + + return url.TrimEnd('/'); + } + + private static string StripXML(string source) + { + char[] buffer = new char[source.Length]; + int bufferIndex = 0; + bool inside = false; + + for (int i = 0; i < source.Length; i++) + { + char let = source[i]; + if (let == '<') + { + inside = true; + continue; + } + if (let == '>') + { + inside = false; + continue; + } + if (!inside) + { + buffer[bufferIndex] = let; + bufferIndex++; + } + } + return new string(buffer, 0, bufferIndex); + } + + private class Channels + { + public string GuideNumber { get; set; } + public string GuideName { get; set; } + public string URL { get; set; } + public bool Favorite { get; set; } + public bool DRM { get; set; } + } + + private LiveTvOptions GetConfiguration() + { + return _config.GetConfiguration("livetv"); + } + + public List GetTunerHosts() + { + return GetConfiguration().TunerHosts.Where(i => string.Equals(i.Type, Type, StringComparison.OrdinalIgnoreCase)).ToList(); + } + + public async Task GetChannelStream(TunerHostInfo info, string channelId, string streamId, CancellationToken cancellationToken) + { + var channels = await GetChannels(info, cancellationToken).ConfigureAwait(false); + var tuners = await GetTunerInfos(info, cancellationToken).ConfigureAwait(false); + + var channel = channels.FirstOrDefault(c => string.Equals(c.Id, channelId, StringComparison.OrdinalIgnoreCase)); + if (channel != null) + { + if (tuners.FindIndex(t => t.Status == LiveTvTunerStatus.Available) >= 0) + { + return new MediaSourceInfo + { + Path = GetApiUrl(info) + "/auto/v" + channelId, + Protocol = MediaProtocol.Http, + MediaStreams = new List + { + new MediaStream + { + Type = MediaStreamType.Video, + // Set the index to -1 because we don't know the exact index of the video stream within the container + Index = -1, + IsInterlaced = true + }, + new MediaStream + { + Type = MediaStreamType.Audio, + // Set the index to -1 because we don't know the exact index of the audio stream within the container + Index = -1 + + } + } + }; + } + + throw new ApplicationException("No tuners avaliable."); + } + throw new ApplicationException("Channel not found."); + } + + + public async Task Validate(TunerHostInfo info) + { + await GetChannels(info, CancellationToken.None).ConfigureAwait(false); + } + } +} diff --git a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj index dc149318b..c77c112a6 100644 --- a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj +++ b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj @@ -226,7 +226,8 @@ - + + -- cgit v1.2.3