Try to add LegacyDownloader which might help a tiny bit for Win 7/8... might

This commit is contained in:
niksedk 2023-05-08 18:33:10 +02:00
parent e04d17bb67
commit d58593ddc0
26 changed files with 408 additions and 141 deletions

View File

@ -21,4 +21,5 @@
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002ECSharpPlaceAttributeOnSameLineMigration/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002ECSharpPlaceAttributeOnSameLineMigration/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EMigrateBlankLinesAroundFieldToBlankLinesAroundProperty/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EMigrateBlankLinesAroundFieldToBlankLinesAroundProperty/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EMigrateThisQualifierSettings/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EMigrateThisQualifierSettings/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Downloader/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Nikse/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary> <s:Boolean x:Key="/Default/UserDictionary/Words/=Nikse/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>

View File

@ -1,110 +0,0 @@
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace Nikse.SubtitleEdit.Core.Common
{
public static class HttpClientHelper
{
public static HttpClient MakeHttpClient()
{
return new HttpClient(GetHttpClientHandler(Configuration.Settings.Proxy));
}
public static HttpClientHandler GetHttpClientHandler(ProxySettings proxySettings)
{
var handler = new HttpClientHandler();
if (!string.IsNullOrEmpty(proxySettings.ProxyAddress))
{
handler.Proxy = new WebProxy(proxySettings.ProxyAddress);
handler.UseProxy = true;
}
if (proxySettings.UseDefaultCredentials)
{
handler.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
handler.Credentials = CredentialCache.DefaultNetworkCredentials;
}
else if (!string.IsNullOrEmpty(proxySettings.UserName) && !string.IsNullOrEmpty(proxySettings.ProxyAddress))
{
var networkCredential = string.IsNullOrWhiteSpace(proxySettings.Domain) ? new NetworkCredential(proxySettings.UserName, proxySettings.Password) : new NetworkCredential(proxySettings.UserName, proxySettings.Password, proxySettings.Domain);
var credentialCache = new CredentialCache
{
{
new Uri(proxySettings.ProxyAddress),
proxySettings.AuthType,
networkCredential
}
};
handler.Credentials = credentialCache;
}
return handler;
}
public static async Task DownloadAsync(this HttpClient client, string requestUri, Stream destination, IProgress<float> progress = null, CancellationToken cancellationToken = default)
{
try
{
client.Timeout = Timeout.InfiniteTimeSpan;
using (var response = await client.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead, cancellationToken))
{
var contentLength = response.Content.Headers.ContentLength;
using (var downloadStream = await response.Content.ReadAsStreamAsync())
{
if (progress == null || !contentLength.HasValue)
{
await downloadStream.CopyToAsync(destination);
return;
}
// Convert absolute progress (bytes downloaded) into relative progress (0% - 100%)
var relativeProgress = new Progress<long>(totalBytes => progress.Report((float)totalBytes / contentLength.Value));
// Use extension method to report progress while downloading
await CopyToAsync(downloadStream, destination, 81920, relativeProgress, cancellationToken);
progress.Report(1);
}
}
}
catch (Exception e)
{
SeLogger.Error(e, "DownloadAsync failed");
throw;
}
}
private static async Task CopyToAsync(Stream source, Stream destination, int bufferSize, IProgress<long> progress = null, CancellationToken cancellationToken = default)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
if (destination == null)
{
throw new ArgumentNullException(nameof(destination));
}
if (bufferSize < 0)
{
throw new ArgumentOutOfRangeException(nameof(bufferSize));
}
var buffer = new byte[bufferSize];
long totalBytesRead = 0;
int bytesRead;
while ((bytesRead = await source.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0)
{
await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
totalBytesRead += bytesRead;
progress?.Report(totalBytesRead);
}
}
}
}

View File

