Skip to content

Commit a03ed65

Browse files
committed
Polymorphism refactor
1 parent 2eb8266 commit a03ed65

File tree

12 files changed

+96
-114
lines changed

12 files changed

+96
-114
lines changed

SmartImage.Lib/Engines/Impl/Ascii2DEngine.cs

Lines changed: 11 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ namespace SmartImage.Lib.Engines.Impl
2121
{
2222
public sealed class Ascii2DEngine : WebSearchEngine
2323
{
24+
2425
public Ascii2DEngine() : base("https://ascii2d.net/search/url/")
2526
{
2627
FollowRedirects = true;
@@ -33,22 +34,6 @@ public Ascii2DEngine() : base("https://ascii2d.net/search/url/")
3334

3435
public override string Name => EngineOption.ToString();
3536

36-
37-
/*protected override bool GetRawResultUri(ImageQuery query, out Uri uri, out IRestResponse res)
38-
{
39-
uri = new Uri(BaseUrl + query.UploadUri);
40-
41-
res = Network.GetResponse(uri.ToString(), (int) Timeout.TotalMilliseconds, Method.GET, false);
42-
43-
if (!res.IsSuccessful && res.StatusCode != HttpStatusCode.Redirect) {
44-
Debug.WriteLine($"{Name} is unavailable or timed out after {Timeout:g} | {uri} {res.StatusCode}",
45-
LogCategories.C_WARN);
46-
return false;
47-
}
48-
49-
return true;
50-
}*/
51-
5237
private Uri ConvertToDetailUri(Uri url)
5338
{
5439
/*
@@ -59,6 +44,11 @@ private Uri ConvertToDetailUri(Uri url)
5944
*
6045
*/
6146

47+
/*
48+
* With Ascii2D, two requests need to be made in order to get the detail results
49+
* as the color results are returned by default
50+
*
51+
*/
6252

6353
var res = Network.GetResponse(url.ToString(), (int) Timeout.TotalMilliseconds, Method.GET, false);
6454

@@ -70,7 +60,6 @@ private Uri ConvertToDetailUri(Uri url)
7060

7161
string detailUrl = newUrl.Replace("/color/", "/bovw/");
7262

73-
7463
return new Uri(detailUrl);
7564
}
7665

@@ -81,7 +70,7 @@ protected override Uri GetRaw(ImageQuery query)
8170

8271
}
8372

84-
protected override IDocument GetContent(IRestResponse response)
73+
protected internal override IDocument GetContent(IRestResponse response)
8574
{
8675
var url = response.ResponseUri;
8776

@@ -96,41 +85,19 @@ protected override IDocument GetContent(IRestResponse response)
9685
protected override bool GetInitialResult(ImageQuery query, out Uri rawUri, out IRestResponse res)
9786
{
9887
rawUri = GetRaw(query);
99-
100-
/*if (!Network.IsAlive(uri, (int) Timeout.TotalMilliseconds)) {
101-
Debug.WriteLine($"{Name} is unavailable or timed out after {Timeout:g} | {uri}", C_WARN);
102-
return null;
103-
}*/
104-
105-
88+
10689
// NOTE: wtf?
10790

10891
res = Network.GetResponse(rawUri.ToString(), (int) Timeout.TotalMilliseconds, Method.GET, FollowRedirects);
109-
110-
//res = new RestClient(rawUri).Execute(new RestRequest());
111-
92+
11293
res.Content = WebUtilities.GetString(rawUri.ToString());
11394

114-
115-
/*if (!res.IsSuccessful)
116-
{
117-
if ((FollowRedirects && res.StatusCode == HttpStatusCode.Redirect))
118-
{
119-
return true;
120-
}
121-
122-
Debug.WriteLine($"{Name} is unavailable or timed out after " +
123-
$"{Timeout:g} | {rawUri} {res.StatusCode}", LogCategories.C_WARN);
124-
return false;
125-
}*/
126-
12795
return true;
128-
12996
}
13097

131-
protected override SearchResult Process(object content, SearchResult sr)
98+
protected override SearchResult Process(object obj, SearchResult sr)
13299
{
133-
var doc = (IDocument) content;
100+
var doc = (IDocument) obj;
134101
var nodes = doc.Body.SelectNodes("//*[contains(@class, 'info-box')]");
135102

136103
var rg = new List<ImageResult>();

SmartImage.Lib/Engines/Impl/IqdbEngine.cs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -148,11 +148,14 @@ private IDocument GetDocument(ImageQuery query)
148148
}
149149

150150

151-
protected override SearchResult Process(ImageQuery query, SearchResult sr)
151+
protected override SearchResult Process(object obj, SearchResult sr)
152152
{
153153
// Don't select other results
154-
155-
var doc = GetDocument(query);
154+
var query = (ImageQuery) obj;
155+
var now = Stopwatch.GetTimestamp();
156+
var doc = GetDocument(query);
157+
var diff = TimeSpan.FromTicks(Stopwatch.GetTimestamp() - now);
158+
sr.RetrievalTime = diff;
156159

157160
var pages = doc.Body.SelectSingleNode("//div[@id='pages']");
158161
var tables = ((IHtmlElement) pages).SelectNodes("div/table");

SmartImage.Lib/Engines/Impl/SauceNaoEngine.cs

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -66,21 +66,22 @@ public SauceNaoEngine() : this(null) { }
6666

6767
private delegate IEnumerable<SauceNaoDataResult> ParseResultFunction(ImageQuery q);
6868

69-
private ParseResultFunction Get() => !UsingAPI ? GetHTMLResults : GetAPIResults;
69+
private ParseResultFunction GetParseFunction() => !UsingAPI ? GetHTMLResults : GetAPIResults;
7070

7171
public override SearchResult GetResult(ImageQuery query)
7272
{
73-
var sresult = base.GetResult(query);
73+
var result = base.GetResult(query);
7474
var primaryResult = new ImageResult();
7575

76-
var f = Get();
76+
var f = GetParseFunction();
7777

78+
var now = Stopwatch.GetTimestamp();
7879
var dataResults = f(query);
79-
80+
result.RetrievalTime = TimeSpan.FromTicks(Stopwatch.GetTimestamp() - now);
8081

8182
if (dataResults == null) {
82-
sresult.ErrorMessage = "Daily search limit (100) exceeded";
83-
sresult.Status = ResultStatus.Cooldown;
83+
result.ErrorMessage = "Daily search limit (100) exceeded";
84+
result.Status = ResultStatus.Cooldown;
8485
//return sresult;
8586
goto ret;
8687
}
@@ -102,18 +103,18 @@ public override SearchResult GetResult(ImageQuery query)
102103

103104
primaryResult.UpdateFrom(imageResults.First());
104105

105-
sresult.OtherResults.AddRange(imageResults);
106+
result.OtherResults.AddRange(imageResults);
106107

107108

108109
if (UsingAPI) {
109110
Debug.WriteLine($"{Name} API key: {Authentication}");
110111
}
111112

112-
sresult.PrimaryResult = primaryResult;
113-
sresult.Consolidate();
113+
result.PrimaryResult = primaryResult;
114+
result.Consolidate();
114115

115116
ret:
116-
return sresult;
117+
return result;
117118
}
118119

119120
private IEnumerable<SauceNaoDataResult> GetHTMLResults(ImageQuery query)

SmartImage.Lib/Engines/Impl/TidderEngine.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,9 @@ public TidderEngine() : base("http://tidder.xyz/?imagelink=") { }
2424
public override string Name => EngineOption.ToString();
2525

2626

27-
protected override SearchResult Process(object content, SearchResult sr)
27+
protected override SearchResult Process(object obj, SearchResult sr)
2828
{
29-
var doc = (IDocument) content;
29+
var doc = (IDocument) obj;
3030

3131
var documentNode = doc.Body;
3232

SmartImage.Lib/Engines/Impl/TraceMoeEngine.cs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,11 @@ public TraceMoeEngine() : base("https://trace.moe/?url=", "https://api.trace.moe
3535

3636
public override SearchEngineOptions EngineOption => SearchEngineOptions.TraceMoe;
3737

38-
protected override SearchResult Process(ImageQuery query, SearchResult r)
38+
protected override SearchResult Process(object obj, SearchResult r)
3939
{
4040

4141
//var r = base.GetResult(url);
42-
42+
var query = (ImageQuery) obj;
4343
// https://soruly.github.io/trace.moe/#/
4444

4545
var rq = new RestRequest("search");
@@ -49,8 +49,11 @@ protected override SearchResult Process(ImageQuery query, SearchResult r)
4949
rq.Timeout = Timeout.Milliseconds;
5050
rq.RequestFormat = DataFormat.Json;
5151

52+
var now = Stopwatch.GetTimestamp();
5253
var re = Client.Execute<TraceMoeRootObject>(rq, Method.GET);
5354
var tm = re.Data;
55+
var diff = TimeSpan.FromTicks(Stopwatch.GetTimestamp() - now);
56+
r.RetrievalTime = diff;
5457

5558
//var tm=JsonConvert.DeserializeObject<TraceMoeRootObject>(re.Content);
5659

SmartImage.Lib/Engines/Impl/YandexEngine.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -172,9 +172,9 @@ static ImageResult Parse(INode siz)
172172

173173

174174

175-
protected override SearchResult Process(object content, SearchResult sr)
175+
protected override SearchResult Process(object obj, SearchResult sr)
176176
{
177-
var doc = (IDocument) content;
177+
var doc = (IDocument) obj;
178178

179179
// Automation detected
180180
const string AUTOMATION_ERROR_MSG = "Please confirm that you and not a robot are sending requests";

SmartImage.Lib/Engines/Model/ClientSearchEngine.cs

Lines changed: 2 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ namespace SmartImage.Lib.Engines.Model
88
/// <summary>
99
/// Represents a search engine whose results are returned from an API.
1010
/// </summary>
11-
public abstract class ClientSearchEngine : BaseSearchEngine
11+
public abstract class ClientSearchEngine : ProcessedSearchEngine
1212
{
1313
protected ClientSearchEngine(string baseUrl, string endpointUrl) : base(baseUrl)
1414
{
@@ -23,21 +23,6 @@ protected ClientSearchEngine(string baseUrl, string endpointUrl) : base(baseUrl)
2323
protected string EndpointUrl { get; }
2424

2525
protected RestClient Client { get; }
26-
27-
28-
// todo: refactor this to inherit from ProcessedSearchEngine
29-
30-
[DebuggerHidden]
31-
public override SearchResult GetResult(ImageQuery query)
32-
{
33-
return TryProcess(base.GetResult(query), sr =>
34-
{
35-
var process = Process(query, sr);
36-
37-
return process;
38-
});
39-
}
40-
41-
protected abstract SearchResult Process(ImageQuery query, SearchResult r);
26+
4227
}
4328
}

SmartImage.Lib/Engines/Model/ProcessedSearchEngine.cs

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System;
22
using System.Diagnostics;
3+
using AngleSharp.Dom;
34
using RestSharp;
45
using SmartImage.Lib.Searching;
56

@@ -13,16 +14,58 @@ protected ProcessedSearchEngine(string baseUrl) : base(baseUrl) { }
1314

1415
public abstract override string Name { get; }
1516

16-
protected abstract SearchResult Process(object content, SearchResult sr);
17+
/// <summary>
18+
/// Processes engine results
19+
/// </summary>
20+
/// <param name="obj">Content upon which to operate</param>
21+
/// <param name="sr"><see cref="SearchResult"/> to build</param>
22+
/// <returns>Final <see cref="SearchResult"/></returns>
23+
protected abstract SearchResult Process(object obj, SearchResult sr);
1724

1825

1926
[DebuggerHidden]
2027
public override SearchResult GetResult(ImageQuery query)
2128
{
22-
return TryProcess(GetResult(query, out var response), sr =>
29+
// HACK: this is questionable, but it resolves the edge case with polymorphism
30+
31+
SearchResult result;
32+
33+
ClientSearchEngine c;
34+
WebSearchEngine w;
35+
36+
IRestResponse response = null;
37+
38+
switch (this) {
39+
case ClientSearchEngine:
40+
result = base.GetResult(query);
41+
c = this as ClientSearchEngine;
42+
w = null;
43+
break;
44+
case WebSearchEngine:
45+
result = GetResult(query, out response);
46+
w = this as WebSearchEngine;
47+
c = null;
48+
break;
49+
default:
50+
throw new InvalidOperationException();
51+
}
52+
53+
return TryProcess(result, sr =>
2354
{
24-
sr = Process(response, sr);
55+
object o;
56+
57+
if (c != null) {
58+
o = query;
59+
}
60+
else if (w != null) {
61+
o = w.GetContent(response);
62+
}
63+
else {
64+
throw new InvalidOperationException();
65+
}
66+
2567

68+
sr = Process(o, sr);
2669
return sr;
2770
});
2871
}

SmartImage.Lib/Engines/Model/WebSearchEngine.cs

Lines changed: 2 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -18,24 +18,13 @@ protected WebSearchEngine(string baseUrl) : base(baseUrl) { }
1818

1919
public abstract override string Name { get; }
2020

21-
protected abstract override SearchResult Process(object content, SearchResult sr);
2221

23-
protected virtual IDocument GetContent(IRestResponse response)
22+
protected internal virtual IDocument GetContent(IRestResponse response)
2423
{
2524
var parser = new HtmlParser();
2625
return parser.ParseDocument(response.Content);
2726
}
2827

29-
[DebuggerHidden]
30-
public override SearchResult GetResult(ImageQuery query)
31-
{
32-
return TryProcess(GetResult(query, out var response), sr =>
33-
{
34-
var doc = GetContent(response);
35-
sr = Process(doc, sr);
36-
37-
return sr;
38-
});
39-
}
28+
4029
}
4130
}

0 commit comments

Comments
 (0)