添加针对API请求的代理设置

This commit is contained in:
Genteure 2019-08-22 03:07:29 +08:00
parent 406945f28e
commit 6e0ce88e04
5 changed files with 159 additions and 6 deletions

View File

@ -5,6 +5,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace BililiveRecorder.Core
@ -13,7 +14,8 @@ namespace BililiveRecorder.Core
{
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
private static readonly Random random = new Random();
private static readonly HttpClient httpclient;
private static readonly SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1, 1);
private static HttpClient httpclient;
static BililiveAPI()
{
@ -23,6 +25,60 @@ namespace BililiveRecorder.Core
httpclient.DefaultRequestHeaders.Add("User-Agent", Utils.UserAgent);
}
public static async Task ApplyProxySettings(bool useProxy, string address, bool useCredential, string user, string pass)
{
await semaphoreSlim.WaitAsync();
try
{
if (useProxy)
{
try
{
var proxy = new WebProxy
{
Address = new Uri(address),
BypassProxyOnLocal = false,
UseDefaultCredentials = false
};
if (useCredential)
{
proxy.Credentials = new NetworkCredential(userName: user, password: pass);
}
var pclient = new HttpClient(handler: new HttpClientHandler
{
Proxy = proxy,
}, disposeHandler: true)
{
Timeout = TimeSpan.FromSeconds(5)
};
pclient.DefaultRequestHeaders.Add("Accept", "application/json, text/javascript, */*; q=0.01");
pclient.DefaultRequestHeaders.Add("Referer", "https://live.bilibili.com/");
pclient.DefaultRequestHeaders.Add("User-Agent", Utils.UserAgent);
httpclient = pclient;
return;
}
catch (Exception ex)
{
logger.Error(ex, "设置代理时发生错误");
}
}
var cleanclient = new HttpClient { Timeout = TimeSpan.FromSeconds(5) };
cleanclient.DefaultRequestHeaders.Add("Accept", "application/json, text/javascript, */*; q=0.01");
cleanclient.DefaultRequestHeaders.Add("Referer", "https://live.bilibili.com/");
cleanclient.DefaultRequestHeaders.Add("User-Agent", Utils.UserAgent);
httpclient = cleanclient;
}
finally
{
semaphoreSlim.Release();
}
}
/// <summary>
/// 下载json并解析
@ -33,9 +89,17 @@ namespace BililiveRecorder.Core
/// <exception cref="WebException"/>
public static async Task<JObject> HttpGetJsonAsync(string url)
{
var s = await httpclient.GetStringAsync(url);
var j = JObject.Parse(s);
return j;
await semaphoreSlim.WaitAsync();
try
{
var s = await httpclient.GetStringAsync(url);
var j = JObject.Parse(s);
return j;
}
finally
{
semaphoreSlim.Release();
}
}
/// <summary>

View File

@ -92,6 +92,36 @@ namespace BililiveRecorder.Core.Config
[JsonProperty("timing_watchdog_behind")]
public uint TimingWatchdogBehind { get => _timingWatchdogBehind; set => SetField(ref _timingWatchdogBehind, value); }
/// <summary>
/// 是否对API请求使用HTTP代理
/// </summary>
[JsonProperty("proxy_enable")]
public bool UseProxyForApi { get => _useProxyForApi; set => SetField(ref _useProxyForApi, value); }
/// <summary>
/// HTTP代理服务器地址
/// </summary>
[JsonProperty("proxy_address")]
public string ProxyAddress { get => _proxyAddress; set => SetField(ref _proxyAddress, value); }
/// <summary>
/// HTTP代理是否需要身份验证
/// </summary>
[JsonProperty("proxy_auth")]
public bool ProxyRequireCredentials { get => _proxyRequireCredentials; set => SetField(ref _proxyRequireCredentials, value); }
/// <summary>
/// HTTP代理用户名
/// </summary>
[JsonProperty("proxy_user")]
public string ProxyUsername { get => _proxyUsername; set => SetField(ref _proxyUsername, value); }
/// <summary>
/// HTTP代理密码
/// </summary>
[JsonProperty("proxy_pass")]
public string ProxyPassword { get => _proxyPassword; set => SetField(ref _proxyPassword, value); }
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
@ -116,5 +146,11 @@ namespace BililiveRecorder.Core.Config
private uint _timingStreamConnect = 3 * 1000;
private uint _timingDanmakuRetry = 2 * 1000;
private uint _timingCheckInterval = 5 * 60;
private bool _useProxyForApi = false;
private string _proxyAddress = "";
private bool _proxyRequireCredentials = false;
private string _proxyUsername = "";
private string _proxyPassword = "";
}
}

