Skip to content

Commit 5624e64

Browse files
committed
Updates
1 parent cd4b927 commit 5624e64

File tree

16 files changed

+102
-104
lines changed

16 files changed

+102
-104
lines changed

SmartImage.Lib/Engines/Search/Ascii2DEngine.cs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,6 @@ protected override SearchResultOrigin GetResultOrigin(ImageQuery query, Cancella
9999
var stub = new SearchResultOrigin()
100100
{
101101
Response = response,
102-
Content = content,
103102
Retrieval = diff,
104103
Success = true,
105104
RawUri = rawUri

SmartImage.Lib/Engines/Search/Base/BaseSearchEngine.cs

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ public virtual SearchResult GetResult(ImageQuery query, CancellationToken? c = n
4141
{
4242
Origin = GetResultOrigin(query)
4343
};
44+
4445
c ??= CancellationToken.None;
4546

4647
if (c is { IsCancellationRequested: true }) {
@@ -63,6 +64,7 @@ public virtual SearchResult GetResult(ImageQuery query, CancellationToken? c = n
6364

6465
public async Task<SearchResult> GetResultAsync(ImageQuery query, CancellationToken? c = null)
6566
{
67+
c??= CancellationToken.None;
6668

6769
var task = Task.Run(delegate
6870
{
@@ -73,7 +75,7 @@ public async Task<SearchResult> GetResultAsync(ImageQuery query, CancellationTok
7375
Debug.WriteLine($"{Name}: result done", C_SUCCESS);
7476

7577
return res;
76-
}, c ?? CancellationToken.None);
78+
}, c.Value);
7779

7880
return await task;
7981
}
@@ -91,7 +93,7 @@ protected virtual SearchResultOrigin GetResultOrigin(ImageQuery query, Cancellat
9193

9294
var res = HttpUtilities.GetHttpResponse(rawUri.ToString(),
9395
(int) Timeout.TotalMilliseconds,
94-
HttpMethod.Get, FollowRedirects);
96+
HttpMethod.Get, FollowRedirects, token: c);
9597

9698

9799
bool success;
@@ -115,16 +117,15 @@ protected virtual SearchResultOrigin GetResultOrigin(ImageQuery query, Cancellat
115117
string content = null;
116118

117119
if (success && res is { }) {
118-
var task = res.Content.ReadAsStringAsync();
119-
120-
task.Wait(Timeout);
121-
content = task.Result;
120+
// var task = res.Content.ReadAsStringAsync();
121+
// task.Wait(Timeout);
122+
// content = task.Result;
122123
}
123124

124125
var origin = new SearchResultOrigin
125126
{
126127
Response = res,
127-
Content = content,
128+
// Content = content,
128129
Success = success,
129130
RawUri = rawUri,
130131
Query = query

SmartImage.Lib/Engines/Search/Base/ProcessedSearchEngine.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ public sealed override SearchResult GetResult(ImageQuery query, CancellationToke
2424
goto ret;
2525
}
2626

27-
if (!sr.IsSuccessful) {
27+
if (!sr.IsStatusSuccessful) {
2828
// sr.Origin.Dispose();
2929
goto ret;
3030
}

SmartImage.Lib/Engines/Search/Base/WebClientSearchEngine.cs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,11 @@ protected override object GetProcessingObject(SearchResult r)
2121

2222
protected virtual object ParseContent(SearchResultOrigin s)
2323
{
24-
var parser = new HtmlParser();
25-
26-
var document = parser.ParseDocument(s.Content);
24+
var parser = new HtmlParser();
25+
var async = s.Response.Content.ReadAsStringAsync();
26+
async.Wait();
27+
var content = async.Result;
28+
var document = parser.ParseDocument((string) content);
2729

2830
return document;
2931
}

SmartImage.Lib/Engines/Search/TinEyeEngine.cs

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,23 @@
33
using System.Diagnostics;
44
using System.Linq;
55
using System.Threading.Tasks;
6+
using Kantan.Net;
67
using PuppeteerExtraSharp;
78
using PuppeteerExtraSharp.Plugins.ExtraStealth;
89
using PuppeteerSharp;
910
using SmartImage.Lib.Engines.Search.Base;
1011
using SmartImage.Lib.Searching;
12+
using SmartImage.Lib.Utilities;
1113

1214
namespace SmartImage.Lib.Engines.Search;
1315

1416
public static class WebDriverExtensions
1517
{
1618
public static string ToValueString(this JSHandle h)
17-
=> h.ToString().Replace("jshandle:", string.Empty, StringComparison.InvariantCultureIgnoreCase);
19+
{
20+
// return h.JsonValueAsync().GetAwaiter().GetResult().ToString();
21+
return h.ToString().Replace("jshandle:", string.Empty, StringComparison.InvariantCultureIgnoreCase);
22+
}
1823
}
1924

2025
public sealed class TinEyeEngine : WebDriverSearchEngine
@@ -75,8 +80,8 @@ protected override async Task<List<ImageResult>> Browse(ImageQuery sd, SearchRes
7580

7681
var ir = new ImageResult(r) { };
7782

78-
var p = await elem.QuerySelectorAllAsync("p");
79-
var h4 = await elem.QuerySelectorAsync("h4");
83+
var p = await elem.QuerySelectorAllAsync("p");
84+
var h4 = await elem.QuerySelectorAsync("h4");
8085

8186
var name = await h4.GetPropertyAsync("textContent");
8287

@@ -87,25 +92,32 @@ protected override async Task<List<ImageResult>> Browse(ImageQuery sd, SearchRes
8792

8893
var uri = new List<Uri>();
8994

95+
// a=a.Distinct().ToArray();
96+
9097
foreach (ElementHandle t in a) {
9198
var href = await t.GetPropertyAsync("href");
9299

93100
string s = href.ToValueString();
94-
Debug.WriteLine($"{s} | {await href.JsonValueAsync()}");
101+
95102
if (!string.IsNullOrWhiteSpace(s)) {
96-
uri.Add(new Uri(s));
103+
var item = new Uri(s);
104+
// item = item.Normalize();
105+
106+
if (!uri.Contains(item)) {
107+
uri.Add(item);
108+
}
97109
}
98110
}
99111

100112
ir.OtherUrl.AddRange(uri);
101113

102114

103-
var imgElems = await t1.QuerySelectorAllAsync("img");
104-
var imgList = new List<Uri>();
115+
var imgElems = await t1.QuerySelectorAllAsync("img");
116+
var imgList = new List<Uri>();
105117

106118
for (int k = 0; k < imgElems.Length; k++) {
107119
var src = await a[k].GetPropertyAsync("src");
108-
120+
109121
imgList.Add(new Uri(src.ToValueString()));
110122
}
111123

@@ -126,15 +138,15 @@ protected override async Task<List<ImageResult>> Browse(ImageQuery sd, SearchRes
126138

127139
img.Add(ir);
128140
}
129-
141+
130142
return img;
131143
}
132144

133145

134146
protected override SearchResult Process(object obj, SearchResult sr)
135147
{
136148
var query = (ImageQuery) obj;
137-
149+
138150
// var vr = base.GetResult(query);
139151

140152
var task = Browse(query, sr);

SmartImage.Lib/SearchClient.cs

Lines changed: 18 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ public SearchClient(SearchConfig config)
4242
DetailedResults = new List<ImageResult>();
4343
ContinueTasks = new List<Task>();
4444

45-
DirectResultsWaitHandle = new AutoResetEvent(false);
45+
DirectResultsWaitHandle = new();
4646

4747
Reload();
4848

@@ -90,7 +90,7 @@ public SearchClient(SearchConfig config)
9090
/// <summary>
9191
/// Number of pending results
9292
/// </summary>
93-
public int PendingCount { get; private set; }
93+
public int PendingCount => Tasks.Count;
9494

9595
public int CompleteCount => AllResults.Count;
9696

@@ -100,7 +100,7 @@ public SearchClient(SearchConfig config)
100100

101101
public List<Task> ContinueTasks { get; }
102102

103-
public WaitHandle DirectResultsWaitHandle { get; private set; }
103+
public TaskCompletionSource DirectResultsWaitHandle { get; private set; }
104104

105105

106106
/// <summary>
@@ -130,13 +130,12 @@ public void Reset()
130130
FilteredResults.Clear();
131131
DetailedResults.Clear();
132132
ContinueTasks.Clear();
133-
PendingCount = 0;
133+
134134

135135
IsComplete = false;
136136
IsContinueComplete = false;
137137

138-
DirectResultsWaitHandle = new AutoResetEvent(false);
139-
138+
DirectResultsWaitHandle = new();
140139
Reload();
141140
}
142141

@@ -159,8 +158,6 @@ public async Task RunSearchAsync(CancellationToken? cts = null)
159158
return task;
160159
}));
161160

162-
PendingCount = Tasks.Count;
163-
164161

165162
while (!IsComplete && !cts.Value.IsCancellationRequested) {
166163
var finished = await Task.WhenAny(Tasks);
@@ -170,10 +167,9 @@ public async Task RunSearchAsync(CancellationToken? cts = null)
170167

171168
ContinueTasks.Add(task);
172169

173-
SearchResult value = await finished;
170+
SearchResult value = finished.Result;
174171

175172
Tasks.Remove(finished);
176-
PendingCount = Tasks.Count;
177173

178174
bool? isFiltered;
179175
bool isPriority = Config.PriorityEngines.HasFlag(value.Engine.EngineOption);
@@ -194,6 +190,7 @@ public async Task RunSearchAsync(CancellationToken? cts = null)
194190

195191
if (value.IsNonPrimitive) {
196192
Results.Add(value);
193+
DetailedResults.Add(value.PrimaryResult);
197194
isFiltered = false;
198195
}
199196
else {
@@ -206,11 +203,6 @@ public async Task RunSearchAsync(CancellationToken? cts = null)
206203
isFiltered = null;
207204
}
208205

209-
210-
if (DetailPredicate(value)) {
211-
DetailedResults.Add(value.PrimaryResult);
212-
}
213-
214206
//
215207

216208
// Call event
@@ -229,7 +221,7 @@ public async Task RunSearchAsync(CancellationToken? cts = null)
229221

230222
/* 2nd pass */
231223

232-
DetailedResults.AddRange(ApplyPredicateFilter(Results, DetailPredicate));
224+
// DetailedResults.AddRange(ApplyPredicateFilter(Results, v => v.IsNonPrimitive));
233225

234226
var args = new SearchCompletedEventArgs { };
235227

@@ -253,17 +245,14 @@ public async Task RunContinueAsync(CancellationToken? c = null)
253245

254246
}
255247

256-
if (!DirectResultsWaitHandle.SafeWaitHandle.IsInvalid || !DirectResultsWaitHandle.SafeWaitHandle.IsClosed) {
257-
((AutoResetEvent) DirectResultsWaitHandle).Set();
258-
}
259248
}
260249

261250

262251
private void GetResultContinueCallback(Task<SearchResult> task, object state)
263252
{
264253
var value = task.Result;
265254

266-
if (!value.IsSuccessful || !value.IsNonPrimitive || value.Scanned) {
255+
if (!value.IsStatusSuccessful || !value.IsNonPrimitive || value.Scanned) {
267256
return;
268257
}
269258

@@ -274,20 +263,19 @@ private void GetResultContinueCallback(Task<SearchResult> task, object state)
274263
DirectResults.AddRange(result);
275264

276265
value.Scanned = true;
277-
var autoResetEvent = ((AutoResetEvent) DirectResultsWaitHandle);
278266

279267
if (DirectResults.Count > 0 /*||
280268
!DirectResultsWaitHandle.SafeWaitHandle.IsClosed*/ /*|| ContinueTasks.Count==1*/) {
281269

282-
if (!DirectResultsWaitHandle.SafeWaitHandle.IsClosed) {
270+
if (DirectResultsWaitHandle.TrySetResult()) {
283271
Debug.WriteLine("wait handle set");
284-
autoResetEvent.Set();
272+
285273

286274
}
287275

288276
}
289277

290-
DirectResultCompleted?.Invoke(null, EventArgs.Empty);
278+
ContinueCompleted?.Invoke(null, EventArgs.Empty);
291279

292280
// if (result.Any()) { }
293281

@@ -345,7 +333,7 @@ public List<SearchResult> MaximizeResults<T>(Func<SearchResult, T> property)
345333

346334
var res = Results.OrderByDescending(property).ToList();
347335

348-
res.RemoveAll(r => !DetailPredicate(r));
336+
res.RemoveAll(r => !r.IsNonPrimitive);
349337

350338
return res;
351339
}
@@ -367,9 +355,9 @@ public static BaseSearchEngine[] GetAllSearchEngines()
367355
}
368356

369357
/// <summary>
370-
/// Fires when a result has been updated with new information
358+
/// Fires when <see cref="GetResultContinueCallback"/> returns
371359
/// </summary>
372-
public event EventHandler DirectResultCompleted;
360+
public event EventHandler ContinueCompleted;
373361

374362
/// <summary>
375363
/// Fires when a result is returned (<see cref="RunSearchAsync" />).
@@ -382,24 +370,19 @@ public static BaseSearchEngine[] GetAllSearchEngines()
382370
public event EventHandler<SearchCompletedEventArgs> SearchCompleted;
383371

384372

385-
private static readonly Predicate<SearchResult> DetailPredicate = r => r.IsNonPrimitive;
386-
387-
private static readonly SmartImageException SearchException = new("Search must be completed");
373+
private static readonly SmartImageException SearchException = new("Search not complete");
388374

389375

390376
public void Dispose()
391377
{
392-
foreach (ImageResult result in DirectResults) {
378+
/*foreach (ImageResult result in DirectResults) {
393379
result.Dispose();
394-
}
380+
}*/
395381

396382
foreach (SearchResult result in AllResults) {
397383
result.Dispose();
398384
}
399385

400-
if (!DirectResultsWaitHandle.SafeWaitHandle.IsClosed) {
401-
DirectResultsWaitHandle.Dispose();
402-
}
403386
}
404387
}
405388

SmartImage.Lib/SearchConfig.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ namespace SmartImage.Lib;
1515
/// Contains configuration for <see cref="SearchClient"/>
1616
/// </summary>
1717
/// <remarks>Search config is only applicable when used in <see cref="SearchClient"/></remarks>
18-
public sealed class SearchConfig : ConfigurationSection
18+
public sealed class SearchConfig /*: ConfigurationSection*/
1919
{
2020
/// <summary>
2121
/// Search query

SmartImage.Lib/Searching/ImageQuery.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ public ImageQuery([NotNull] string value, [CanBeNull] BaseUploadEngine engine =
100100
public static (bool IsUri, bool IsFile) IsUriOrFile(string x)
101101
{
102102
//todo
103-
var isUriOrFile = (ImageHelper.IsBinaryImage(x, out var di), File.Exists(x));
103+
var isUriOrFile = (ImageHelper.IsBinaryImage(x, out var di,-1), File.Exists(x));
104104
// di?.Dispose();
105105
return isUriOrFile;
106106
}
@@ -109,7 +109,7 @@ public ImageResult GetImageResult()
109109
{
110110

111111

112-
BinaryResource directImage = new()
112+
MediaResource directImage = new()
113113
{
114114
// Stream = Stream,
115115
Url = UploadUri

0 commit comments

Comments
 (0)