Skip to content

Commit

Permalink
#137 Proxy support with reworked CookieClient, Parser's and some init…
Browse files Browse the repository at this point in the history
…alization code.
  • Loading branch information
MonkAlex committed May 12, 2019
1 parent b92d050 commit b3fbdf2
Show file tree
Hide file tree
Showing 45 changed files with 499 additions and 148 deletions.
11 changes: 3 additions & 8 deletions MangaReader.Core/Account/CookieClient.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Net;
using System.Text;
using MangaReader.Core.Services;

namespace MangaReader.Core.Account
{
Expand Down Expand Up @@ -33,16 +34,10 @@ protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult r
return baseResponce;
}

public CookieClient() : this(new CookieContainer())
{

}

public CookieClient(CookieContainer cookie)
protected CookieClient()
{
this.Cookie = new CookieContainer();
this.Encoding = Encoding.UTF8;
this.Proxy = SystemProxySetting.SystemProxy.Value;
this.Cookie = cookie;
Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0";
}
}
Expand Down
9 changes: 0 additions & 9 deletions MangaReader.Core/Account/IProxySetting.cs

This file was deleted.

6 changes: 2 additions & 4 deletions MangaReader.Core/Account/Login.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Threading.Tasks;
using MangaReader.Core.Manga;
using MangaReader.Core.Services;
using MangaReader.Core.Services.Config;

namespace MangaReader.Core.Account
{
Expand Down Expand Up @@ -39,10 +40,7 @@ public bool IsLogined
/// </summary>
protected internal CookieContainer ClientCookie { get; set; }

protected internal CookieClient GetClient()
{
return new CookieClient(this.ClientCookie) { BaseAddress = MainUri.ToString() };
}
protected internal abstract CookieClient GetClient();

private bool isLogined;

Expand Down
41 changes: 38 additions & 3 deletions MangaReader.Core/Account/ProxySetting.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,15 @@

namespace MangaReader.Core.Account
{
public class ProxySetting : Entity.Entity, IProxySetting
public class ProxySetting : Entity.Entity
{
internal static readonly Lazy<IWebProxy> SystemProxy = new Lazy<IWebProxy>(() =>
{
var proxy = WebRequest.GetSystemWebProxy();
proxy.Credentials = CredentialCache.DefaultCredentials;
return proxy;
});

public string Name { get; set; }

public Uri Address { get; set; }
Expand All @@ -13,10 +20,38 @@ public class ProxySetting : Entity.Entity, IProxySetting

public string Password { get; set; }

public ProxySettingType SettingType { get; set; }

public virtual IWebProxy GetProxy()
{
var proxy = new WebProxy(Address, true, null, new NetworkCredential(UserName, Password));
return proxy;
switch (SettingType)
{
case ProxySettingType.NoProxy:
return null;
case ProxySettingType.System:
return SystemProxy.Value;
case ProxySettingType.Manual:
return new WebProxy(Address, true, null, new NetworkCredential(UserName, Password));
default:
throw new ArgumentOutOfRangeException();
}
}

protected ProxySetting()
{
this.SettingType = ProxySettingType.NoProxy;
}

public ProxySetting(ProxySettingType settingType)
{
this.SettingType = settingType;
}
}

public enum ProxySettingType
{
NoProxy,
System,
Manual
}
}
20 changes: 0 additions & 20 deletions MangaReader.Core/Account/SystemProxySetting.cs

This file was deleted.

13 changes: 7 additions & 6 deletions MangaReader.Core/BaseSiteParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -110,17 +110,18 @@ protected void FillMangaPages(IManga manga, ICollection<MangaPageDto> pages)

public virtual IAsyncEnumerable<IManga> Search(string name)
{
var client = new CookieClient();
var hosts = ConfigStorage.Plugins
.Where(p => p.GetParser().GetType() == this.GetType())
.Select(p => p.GetSettings().MainUri);
return hosts.SelectAsync(async host => await GetMangaNodes(name, host, client).ConfigureAwait(false))
.Where(nc => nc != null && nc.Item1 != null)
.SelectMany(n => n.Item1.SelectAsync(node => GetMangaFromNode(n.Item2, client, node)))
return hosts.SelectAsync(async host => await GetMangaNodes(name, host).ConfigureAwait(false))
.Where(nc => nc.Nodes != null)
.SelectMany(n => n.Nodes.SelectAsync(node => GetMangaFromNode(n.Uri, n.CookieClient, node)))
.Where(m => m != null);
}

protected abstract Task<Tuple<HtmlNodeCollection, Uri>> GetMangaNodes(string name, Uri host, CookieClient client);
public abstract CookieClient GetClient();

protected abstract Task<(HtmlNodeCollection Nodes, Uri Uri, CookieClient CookieClient)> GetMangaNodes(string name, Uri host);

protected abstract Task<IManga> GetMangaFromNode(Uri host, CookieClient client, HtmlNode manga);

Expand All @@ -142,4 +143,4 @@ public virtual IMapper GetMapper()
});
}
}
}
}
37 changes: 37 additions & 0 deletions MangaReader.Core/Convertation/Config/From47To48.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using MangaReader.Core.Account;
using MangaReader.Core.Convertation.Primitives;
using MangaReader.Core.NHibernate;
using MangaReader.Core.Services;