View File

@ -50,6 +50,36 @@ namespace BililiveRecorder.Core
$"O:{e.OldItems?.Cast<IRecordedRoom>()?.Select(rr => rr.RoomId.ToString())?.Aggregate((current, next) => current + "," + next)};" +
$"N:{e.NewItems?.Cast<IRecordedRoom>()?.Select(rr => rr.RoomId.ToString())?.Aggregate((current, next) => current + "," + next)}");
};
var debouncing = new SemaphoreSlim(1, 1);
Config.PropertyChanged += async (sender, e) =>
{
if (e.PropertyName == nameof(Config.UseProxyForApi)
|| e.PropertyName == nameof(Config.ProxyAddress)
|| e.PropertyName == nameof(Config.ProxyRequireCredentials)
|| e.PropertyName == nameof(Config.ProxyUsername)
|| e.PropertyName == nameof(Config.ProxyPassword)
)
{
if (await debouncing.WaitAsync(0))
{
try
{
logger.Debug("设置代理等待...");
await Task.Delay(50);
logger.Debug("设置代理信息...");
await BililiveAPI.ApplyProxySettings(
Config.UseProxyForApi, Config.ProxyAddress,
Config.ProxyRequireCredentials, Config.ProxyUsername, Config.ProxyPassword);
logger.Debug("设置成功");
}
finally
{
debouncing.Release();
}
}
}
};
}
public event PropertyChangedEventHandler PropertyChanged

View File

@ -13,7 +13,7 @@
<Grid.Resources>
<ResourceDictionary>
<DataTemplate x:Key="LogTemplate" >
<TextBlock Text="{Binding}" TextWrapping="Wrap" Cursor="Hand" MouseRightButtonUp="TextBlock_MouseRightButtonUp"/>
<TextBlock Text="{Binding}" TextWrapping="Wrap" MouseRightButtonUp="TextBlock_MouseRightButtonUp"/>
</DataTemplate>
<local:RecordStatusConverter x:Key="RSC"/>
<local:BoolToStringConverter x:Key="RecordStatusConverter" TrueValue="录制中" FalseValue="闲置"/>

View File

@ -8,7 +8,7 @@
xmlns:flv="clr-namespace:BililiveRecorder.FlvProcessor;assembly=BililiveRecorder.FlvProcessor"
mc:Ignorable="d"
ShowInTaskbar="False" ResizeMode="NoResize"
Title="设置 - 录播姬" Height="400" Width="270">
Title="设置 - 录播姬" Height="450" Width="270">
<Window.Resources>
<local:ValueConverterGroup x:Key="EnumToInvertBooleanConverter">
<local:EnumToBooleanConverter/>
@ -30,6 +30,7 @@
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="1*"/>
</Grid.RowDefinitions>
<Grid.Resources>
@ -296,6 +297,28 @@
ConverterParameter={x:Static flv:AutoCuttingMode.BySize}}">根据文件大小(MiB)切割</RadioButton>
</StackPanel>
</Grid>
<Separator Grid.Row="5"/>
<Grid Grid.Row="6" Margin="10,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<CheckBox Grid.ColumnSpan="2" IsChecked="{Binding UseProxyForApi}">除了直播流以外的请求使用 HTTP 代理</CheckBox>
<TextBlock Grid.Row="1">地址:</TextBlock>
<local:ClickSelectTextBox Grid.Row="1" Grid.Column="1" Text="{Binding ProxyAddress,Delay=500,UpdateSourceTrigger=PropertyChanged}"/>
<CheckBox Grid.Row="2" Grid.ColumnSpan="2" Margin="0,5,0,0" IsChecked="{Binding ProxyRequireCredentials}">使用用户名密码验证</CheckBox>
<TextBlock Grid.Row="3">用户名:</TextBlock>
<local:ClickSelectTextBox Grid.Row="3" Grid.Column="1" Text="{Binding ProxyUsername,Delay=500,UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock Grid.Row="4">密码:</TextBlock>
<local:ClickSelectTextBox Grid.Row="4" Grid.Column="1" Text="{Binding ProxyPassword,Delay=500,UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
<!--
<TextBlock Grid.Row="4" Grid.Column="0"></TextBlock>
<StackPanel Grid.Row="4" Grid.Column="1">