Skip to content

Commit 2309813

Browse files
committed
Refactor SauceNao
1 parent e802c01 commit 2309813

File tree

6 files changed

+45
-48
lines changed

6 files changed

+45
-48
lines changed

SmartImage.Lib/Engines/Impl/Ascii2DEngine.cs

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ public sealed class Ascii2DEngine : WebSearchEngine
2323
{
2424
public Ascii2DEngine() : base("https://ascii2d.net/search/url/")
2525
{
26-
FollowRedirects = true;
2726

2827
}
2928

@@ -33,11 +32,11 @@ public Ascii2DEngine() : base("https://ascii2d.net/search/url/")
3332

3433
public override string Name => EngineOption.ToString();
3534

36-
protected override Uri GetRaw(ImageQuery query)
35+
protected override Uri GetRawUri(ImageQuery query)
3736
{
38-
var a = base.GetRaw(query);
37+
var uri = base.GetRawUri(query);
3938

40-
var request = WebRequest.Create(a);
39+
var request = WebRequest.Create(uri);
4140

4241
using var response = request.GetResponse();
4342

@@ -54,9 +53,7 @@ protected override Uri GetRaw(ImageQuery query)
5453
* as the color results are returned by default
5554
*
5655
*/
57-
58-
// Convert to detail url
59-
56+
6057
string detailUrl = response.ResponseUri.ToString().Replace("/color/", "/bovw/");
6158

6259
return new Uri(detailUrl);
@@ -66,18 +63,21 @@ protected override Uri GetRaw(ImageQuery query)
6663

6764
protected override bool GetInitialResult(ImageQuery query, out Uri rawUri, out IRestResponse res)
6865
{
69-
rawUri = GetRaw(query);
70-
71-
res = new RestResponse();
66+
rawUri = GetRawUri(query);
67+
68+
res = new RestResponse
69+
{
70+
Content = WebUtilities.GetString(rawUri.ToString())
71+
};
7272

73-
res.Content = WebUtilities.GetString(rawUri.ToString());
7473

7574
return true;
7675
}
7776

7877
protected override SearchResult Process(object obj, SearchResult sr)
7978
{
8079
var doc = (IDocument) obj;
80+
8181
var nodes = doc.Body.SelectNodes("//*[contains(@class, 'info-box')]");
8282

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

SmartImage.Lib/Engines/Impl/SauceNaoEngine.cs

Lines changed: 19 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -32,51 +32,47 @@
3232

3333
namespace SmartImage.Lib.Engines.Impl
3434
{
35-
public sealed class SauceNaoEngine : BaseSearchEngine
35+
public sealed class SauceNaoEngine : ClientSearchEngine
3636
{
3737
private const string BASE_URL = "https://saucenao.com/";
3838

3939
private const string BASIC_RESULT = "https://saucenao.com/search.php?url=";
4040

41-
private const string SEARCH = "search.php";
42-
43-
private readonly RestClient m_client;
44-
41+
public override string Name => EngineOption.ToString();
4542

4643
/*
4744
* Excerpts adapted from https://github.com/Lazrius/SharpNao/blob/master/SharpNao.cs#L53
4845
* https://github.com/luk1337/SauceNAO/blob/master/app/src/main/java/com/luk/saucenao/MainActivity.java
4946
*/
5047

5148

52-
public SauceNaoEngine(string authentication) : base(BASIC_RESULT)
49+
public SauceNaoEngine(string authentication) : base(BASIC_RESULT, BASE_URL)
5350
{
54-
m_client = new RestClient(BASE_URL);
5551
Authentication = authentication;
5652
}
5753

5854
public SauceNaoEngine() : this(null) { }
5955

60-
public string Authentication { get; init; }
56+
public string Authentication { get; set; }
6157

6258
public bool UsingAPI => !String.IsNullOrWhiteSpace(Authentication);
6359

6460
public override SearchEngineOptions EngineOption => SearchEngineOptions.SauceNao;
6561

6662

67-
private delegate IEnumerable<SauceNaoDataResult> ParseResultFunction(ImageQuery q);
68-
69-
private ParseResultFunction GetParseFunction() => !UsingAPI ? GetHTMLResults : GetAPIResults;
70-
71-
public override SearchResult GetResult(ImageQuery query)
63+
protected override SearchResult Process(object obj, SearchResult result)
7264
{
73-
var result = base.GetResult(query);
65+
var query = (ImageQuery) obj;
66+
7467
var primaryResult = new ImageResult();
7568

76-
var f = GetParseFunction();
69+
var parseFunc = (Func<ImageQuery, IEnumerable<SauceNaoDataResult>>)
70+
(!UsingAPI ? GetHTMLResults : GetAPIResults);
71+
72+
var now = Stopwatch.GetTimestamp();
73+
74+
var dataResults = parseFunc(query);
7775

78-
var now = Stopwatch.GetTimestamp();
79-
var dataResults = f(query);
8076
result.RetrievalTime = TimeSpan.FromTicks(Stopwatch.GetTimestamp() - now);
8177

8278
if (dataResults == null) {
@@ -89,8 +85,7 @@ public override SearchResult GetResult(ImageQuery query)
8985
var imageResults = dataResults.Where(o => o != null)
9086
.AsParallel()
9187
.Select(ConvertToImageResult)
92-
.Where(o => o != null)
93-
.Where(e => e.Url != null)
88+
.Where(o => o != null)
9489
.OrderByDescending(e => e.Similarity)
9590
.ToList();
9691

@@ -117,6 +112,7 @@ public override SearchResult GetResult(ImageQuery query)
117112
return result;
118113
}
119114

115+
120116
private IEnumerable<SauceNaoDataResult> GetHTMLResults(ImageQuery query)
121117
{
122118

@@ -125,7 +121,7 @@ private IEnumerable<SauceNaoDataResult> GetHTMLResults(ImageQuery query)
125121
var docp = new HtmlParser();
126122

127123

128-
var req = new RestRequest(SEARCH, Method.POST);
124+
var req = new RestRequest("search.php", Method.POST);
129125

130126
if (query.IsFile) {
131127
req.AddFile("file", File.ReadAllBytes(query.Value), "image.png");
@@ -137,7 +133,7 @@ private IEnumerable<SauceNaoDataResult> GetHTMLResults(ImageQuery query)
137133
throw new SmartImageException();
138134
}
139135

140-
var execute = m_client.Execute(req);
136+
var execute = Client.Execute(req);
141137

142138
string html = execute.Content;
143139

@@ -225,14 +221,14 @@ private IEnumerable<SauceNaoDataResult> GetAPIResults(ImageQuery url)
225221
{
226222
Trace.WriteLine($"{Name} | API");
227223

228-
var req = new RestRequest(SEARCH);
224+
var req = new RestRequest("search.php");
229225
req.AddQueryParameter("db", "999");
230226
req.AddQueryParameter("output_type", "2");
231227
req.AddQueryParameter("numres", "16");
232228
req.AddQueryParameter("api_key", Authentication);
233229
req.AddQueryParameter("url", url.UploadUri.ToString());
234230

235-
var res = m_client.Execute(req);
231+
var res = Client.Execute(req);
236232

237233
if (res.StatusCode == HttpStatusCode.Forbidden) {
238234
return null;

SmartImage.Lib/Engines/Model/BaseSearchEngine.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ public async Task<SearchResult> GetResultAsync(ImageQuery query)
6666
return await task;
6767
}
6868

69-
protected virtual Uri GetRaw(ImageQuery query)
69+
protected virtual Uri GetRawUri(ImageQuery query)
7070
{
7171
//
7272
return new(BaseUrl + query.UploadUri);
@@ -76,7 +76,7 @@ protected virtual Uri GetRaw(ImageQuery query)
7676
protected virtual bool GetInitialResult(ImageQuery query, out Uri rawUri, out IRestResponse res)
7777
{
7878

79-
rawUri = GetRaw(query);
79+
rawUri = GetRawUri(query);
8080

8181
/*if (!Network.IsAlive(uri, (int) Timeout.TotalMilliseconds)) {
8282
Debug.WriteLine($"{Name} is unavailable or timed out after {Timeout:g} | {uri}", C_WARN);

SmartImage/Program.cs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ public static class Program
7272
/// </summary>
7373
public static readonly NConsoleDialog ResultDialog = new()
7474
{
75-
Options = new List<NConsoleOption>(),
75+
Options = new List<NConsoleOption>(),
7676

7777
Description = "Press the result number to open in browser\n" +
7878
"Ctrl: Load direct | Alt: Show other | Shift: Open raw | Alt+Ctrl: Download\n" +
@@ -103,7 +103,7 @@ public static class Program
103103

104104
NConsole.Refresh();
105105
},
106-
106+
107107
}
108108
};
109109

@@ -161,7 +161,7 @@ private static async Task Main(string[] args)
161161
ResultDialog.Subtitle = $"SE: {Config.SearchEngines} " +
162162
$"| PE: {Config.PriorityEngines} " +
163163
$"| Filtering: {Config.Filtering.ToToggleString()}";
164-
164+
165165
CancellationTokenSource cts = new();
166166

167167
// Run search
@@ -172,8 +172,7 @@ private static async Task Main(string[] args)
172172
{
173173
OnSearchCompleted(obj, eventArgs, cts);
174174

175-
if (Config.Notification)
176-
{
175+
if (Config.Notification) {
177176
AppInterface.ShowToast(obj, eventArgs);
178177
}
179178
};

SmartImage/UI/NConsoleFactory.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
using Kantan.Diagnostics;
1111
using Kantan.Net;
1212
using Kantan.Utilities;
13+
using Kantan.Utilities.Configuration;
1314
using Novus.Utilities;
1415
using Novus.Win32;
1516
using SmartImage.Core;

Test/Program.cs

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -160,24 +160,25 @@ public static async Task Main(string[] args)
160160
//var r2 = await i2;
161161

162162
//Console.WriteLine(">> {0}", r2);
163+
var q = new ImageQuery(@"C:\Users\Deci\Pictures\Test Images\Test6.jpg");
164+
var ix = new SauceNaoEngine() { };
165+
ix.Authentication = "362e7e82bc8cf7f6025431fbf3006510057298c3";
166+
var i2x = ix.GetResultAsync(q);
167+
var r2x = await i2x;
163168

164-
//var ix = new SauceNaoEngine() { };
165-
//var i2x = ix.GetResultAsync(q);
166-
//var r2x = await i2x;
167-
168-
//Console.WriteLine(">> {0}", r2x);
169+
Console.WriteLine(">> {0}", r2x);
169170

170171
//var t = ImageHelper.FindDirectImages("https://deviantart.com/view/817835288");
171172

172173

173-
var sw = Stopwatch.StartNew();
174+
/*var sw = Stopwatch.StartNew();
174175
var t = ImageHelper.FindDirectImages("https://www.zerochan.net/2750747");
175176
sw.Stop();
176177
Debug.WriteLine($"{sw.Elapsed.TotalSeconds}");
177178
178179
foreach (var s in t) {
179180
Console.WriteLine(s);
180-
}
181+
}*/
181182

182183

183184
}

0 commit comments

Comments
 (0)