namespace MangaReader.Core.Convertation.Config
{
public class From47To48 : ConfigConverter
{
protected override async Task ProtectedConvert(IProcess process)
{
using (var context = Repository.GetEntityContext())
{
var proxySetting = await context
.Get<ProxySetting>()
.Where(s => s.SettingType == ProxySettingType.System)
.SingleAsync().ConfigureAwait(false);
var settings = await context.Get<MangaSetting>().Where(s => s.ProxySetting == null).ToListAsync().ConfigureAwait(false);
foreach (var setting in settings)
{
setting.ProxySetting = proxySetting;
}

await settings.SaveAll(context).ConfigureAwait(false);
}
}

public From47To48()
{
this.Name = "Поддержка прокси";
this.Version = new Version(1, 48, 0);
}
}
}
4 changes: 2 additions & 2 deletions MangaReader.Core/Convertation/Primitives/BaseConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ public async Task Convert(IProcess process)
{
if (this.CanConvert(process))
{
Log.AddFormat("Converter '{0}{1}' started", this.Name, this.Version);
Log.AddFormat("Converter '{0} {1}' started", this.Name, this.Version);
await this.ProtectedConvert(process).ConfigureAwait(false);
Log.AddFormat("Converter '{0}{1}' completed", this.Name, this.Version);
Log.AddFormat("Converter '{0} {1}' completed", this.Name, this.Version);
}
}

Expand Down
9 changes: 8 additions & 1 deletion MangaReader.Core/ISiteParser.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using MangaReader.Core.Account;
using MangaReader.Core.Manga;

namespace MangaReader.Core
Expand Down Expand Up @@ -50,6 +51,12 @@ public interface ISiteParser
/// <param name="name">Название манги.</param>
/// <returns>Найденная манга.</returns>
IAsyncEnumerable<IManga> Search(string name);

/// <summary>
/// Клиент для работы с сайтом.
/// </summary>
/// <returns></returns>
CookieClient GetClient();
}

public class UriParseResult
Expand All @@ -75,4 +82,4 @@ public enum UriParseKind
Chapter = 2,
Page = 3
}
}
}
2 changes: 1 addition & 1 deletion MangaReader.Core/Manga/Mangas.cs
Original file line number Diff line number Diff line change
Expand Up @@ -490,7 +490,7 @@ public override async Task BeforeSave(ChangeTrackerArgs args)
debugMessage += $" uri changed from '{uriState.OldValue}' to '{uriState.Value}'";
using (Repository.GetEntityContext("Manga uri changed"))
{
var settings = ConfigStorage.Plugins.Where(p => p.GetParser().GetType() == Parser.GetType()).Select(p => p.GetSettings());
var settings = ConfigStorage.Plugins.Where(p => p.LoginType == this.Setting.Login.GetType()).Select(p => p.GetSettings());
var allowedUris = settings.Select(s => s.MainUri).ToList();
if (allowedUris.Any(s => s.Host == uriState.OldValue.Host) &&
allowedUris.All(s => s.Host != uriState.Value.Host))
Expand Down
1 change: 1 addition & 0 deletions MangaReader.Core/NHibernate/MangaSettingMap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ public MangaSettingMap()
Map(x => x.MainUri);
Map(x => x.FolderNamingStrategy);
References(x => x.Login).Cascade.All().NotFound.Ignore();
References(x => x.ProxySetting);
}
}
}
19 changes: 19 additions & 0 deletions MangaReader.Core/NHibernate/ProxySettingMap.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using FluentNHibernate.Mapping;
using MangaReader.Core.Account;