@ -809,7 +809,7 @@ namespace Nikse.SubtitleEdit.Core.Common
EbuStlNewLineRows = 2; EbuStlNewLineRows = 2;
PacVerticalTop = 1; PacVerticalTop = 1;
PacVerticalCenter = 5; PacVerticalCenter = 6;
PacVerticalBottom = 11; PacVerticalBottom = 11;
DvdStudioProHeader = @"$VertAlign = Bottom DvdStudioProHeader = @"$VertAlign = Bottom
@ -1470,6 +1470,7 @@ $HorzAlign = Center
public bool DarkThemeShowListViewGridLines { get; set; } public bool DarkThemeShowListViewGridLines { get; set; }
public bool ShowBetaStuff { get; set; } public bool ShowBetaStuff { get; set; }
public bool DebugTranslationSync { get; set; } public bool DebugTranslationSync { get; set; }
public bool UseLegacyDownloader { get; set; }
public GeneralSettings() public GeneralSettings()
{ {
@ -4479,6 +4480,12 @@ $HorzAlign = Center
settings.General.DebugTranslationSync = Convert.ToBoolean(subNode.InnerText.Trim(), CultureInfo.InvariantCulture); settings.General.DebugTranslationSync = Convert.ToBoolean(subNode.InnerText.Trim(), CultureInfo.InvariantCulture);
} }
subNode = node.SelectSingleNode("UseLegacyDownloader");
if (subNode != null)
{
settings.General.UseLegacyDownloader = Convert.ToBoolean(subNode.InnerText.Trim(), CultureInfo.InvariantCulture);
}
subNode = node.SelectSingleNode("NewEmptyDefaultMs"); subNode = node.SelectSingleNode("NewEmptyDefaultMs");
if (subNode != null) if (subNode != null)
{ {
@ -10456,6 +10463,7 @@ $HorzAlign = Center
textWriter.WriteElementString("DarkThemeShowListViewGridLines", settings.General.DarkThemeShowListViewGridLines.ToString(CultureInfo.InvariantCulture)); textWriter.WriteElementString("DarkThemeShowListViewGridLines", settings.General.DarkThemeShowListViewGridLines.ToString(CultureInfo.InvariantCulture));
textWriter.WriteElementString("ShowBetaStuff", settings.General.ShowBetaStuff.ToString(CultureInfo.InvariantCulture)); textWriter.WriteElementString("ShowBetaStuff", settings.General.ShowBetaStuff.ToString(CultureInfo.InvariantCulture));
textWriter.WriteElementString("DebugTranslationSync", settings.General.DebugTranslationSync.ToString(CultureInfo.InvariantCulture)); textWriter.WriteElementString("DebugTranslationSync", settings.General.DebugTranslationSync.ToString(CultureInfo.InvariantCulture));
textWriter.WriteElementString("UseLegacyDownloader", settings.General.UseLegacyDownloader.ToString(CultureInfo.InvariantCulture));
textWriter.WriteElementString("NewEmptyDefaultMs", settings.General.NewEmptyDefaultMs.ToString(CultureInfo.InvariantCulture)); textWriter.WriteElementString("NewEmptyDefaultMs", settings.General.NewEmptyDefaultMs.ToString(CultureInfo.InvariantCulture));
textWriter.WriteEndElement(); textWriter.WriteEndElement();

View File

@ -1,4 +1,5 @@
using Nikse.SubtitleEdit.Core.Common; using Nikse.SubtitleEdit.Core.Common;
using Nikse.SubtitleEdit.Core.Http;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -92,7 +93,7 @@ namespace Nikse.SubtitleEdit.Core.Forms
{ {
try try
{ {
using (var httpClient = HttpClientHelper.MakeHttpClient()) using (var httpClient = DownloaderFactory.MakeHttpClient())
{ {
_changeLog = httpClient.GetStringAsync(ChangeLogUrl).Result; _changeLog = httpClient.GetStringAsync(ChangeLogUrl).Result;
} }

View File

@ -0,0 +1,54 @@
using System;
using System.Net;
using System.Net.Http;
using Nikse.SubtitleEdit.Core.Common;
namespace Nikse.SubtitleEdit.Core.Http
{
public static class DownloaderFactory
{
public static IDownloader MakeHttpClient()
{
var httpClient = new HttpClient(GetHttpClientHandler(Configuration.Settings.Proxy));
if (Configuration.Settings.General.UseLegacyDownloader)
{
return new LegacyDownloader(httpClient);
}
return new HttpClientDownloader(httpClient);
}
public static HttpClientHandler GetHttpClientHandler(ProxySettings proxySettings)
{
var handler = new HttpClientHandler();
if (!string.IsNullOrEmpty(proxySettings.ProxyAddress))
{
handler.Proxy = new WebProxy(proxySettings.ProxyAddress);
handler.UseProxy = true;
}
if (proxySettings.UseDefaultCredentials)
{
handler.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
handler.Credentials = CredentialCache.DefaultNetworkCredentials;
}
else if (!string.IsNullOrEmpty(proxySettings.UserName) && !string.IsNullOrEmpty(proxySettings.ProxyAddress))
{
var networkCredential = string.IsNullOrWhiteSpace(proxySettings.Domain) ? new NetworkCredential(proxySettings.UserName, proxySettings.Password) : new NetworkCredential(proxySettings.UserName, proxySettings.Password, proxySettings.Domain);
var credentialCache = new CredentialCache
{
{
new Uri(proxySettings.ProxyAddress),
proxySettings.AuthType,
networkCredential
}
};
handler.Credentials = credentialCache;
}
return handler;
}
}
}

View File

@ -0,0 +1,109 @@
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using Nikse.SubtitleEdit.Core.Common;
namespace Nikse.SubtitleEdit.Core.Http
{
public class HttpClientDownloader : IDownloader
{
private readonly HttpClient _httpClient;
public HttpClientDownloader(HttpClient httpClient)
{
_httpClient = httpClient;
}
public Uri BaseAddress
{
get => _httpClient.BaseAddress;
set => _httpClient.BaseAddress = value;
}
public HttpRequestHeaders DefaultRequestHeaders => _httpClient.DefaultRequestHeaders;
public Task<HttpResponseMessage> PostAsync(string uri, StringContent stringContent)
{
return _httpClient.PostAsync(uri, stringContent);
}
public Task<string> GetStringAsync(string url)
{
return _httpClient.GetStringAsync(url);
}
public async Task DownloadAsync(string requestUri, Stream destination, IProgress<float> progress = null, CancellationToken cancellationToken = default)
{
try
{
_httpClient.Timeout = Timeout.InfiniteTimeSpan;
using (var response = await _httpClient.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead, cancellationToken))
{
var contentLength = response.Content.Headers.ContentLength;
using (var downloadStream = await response.Content.ReadAsStreamAsync())
{
if (progress == null || !contentLength.HasValue)
{
await downloadStream.CopyToAsync(destination);
return;
}
// Convert absolute progress (bytes downloaded) into relative progress (0% - 100%)
var relativeProgress = new Progress<long>(totalBytes => progress.Report((float)totalBytes / contentLength.Value));
// Use extension method to report progress while downloading
await CopyToAsync(downloadStream, destination, 81920, relativeProgress, cancellationToken);
progress.Report(1);
}
}
}
catch (Exception e)
{
SeLogger.Error(e, $"DownloadAsync failed - {requestUri}");
if (Environment.OSVersion.Version.Major < 10)
{
Configuration.Settings.General.UseLegacyDownloader = true;
SeLogger.Error("Switching to legacy downloader due to old OS!");
}
throw;
}
}
public static async Task CopyToAsync(Stream source, Stream destination, int bufferSize, IProgress<long> progress = null, CancellationToken cancellationToken = default)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
if (destination == null)
{
throw new ArgumentNullException(nameof(destination));
}
if (bufferSize < 0)
{
throw new ArgumentOutOfRangeException(nameof(bufferSize));
}
var buffer = new byte[bufferSize];
long totalBytesRead = 0;
int bytesRead;
while ((bytesRead = await source.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0)
{
await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
totalBytesRead += bytesRead;
progress?.Report(totalBytesRead);
}
}
public void Dispose()
{
_httpClient?.Dispose();
}
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
namespace Nikse.SubtitleEdit.Core.Http
{
public interface IDownloader : IDisposable
{
Task DownloadAsync(string requestUri, Stream destination, IProgress<float> progress = null, CancellationToken cancellationToken = default);
Uri BaseAddress { get; set; }
HttpRequestHeaders DefaultRequestHeaders { get; }
Task<HttpResponseMessage> PostAsync(string uri, StringContent stringContent);
Task<string> GetStringAsync(string url);
}
}

View File

@ -0,0 +1,167 @@
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using Nikse.SubtitleEdit.Core.Common;
namespace Nikse.SubtitleEdit.Core.Http
{
public class LegacyDownloader : IDownloader
{
public Task DownloadAsync(string requestUri, Stream destination, IProgress<float> progress = null, CancellationToken cancellationToken = default)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
return Task.Factory.StartNew(delegate
{
try
{
const int bufferSize = 4096;
var request = (HttpWebRequest)HttpWebRequest.Create(requestUri);
request.Timeout = Timeout.Infinite;
var response = (HttpWebResponse)request.GetResponse();
var responseStream = response.GetResponseStream();
var tempFileName = Path.GetTempFileName();
var fileStream = new FileStream(tempFileName, FileMode.OpenOrCreate, FileAccess.Write);
var buff = new byte[bufferSize];
int bytesRead;
long totalBytesRead = 0;
while ((bytesRead = responseStream.Read(buff, 0, bufferSize)) > 0 && !cancellationToken.IsCancellationRequested)
{
fileStream.Write(buff, 0, bytesRead);
fileStream.Flush();
totalBytesRead += bytesRead;
if (progress != null && response.ContentLength > 0)
{
progress.Report(totalBytesRead / (float)response.ContentLength);
}
}
fileStream.Close();
responseStream.Close();
var fs = new FileStream(tempFileName, FileMode.Open);
CopyTo(fs, destination, 2048);
fs.Close();
try
{
File.Delete(tempFileName);
}
catch
{
// ignore
}
}
catch (Exception exception)
{
SeLogger.Error(exception, $"Error downloading {requestUri}");
throw;
}
}, cancellationToken);
}
private readonly HttpClient _httpClient;
public LegacyDownloader(HttpClient httpClient)
{
_httpClient = httpClient;
}
public Uri BaseAddress
{
get => _httpClient.BaseAddress;
set => _httpClient.BaseAddress = value;
}
public HttpRequestHeaders DefaultRequestHeaders => _httpClient.DefaultRequestHeaders;
public Task<HttpResponseMessage> PostAsync(string uri, StringContent stringContent)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
return _httpClient.PostAsync(uri, stringContent);
}
public async Task<string> GetStringAsync(string url)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
var webClient = new WebClient { Proxy = GetProxy() };
foreach (var header in _httpClient.DefaultRequestHeaders)
{
foreach (var v in header.Value)
{
webClient.Headers.Add(header.Key, v);
}
}
return await Task.Run(() => webClient.DownloadStringTaskAsync(new Uri(url))).ConfigureAwait(false);
}
public void Dispose()
{
_httpClient?.Dispose();
}
public static void CopyTo(Stream source, Stream destination, int bufferSize)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
if (destination == null)
{
throw new ArgumentNullException(nameof(destination));
}
if (bufferSize < 0)
{
throw new ArgumentOutOfRangeException(nameof(bufferSize));
}
var buffer = new byte[bufferSize];
var bytesRead = int.MaxValue;
while (bytesRead != 0)
{
if (bytesRead != int.MaxValue)
{
destination.Write(buffer, 0, bytesRead);
}
bytesRead = source.Read(buffer, 0, buffer.Length);
}
}
public static WebProxy GetProxy()
{
if (string.IsNullOrEmpty(Configuration.Settings.Proxy.ProxyAddress))
{
return null;
}
var proxy = new WebProxy(Configuration.Settings.Proxy.ProxyAddress);
if (!string.IsNullOrEmpty(Configuration.Settings.Proxy.UserName))
{
if (string.IsNullOrEmpty(Configuration.Settings.Proxy.Domain))
{
proxy.Credentials = new NetworkCredential(Configuration.Settings.Proxy.UserName, Configuration.Settings.Proxy.DecodePassword());
}
else
{
proxy.Credentials = new NetworkCredential(Configuration.Settings.Proxy.UserName, Configuration.Settings.Proxy.DecodePassword(), Configuration.Settings.Proxy.Domain);
}
}
else
{
proxy.UseDefaultCredentials = true;
}
return proxy;
}
}
}

View File

@ -1,4 +1,5 @@
using Nikse.SubtitleEdit.Core.Common; using Nikse.SubtitleEdit.Core.Common;
using Nikse.SubtitleEdit.Core.Http;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -14,13 +15,14 @@ namespace Nikse.SubtitleEdit.Core.Translate.Service
/// </summary> /// </summary>
public class GoogleTranslator1 : ITranslationStrategy public class GoogleTranslator1 : ITranslationStrategy
{ {
private readonly HttpClient _httpClient; private readonly IDownloader _httpClient;
private const char SplitChar = '\n'; private const char SplitChar = '\n';
public GoogleTranslator1() public GoogleTranslator1()
{ {
_httpClient = HttpClientHelper.MakeHttpClient(); var x = new HttpClient();
_httpClient = DownloaderFactory.MakeHttpClient();
_httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"); _httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36");
_httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=UTF-8"); _httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=UTF-8");
_httpClient.BaseAddress = new Uri("https://translate.googleapis.com/"); _httpClient.BaseAddress = new Uri("https://translate.googleapis.com/");

View File

@ -1,4 +1,5 @@
using Nikse.SubtitleEdit.Core.Common; using Nikse.SubtitleEdit.Core.Common;
using Nikse.SubtitleEdit.Core.Http;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net; using System.Net;
@ -15,7 +16,7 @@ namespace Nikse.SubtitleEdit.Core.Translate.Service
public class GoogleTranslator2 : ITranslationStrategy public class GoogleTranslator2 : ITranslationStrategy
{ {
private readonly string _apiKey; private readonly string _apiKey;
private readonly HttpClient _httpClient; private readonly IDownloader _httpClient;
public string GetName() public string GetName()
{ {
@ -35,7 +36,7 @@ namespace Nikse.SubtitleEdit.Core.Translate.Service
public GoogleTranslator2(string apiKey) public GoogleTranslator2(string apiKey)
{ {
_apiKey = apiKey; _apiKey = apiKey;
_httpClient = HttpClientHelper.MakeHttpClient(); _httpClient = DownloaderFactory.MakeHttpClient();
_httpClient.BaseAddress = new Uri("https://translation.googleapis.com/language/translate/v2/"); _httpClient.BaseAddress = new Uri("https://translation.googleapis.com/language/translate/v2/");
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
} }

View File

@ -1,4 +1,5 @@
using Nikse.SubtitleEdit.Core.Common; using Nikse.SubtitleEdit.Core.Common;
using Nikse.SubtitleEdit.Core.Http;
using Nikse.SubtitleEdit.Core.SubtitleFormats; using Nikse.SubtitleEdit.Core.SubtitleFormats;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -18,13 +19,13 @@ namespace Nikse.SubtitleEdit.Core.Translate.Service
{ {
private readonly string _apiKey; private readonly string _apiKey;
private readonly string _projectNumberOrId; private readonly string _projectNumberOrId;
private readonly HttpClient _httpClient; private readonly IDownloader _httpClient;
public GoogleTranslator3(string apiKey, string projectNumberOrId) public GoogleTranslator3(string apiKey, string projectNumberOrId)
{ {
_apiKey = apiKey; _apiKey = apiKey;
_projectNumberOrId = projectNumberOrId; _projectNumberOrId = projectNumberOrId;
_httpClient = HttpClientHelper.MakeHttpClient(); _httpClient = DownloaderFactory.MakeHttpClient();
_httpClient.BaseAddress = new Uri("https://translation.googleapis.com/v3/"); _httpClient.BaseAddress = new Uri("https://translation.googleapis.com/v3/");
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
} }

View File

@ -1,4 +1,5 @@
using Nikse.SubtitleEdit.Core.Common; using Nikse.SubtitleEdit.Core.Common;
using Nikse.SubtitleEdit.Core.Http;
using Nikse.SubtitleEdit.Core.SubtitleFormats; using Nikse.SubtitleEdit.Core.SubtitleFormats;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -22,7 +23,7 @@ namespace Nikse.SubtitleEdit.Core.Translate.Service
private static List<TranslationPair> _translationPairs; private static List<TranslationPair> _translationPairs;
private readonly string _accessToken; private readonly string _accessToken;
private readonly string _category; private readonly string _category;
private HttpClient _httpClient; private IDownloader _httpClient;
public MicrosoftTranslationService(string apiKey, string tokenEndpoint, string category) public MicrosoftTranslationService(string apiKey, string tokenEndpoint, string category)
{ {
@ -38,11 +39,11 @@ namespace Nikse.SubtitleEdit.Core.Translate.Service
} }
} }
private HttpClient GetTranslateClient() private IDownloader GetTranslateClient()
{ {
if (_httpClient == null) if (_httpClient == null)
{ {
_httpClient = HttpClientHelper.MakeHttpClient(); _httpClient = DownloaderFactory.MakeHttpClient();
_httpClient.BaseAddress = new Uri("https://api.cognitive.microsofttranslator.com/"); _httpClient.BaseAddress = new Uri("https://api.cognitive.microsofttranslator.com/");
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken);
@ -53,7 +54,7 @@ namespace Nikse.SubtitleEdit.Core.Translate.Service
private static string GetAccessToken(string apiKey, string tokenEndpoint) private static string GetAccessToken(string apiKey, string tokenEndpoint)
{ {
var httpClient = HttpClientHelper.MakeHttpClient(); var httpClient = DownloaderFactory.MakeHttpClient();
httpClient.DefaultRequestHeaders httpClient.DefaultRequestHeaders
.Accept .Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json")); .Add(new MediaTypeWithQualityHeaderValue("application/json"));
@ -69,7 +70,7 @@ namespace Nikse.SubtitleEdit.Core.Translate.Service
return _translationPairs; return _translationPairs;
} }
using (var httpClient = HttpClientHelper.MakeHttpClient()) using (var httpClient = DownloaderFactory.MakeHttpClient())
{ {
httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"); httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36");
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=UTF-8"); httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=UTF-8");

View File

@ -1,4 +1,5 @@
using Nikse.SubtitleEdit.Core.Common; using Nikse.SubtitleEdit.Core.Common;
using Nikse.SubtitleEdit.Core.Http;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Drawing; using System.Drawing;
@ -19,7 +20,7 @@ namespace Nikse.SubtitleEdit.Core.VobSub.Ocr.Service
public class GoogleCloudVisionApi : IOcrStrategy public class GoogleCloudVisionApi : IOcrStrategy
{ {
private readonly string _apiKey; private readonly string _apiKey;
private readonly HttpClient _httpClient; private readonly IDownloader _httpClient;
public string GetName() public string GetName()
{ {
@ -152,7 +153,7 @@ namespace Nikse.SubtitleEdit.Core.VobSub.Ocr.Service
public GoogleCloudVisionApi(string apiKey) public GoogleCloudVisionApi(string apiKey)
{ {
_apiKey = apiKey; _apiKey = apiKey;
_httpClient = HttpClientHelper.MakeHttpClient(); _httpClient = DownloaderFactory.MakeHttpClient();
_httpClient.BaseAddress = new Uri("https://vision.googleapis.com/v1/images:annotate"); _httpClient.BaseAddress = new Uri("https://vision.googleapis.com/v1/images:annotate");
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
} }

View File

@ -5,6 +5,7 @@ using System.Threading;
using System.Windows.Forms; using System.Windows.Forms;
using Nikse.SubtitleEdit.Core.AudioToText; using Nikse.SubtitleEdit.Core.AudioToText;
using Nikse.SubtitleEdit.Core.Common; using Nikse.SubtitleEdit.Core.Common;
using Nikse.SubtitleEdit.Core.Http;
using Nikse.SubtitleEdit.Logic; using Nikse.SubtitleEdit.Logic;
namespace Nikse.SubtitleEdit.Forms.AudioToText namespace Nikse.SubtitleEdit.Forms.AudioToText
@ -69,7 +70,7 @@ namespace Nikse.SubtitleEdit.Forms.AudioToText
buttonDownload.Enabled = false; buttonDownload.Enabled = false;
Refresh(); Refresh();
Cursor = Cursors.WaitCursor; Cursor = Cursors.WaitCursor;
var httpClient = HttpClientHelper.MakeHttpClient(); var httpClient = DownloaderFactory.MakeHttpClient();
using (var downloadStream = new MemoryStream()) using (var downloadStream = new MemoryStream())
{ {
var downloadTask = httpClient.DownloadAsync(url, downloadStream, new Progress<float>((progress) => var downloadTask = httpClient.DownloadAsync(url, downloadStream, new Progress<float>((progress) =>

View File

@ -6,6 +6,7 @@ using System.Linq;
using System.Threading; using System.Threading;
using System.Windows.Forms; using System.Windows.Forms;
using Nikse.SubtitleEdit.Core.AudioToText; using Nikse.SubtitleEdit.Core.AudioToText;
using Nikse.SubtitleEdit.Core.Http;
namespace Nikse.SubtitleEdit.Forms.AudioToText namespace Nikse.SubtitleEdit.Forms.AudioToText
{ {
@ -81,13 +82,14 @@ namespace Nikse.SubtitleEdit.Forms.AudioToText
try try
{ {
var httpClient = HttpClientHelper.MakeHttpClient(); var httpClient = DownloaderFactory.MakeHttpClient();
using (var downloadStream = new MemoryStream()) using (var downloadStream = new MemoryStream())
{ {
var downloadTask = httpClient.DownloadAsync(downloadUrl, downloadStream, new Progress<float>((progress) => var downloadTask = httpClient.DownloadAsync(downloadUrl, downloadStream, new Progress<float>((progress) =>
{ {
var pct = (int)Math.Round(progress * 100.0, MidpointRounding.AwayFromZero); var pct = (int)Math.Round(progress * 100.0, MidpointRounding.AwayFromZero);
labelPleaseWait.Text = LanguageSettings.Current.General.PleaseWait + " " + pct + "%"; labelPleaseWait.Text = LanguageSettings.Current.General.PleaseWait + " " + pct + "%";
labelPleaseWait.Refresh();
}), _cancellationTokenSource.Token); }), _cancellationTokenSource.Token);
while (!downloadTask.IsCompleted && !downloadTask.IsCanceled) while (!downloadTask.IsCompleted && !downloadTask.IsCanceled)

View File

@ -1,5 +1,5 @@
using Nikse.SubtitleEdit.Core.AudioToText; using Nikse.SubtitleEdit.Core.AudioToText;
using Nikse.SubtitleEdit.Core.Common; using Nikse.SubtitleEdit.Core.Http;
using Nikse.SubtitleEdit.Logic; using Nikse.SubtitleEdit.Logic;
using System; using System;
using System.IO; using System.IO;
@ -102,7 +102,7 @@ namespace Nikse.SubtitleEdit.Forms.AudioToText
foreach (var url in LastDownloadedModel.Urls) foreach (var url in LastDownloadedModel.Urls)
{ {
var httpClient = HttpClientHelper.MakeHttpClient(); var httpClient = DownloaderFactory.MakeHttpClient();
currentDownloadUrl = url; currentDownloadUrl = url;
_downloadFileName = MakeDownloadFileName(LastDownloadedModel, url) + ".$$$"; _downloadFileName = MakeDownloadFileName(LastDownloadedModel, url) + ".$$$";
labelFileName.Text = url.Split('/').Last(); labelFileName.Text = url.Split('/').Last();

View File

@ -1,4 +1,5 @@
using Nikse.SubtitleEdit.Core.Common; using Nikse.SubtitleEdit.Core.Common;
using Nikse.SubtitleEdit.Core.Http;
using Nikse.SubtitleEdit.Logic; using Nikse.SubtitleEdit.Logic;
using System; using System;
using System.IO; using System.IO;
@ -53,7 +54,7 @@ namespace Nikse.SubtitleEdit.Forms
labelPleaseWait.Text = LanguageSettings.Current.General.PleaseWait; labelPleaseWait.Text = LanguageSettings.Current.General.PleaseWait;
buttonOK.Enabled = false; buttonOK.Enabled = false;
Cursor = Cursors.WaitCursor; Cursor = Cursors.WaitCursor;
var httpClient = HttpClientHelper.MakeHttpClient(); var httpClient = DownloaderFactory.MakeHttpClient();
using (var downloadStream = new MemoryStream()) using (var downloadStream = new MemoryStream())
{ {
var downloadTask = httpClient.DownloadAsync(url, downloadStream, new Progress<float>((progress) => var downloadTask = httpClient.DownloadAsync(url, downloadStream, new Progress<float>((progress) =>

View File

@ -1,4 +1,5 @@
using Nikse.SubtitleEdit.Core.Common; using Nikse.SubtitleEdit.Core.Common;
using Nikse.SubtitleEdit.Core.Http;
using Nikse.SubtitleEdit.Logic; using Nikse.SubtitleEdit.Logic;
using System; using System;
using System.IO; using System.IO;
@ -62,7 +63,7 @@ namespace Nikse.SubtitleEdit.Forms
Refresh(); Refresh();
Cursor = Cursors.WaitCursor; Cursor = Cursors.WaitCursor;
var httpClient = HttpClientHelper.MakeHttpClient(); var httpClient = DownloaderFactory.MakeHttpClient();
using (var downloadStream = new MemoryStream()) using (var downloadStream = new MemoryStream())
{ {
var downloadTask = httpClient.DownloadAsync(VoskUrl, downloadStream, new Progress<float>((progress) => var downloadTask = httpClient.DownloadAsync(VoskUrl, downloadStream, new Progress<float>((progress) =>

View File

@ -1,4 +1,5 @@
using Nikse.SubtitleEdit.Core.Common; using Nikse.SubtitleEdit.Core.Common;
using Nikse.SubtitleEdit.Core.Http;
using Nikse.SubtitleEdit.Logic; using Nikse.SubtitleEdit.Logic;
using System; using System;
using System.IO; using System.IO;
@ -53,7 +54,7 @@ namespace Nikse.SubtitleEdit.Forms
buttonOK.Enabled = false; buttonOK.Enabled = false;
Refresh(); Refresh();
Cursor = Cursors.WaitCursor; Cursor = Cursors.WaitCursor;
var httpClient = HttpClientHelper.MakeHttpClient(); var httpClient = DownloaderFactory.MakeHttpClient();
using (var downloadStream = new MemoryStream()) using (var downloadStream = new MemoryStream())
{ {
var downloadTask = httpClient.DownloadAsync(Url, downloadStream, new Progress<float>((progress) => var downloadTask = httpClient.DownloadAsync(Url, downloadStream, new Progress<float>((progress) =>

View File

@ -1,4 +1,5 @@
using Nikse.SubtitleEdit.Core.Common; using Nikse.SubtitleEdit.Core.Common;
using Nikse.SubtitleEdit.Core.Http;
using Nikse.SubtitleEdit.Logic; using Nikse.SubtitleEdit.Logic;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -174,7 +175,7 @@ namespace Nikse.SubtitleEdit.Forms
Refresh(); Refresh();
Cursor = Cursors.WaitCursor; Cursor = Cursors.WaitCursor;
var httpClient = HttpClientHelper.MakeHttpClient(); var httpClient = DownloaderFactory.MakeHttpClient();
using (var downloadStream = new MemoryStream()) using (var downloadStream = new MemoryStream())
{ {
var downloadTask = httpClient.DownloadAsync(_downloadLink, downloadStream, new Progress<float>((progress) => var downloadTask = httpClient.DownloadAsync(_downloadLink, downloadStream, new Progress<float>((progress) =>

View File

@ -1,4 +1,5 @@
using Nikse.SubtitleEdit.Core.Common; using Nikse.SubtitleEdit.Core.Common;
using Nikse.SubtitleEdit.Core.Http;
using Nikse.SubtitleEdit.Logic; using Nikse.SubtitleEdit.Logic;
using System; using System;
using System.IO; using System.IO;
@ -29,7 +30,7 @@ namespace Nikse.SubtitleEdit.Forms.Ocr
try try
{ {
var httpClient = HttpClientHelper.MakeHttpClient(); var httpClient = DownloaderFactory.MakeHttpClient();
using (var downloadStream = new MemoryStream()) using (var downloadStream = new MemoryStream())
{ {
var downloadTask = httpClient.DownloadAsync(url, downloadStream, new Progress<float>((progress) => var downloadTask = httpClient.DownloadAsync(url, downloadStream, new Progress<float>((progress) =>

View File

@ -1,4 +1,5 @@
using Nikse.SubtitleEdit.Core.Common; using Nikse.SubtitleEdit.Core.Common;
using Nikse.SubtitleEdit.Core.Http;
using Nikse.SubtitleEdit.Logic; using Nikse.SubtitleEdit.Logic;
using System; using System;
using System.IO; using System.IO;
@ -28,7 +29,7 @@ namespace Nikse.SubtitleEdit.Forms.Ocr
try try
{ {
Utilities.SetSecurityProtocol(); Utilities.SetSecurityProtocol();
var httpClient = HttpClientHelper.MakeHttpClient(); var httpClient = DownloaderFactory.MakeHttpClient();
using (var downloadStream = new MemoryStream()) using (var downloadStream = new MemoryStream())
{ {
var downloadTask = httpClient.DownloadAsync(TesseractDownloadUrl, downloadStream, new Progress<float>((progress) => var downloadTask = httpClient.DownloadAsync(TesseractDownloadUrl, downloadStream, new Progress<float>((progress) =>

View File

@ -1,4 +1,5 @@
using Nikse.SubtitleEdit.Core.Common; using Nikse.SubtitleEdit.Core.Common;
using Nikse.SubtitleEdit.Core.Http;
using Nikse.SubtitleEdit.Logic; using Nikse.SubtitleEdit.Logic;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -106,7 +107,7 @@ namespace Nikse.SubtitleEdit.Forms.Ocr
try try
{ {
var httpClient = HttpClientHelper.MakeHttpClient(); var httpClient = DownloaderFactory.MakeHttpClient();
using (var downloadStream = new MemoryStream()) using (var downloadStream = new MemoryStream())
{ {
var downloadTask = httpClient.DownloadAsync(url, downloadStream, new Progress<float>((progress) => var downloadTask = httpClient.DownloadAsync(url, downloadStream, new Progress<float>((progress) =>

View File

@ -1,4 +1,5 @@
using Nikse.SubtitleEdit.Core.Common; using Nikse.SubtitleEdit.Core.Common;
using Nikse.SubtitleEdit.Core.Http;
using Nikse.SubtitleEdit.Logic; using Nikse.SubtitleEdit.Logic;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -86,7 +87,7 @@ namespace Nikse.SubtitleEdit.Forms.Ocr
ChosenLanguage = comboBoxDictionaries.Items[index].ToString(); ChosenLanguage = comboBoxDictionaries.Items[index].ToString();
var httpClient = HttpClientHelper.MakeHttpClient(); var httpClient = DownloaderFactory.MakeHttpClient();
using (var downloadStream = new MemoryStream()) using (var downloadStream = new MemoryStream())
{ {
var downloadTask = httpClient.DownloadAsync(url, downloadStream, new Progress<float>((progress) => var downloadTask = httpClient.DownloadAsync(url, downloadStream, new Progress<float>((progress) =>

View File

@ -1,4 +1,5 @@
using Nikse.SubtitleEdit.Core.Common; using Nikse.SubtitleEdit.Core.Common;
using Nikse.SubtitleEdit.Core.Http;
using Nikse.SubtitleEdit.Logic; using Nikse.SubtitleEdit.Logic;
using Nikse.SubtitleEdit.Logic.VideoPlayers; using Nikse.SubtitleEdit.Logic.VideoPlayers;
using System; using System;
@ -45,7 +46,7 @@ namespace Nikse.SubtitleEdit.Forms.Options
buttonDownload.Enabled = false; buttonDownload.Enabled = false;
Refresh(); Refresh();
Cursor = Cursors.WaitCursor; Cursor = Cursors.WaitCursor;
var httpClient = HttpClientHelper.MakeHttpClient(); var httpClient = DownloaderFactory.MakeHttpClient();
using (var downloadStream = new MemoryStream()) using (var downloadStream = new MemoryStream())
{ {
var downloadTask = httpClient.DownloadAsync(_downloadUrl, downloadStream, new Progress<float>((progress) => var downloadTask = httpClient.DownloadAsync(_downloadUrl, downloadStream, new Progress<float>((progress) =>

View File

@ -1,4 +1,5 @@
using Nikse.SubtitleEdit.Core.Common; using Nikse.SubtitleEdit.Core.Common;
using Nikse.SubtitleEdit.Core.Http;
using Nikse.SubtitleEdit.Logic; using Nikse.SubtitleEdit.Logic;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -82,7 +83,7 @@ namespace Nikse.SubtitleEdit.Forms
Refresh(); Refresh();
ShowInstalledPlugins(); ShowInstalledPlugins();
using (var httpClient = HttpClientHelper.MakeHttpClient()) using (var httpClient = DownloaderFactory.MakeHttpClient())
using (var downloadStream = new MemoryStream()) using (var downloadStream = new MemoryStream())
{ {
var downloadTask = httpClient.DownloadAsync(url, downloadStream, new Progress<float>((progress) => var downloadTask = httpClient.DownloadAsync(url, downloadStream, new Progress<float>((progress) =>
@ -301,7 +302,7 @@ namespace Nikse.SubtitleEdit.Forms
Refresh(); Refresh();
Cursor = Cursors.WaitCursor; Cursor = Cursors.WaitCursor;
using (var httpClient = HttpClientHelper.MakeHttpClient()) using (var httpClient = DownloaderFactory.MakeHttpClient())
using (var downloadStream = new MemoryStream()) using (var downloadStream = new MemoryStream())
{ {
var downloadTask = httpClient.DownloadAsync(url, downloadStream, new Progress<float>((progress) => var downloadTask = httpClient.DownloadAsync(url, downloadStream, new Progress<float>((progress) =>
@ -508,7 +509,7 @@ namespace Nikse.SubtitleEdit.Forms
Refresh(); Refresh();
Cursor = Cursors.WaitCursor; Cursor = Cursors.WaitCursor;
using (var httpClient = HttpClientHelper.MakeHttpClient()) using (var httpClient = DownloaderFactory.MakeHttpClient())
{ {
_updatingAllPluginsCount = 0; _updatingAllPluginsCount = 0;
_updatingAllPlugins = true; _updatingAllPlugins = true;