sonarr-repo-only/NzbDrone.Core/Download/Clients/Sabnzbd/SabAutoConfigureService.cs

101 lines
3.1 KiB
C#
Raw Normal View History

2011-04-25 07:42:29 +00:00
using System;
using System.Collections.Generic;
using System.IO;
2011-04-25 07:42:29 +00:00
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
2011-04-25 07:42:29 +00:00
using System.Text.RegularExpressions;
using NLog;
2011-04-25 07:42:29 +00:00
using NzbDrone.Core.Model;
namespace NzbDrone.Core.Download.Clients.Sabnzbd
2011-04-25 07:42:29 +00:00
{
public class SabAutoConfigureService
2011-04-25 07:42:29 +00:00
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
2011-04-25 07:42:29 +00:00
public SabModel AutoConfigureSab()
2011-04-25 07:42:29 +00:00
{
var info = GetConnectionList();
return FindApiKey(info);
2011-04-25 07:42:29 +00:00
}
private List<ConnectionInfoModel> GetConnectionList()
2011-04-25 07:42:29 +00:00
{
IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
var info =
ipProperties.GetActiveTcpListeners().Select(
p =>
new ConnectionInfoModel { Address = p.Address.ToString().Replace("0.0.0.0", "127.0.0.1"), Port = p.Port }).Distinct().
ToList();
info.RemoveAll(i => i.Port == 135);
info.RemoveAll(i => i.Port == 139);
info.RemoveAll(i => i.Port == 445);
info.RemoveAll(i => i.Port == 3389);
info.RemoveAll(i => i.Port == 5900);
info.RemoveAll(i => i.Address.Contains("::"));
info.Reverse();
return info;
}
2011-04-25 07:42:29 +00:00
private SabModel FindApiKey(List<ConnectionInfoModel> info)
{
foreach (var connection in info)
2011-04-25 07:42:29 +00:00
{
var apiKey = GetApiKey(connection.Address, connection.Port);
if (!String.IsNullOrEmpty(apiKey))
return new SabModel
{
Host = connection.Address,
Port = connection.Port,
ApiKey = apiKey
};
2011-04-25 07:42:29 +00:00
}
return null;
}
private string GetApiKey(string ipAddress, int port)
2011-04-25 07:42:29 +00:00
{
var request = String.Format("http://{0}:{1}/config/general/", ipAddress, port);
var result = DownloadString(request);
Regex regex =
new Regex("\\<input\\Wtype\\=\\\"text\\\"\\Wid\\=\\\"apikey\\\"\\Wvalue\\=\\\"(?<apikey>\\w+)\\W",
RegexOptions.IgnoreCase
| RegexOptions.Compiled);
var match = regex.Match(result);
2011-04-25 07:42:29 +00:00
if (match.Success)
{
return match.Groups["apikey"].Value;
}
return String.Empty;
2011-04-25 07:42:29 +00:00
}
private string DownloadString(string url)
2011-04-25 07:42:29 +00:00
{
try
{
var request = WebRequest.Create(url);
request.Timeout = 2000;
2011-04-25 07:42:29 +00:00
var response = request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
return reader.ReadToEnd();
}
catch (Exception ex)
{
Logger.Trace("Failed to get response from: {0}", url);
Logger.Trace(ex.Message, ex);
}
2011-04-25 07:42:29 +00:00
return String.Empty;
2011-04-25 07:42:29 +00:00
}
}
}