namespace MangaReader.Core.NHibernate
{
public class ProxySettingMap : ClassMap<ProxySetting>
{
public ProxySettingMap()
{
Not.LazyLoad();
Id(x => x.Id);
Map(x => x.Name);
Map(x => x.UserName);
Map(x => x.Password);
Map(x => x.SettingType);
Map(x => x.Address);
}
}
}
25 changes: 25 additions & 0 deletions MangaReader.Core/Services/CallContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using System.Collections.Concurrent;
using System.Threading;

namespace MangaReader.Core.Services
{
public static class CallContext<T>
{
private static readonly ConcurrentDictionary<string, AsyncLocal<T>> State = new ConcurrentDictionary<string, AsyncLocal<T>>();

public static void SetData(string name, T data)
{
State.AddOrUpdate(name, new AsyncLocal<T>(), (_, __) => new AsyncLocal<T>()).Value = data;
}

public static T GetData(string name)
{
return State.TryGetValue(name, out AsyncLocal<T> data) ? data.Value : default(T);
}

public static bool RemoveData(string name)
{
return State.TryRemove(name, out _);
}
}
}
25 changes: 24 additions & 1 deletion MangaReader.Core/Services/Config/DatabaseConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,32 @@ private static async Task CreateDefaultMangaSettings(RepositoryContext context)
Manga = plugin.MangaGuid,
MangaName = plugin.Name,
DefaultCompression = Compression.CompressionMode.Manga,
ProxySetting = await context.Get<ProxySetting>().SingleAsync(s => s.SettingType == ProxySettingType.System).ConfigureAwait(false),
Login = await Login.Get(plugin.LoginType).ConfigureAwait(false)
};

await context.Save(setting).ConfigureAwait(false);
settings.Add(setting);
}

foreach (var setting in settings)
{
MangaSettingCache.Set(new MangaSettingCache(setting));
}
}

private static async Task CreateDefaultProxySettings(RepositoryContext context)
{
var types = new[] { ProxySettingType.NoProxy, ProxySettingType.System };
foreach (var settingType in types)
{
if (!await context.Get<ProxySetting>().AnyAsync(s => s.SettingType == settingType)
.ConfigureAwait(false))
{
var noProxy = new ProxySetting(settingType);
await context.Save(noProxy).ConfigureAwait(false);
}
}
}

public DatabaseConfig()
Expand All @@ -77,7 +97,10 @@ public static async Task Initialize()
{
await Repository.GetStateless<DatabaseConfig>().SingleOrCreate().ConfigureAwait(false);
using (var context = Repository.GetEntityContext("Initialize database config"))
{
await CreateDefaultProxySettings(context).ConfigureAwait(false);
await CreateDefaultMangaSettings(context).ConfigureAwait(false);
}
}
}
}
}
5 changes: 5 additions & 0 deletions MangaReader.Core/Services/MangaSetting.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ public class MangaSetting : Entity.Entity
/// </summary>
public Guid FolderNamingStrategy { get; set; }

/// <summary>
/// Настройки прокси.
/// </summary>
public ProxySetting ProxySetting { get; set; }

public override async Task BeforeSave(ChangeTrackerArgs args)
{
if (!DirectoryHelpers.ValidateSettingPath(this.Folder))
Expand Down
Loading

0 comments on commit b3fbdf2

Please sign in to comment.