1
- global using R1 = SmartImage.Lib.Resources;
1
+ // Author: Deci | Project: SmartImage.Lib | Name: BaseSearchEngine.cs
2
+ // Date: 2024/06/06 @ 14:06:00
3
+
4
+ global using R1 = SmartImage.Lib.Resources;
2
5
global using Url = Flurl.Url;
3
- using System.Collections.Concurrent;
4
6
using System.Diagnostics;
5
- using System.Drawing;
6
- using System.Text.Json;
7
- using System.Resources;
8
- using Novus.Utilities;
9
- using SmartImage.Lib.Results;
10
- using AngleSharp.Dom;
11
- using AngleSharp.Html.Parser;
12
7
using Flurl.Http;
13
- using Flurl.Http.Configuration;
14
8
using Kantan.Diagnostics;
15
9
using Kantan.Net.Utilities;
16
- using Kantan.Net.Web;
17
- using Microsoft.Extensions.Http.Logging;
18
10
using Microsoft.Extensions.Logging;
19
11
using SmartImage.Lib.Engines.Impl.Search;
20
12
using SmartImage.Lib.Engines.Impl.Search.Other;
21
- using SmartImage.Lib.Images;
22
- using SmartImage.Lib.Utilities;
23
- using SmartImage.Lib.Results.Data;
24
- using SmartImage.Lib.Diagnostics;
13
+ using SmartImage.Lib.Results;
25
14
using SmartImage.Lib.Utilities.Diagnostics;
26
15
27
16
namespace SmartImage.Lib.Engines;
28
17
#nullable enable
29
18
public abstract class BaseSearchEngine : IDisposable, IEquatable<BaseSearchEngine>
30
19
{
31
20
32
- protected static FlurlClient Client { get; }
33
-
34
- /// <summary>
35
- /// The corresponding <see cref="SearchEngineOptions"/> of this engine
36
- /// </summary>
37
- public abstract SearchEngineOptions EngineOption { get; }
38
-
39
- /// <summary>
40
- /// Name of this engine
41
- /// </summary>
42
- public virtual string Name => EngineOption.ToString();
43
-
44
- public virtual Url BaseUrl { get; }
45
-
46
- public bool IsAdvanced { get; protected init; }
47
-
48
- public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(15);
49
-
50
- public string? EndpointUrl { get; }
51
-
52
- protected long? MaxSize { get; set; }
53
-
54
- protected virtual string[] ErrorBodyMessages { get; } = [];
55
-
56
- protected BaseSearchEngine(string baseUrl, string? endpoint = null)
57
- {
58
- BaseUrl = baseUrl;
59
- IsAdvanced = true;
60
- EndpointUrl = endpoint;
61
- MaxSize = null;
62
- }
63
-
64
- protected static readonly ILogger Logger = AppSupport.Factory.CreateLogger(nameof(BaseSearchEngine));
65
-
66
- /*protected IFlurlRequest Build(IFlurlRequest request)
67
- {
68
- return request.WithTimeout(Timeout);
69
- }*/
70
-
71
-
72
21
static BaseSearchEngine()
73
22
{
74
- /*var handler = new LoggingHttpMessageHandler(Logger)
75
- {
76
- InnerHandler = new HttpLoggingHandler(Logger)
77
- {
78
- InnerHandler = new HttpClientHandler()
79
- }
80
- };
81
-
82
- Client = new FlurlClient(new HttpClient(handler))
83
- {
84
- Settings =
85
- {
86
- Redirects =
87
- {
88
- Enabled = true,
89
- AllowSecureToInsecure = true,
90
- ForwardAuthorizationHeader = true,
91
- MaxAutoRedirects = 20,
92
- },
93
- }
94
- };*/
95
-
96
-
97
23
Client = (FlurlClient) FlurlHttp.Clients.GetOrAdd(nameof(BaseSearchEngine), null, builder =>
98
24
{
99
25
builder.Headers.AddOrReplace("User-Agent", HttpUtilities.UserAgent);
100
-
26
+
101
27
// builder.Settings.JsonSerializer = new DefaultJsonSerializer();
102
28
103
29
builder.Settings.AllowedHttpStatusRange = "*";
104
- builder.OnError(f=>
30
+
31
+ builder.OnError(f =>
105
32
{
33
+ Debugger.Break();
106
34
Logger.LogError(f.Exception, $"from {f.Request}");
107
- return;
108
35
});
109
36
110
37
builder.AddMiddleware(() => new HttpLoggingHandler(Logger));
111
38
112
- });;
113
- }
114
-
115
- public override string ToString()
116
- {
117
- return $"{Name}: {BaseUrl} {Timeout}";
118
- }
119
-
120
- public virtual async Task<SearchResult> GetResultAsync(SearchQuery query, CancellationToken token = default)
121
- {
122
- var b = await VerifyQueryAsync(query);
123
-
124
- /*
125
- if (!b) {
126
- // throw new SmartImageException($"{query}");
127
- Debug.WriteLine($"{query} : Verification error", LogCategories.C_ERROR);
128
- }
129
- */
130
-
131
- var srs = b ? SearchResultStatus.None : SearchResultStatus.IllegalInput;
132
-
133
- var res = new SearchResult(this)
134
- {
135
- RawUrl = GetRawUrl(query),
136
- ErrorMessage = null,
137
- Status = srs
138
- };
139
-
140
- lock (res.Results) {
141
- res.Results.Add(res.GetRawResultItem());
142
- }
143
-
144
- Debug.WriteLine($"{Name} | {query} - {res.Status}", LogCategories.C_INFO);
145
-
146
- return res;
39
+ });
40
+ ;
147
41
}
148
42
149
- protected virtual Url GetRawUrl(SearchQuery query )
43
+ protected BaseSearchEngine(string baseUrl, string? endpoint = null )
150
44
{
151
- //
152
- Url u = ((BaseUrl + query.Upload));
153
-
154
- return u;
45
+ BaseUrl = baseUrl;
46
+ EndpointUrl = endpoint;
47
+ MaxSize = null;
155
48
}
156
49
157
- public virtual ValueTask<bool> VerifyQueryAsync(SearchQuery q)
158
- {
159
- /*if (q.Upload is not { }) {
160
- return false;
161
- }*/
162
-
163
- bool b = true;
50
+ protected static readonly ILogger Logger = AppSupport.Factory.CreateLogger(nameof(BaseSearchEngine));
164
51
165
- if (MaxSize.HasValue) {
166
- b = q.Source.Size <= MaxSize;
167
- }
52
+ /// <summary>
53
+ /// The corresponding <see cref="SearchEngineOptions" /> of this engine
54
+ /// </summary>
55
+ public abstract SearchEngineOptions EngineOption { get; }
168
56
169
- /*if (MaxSize == NA_SIZE || q.Size == NA_SIZE) {
170
- b = true;
171
- }
57
+ /// <summary>
58
+ /// Name of this engine
59
+ /// </summary>
60
+ public virtual string Name => EngineOption.ToString();
172
61
173
- else {
174
- b = q.Size <= MaxSize;
175
- }*/
62
+ public virtual Url BaseUrl { get; }
176
63
177
- return ValueTask.FromResult(b);
178
- }
64
+ public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(15);
179
65
66
+ public string? EndpointUrl { get; }
180
67
181
- // TODO: move config application to ctors?
68
+ protected long? MaxSize { get; set; }
182
69
183
- public abstract void Dispose() ;
70
+ protected virtual string[] ErrorBodyMessages { get; } = [] ;
184
71
185
- /*
186
- public static readonly BaseSearchEngine[] All =
187
- ReflectionHelper.CreateAllInAssembly<BaseSearchEngine>(InheritanceProperties.Subclass).ToArray();
188
- */
72
+ protected static FlurlClient Client { get; }
189
73
190
74
public static IEnumerable<BaseSearchEngine> GetSelectedEngines(SearchEngineOptions options)
191
75
{
@@ -242,21 +126,87 @@ public static IEnumerable<BaseSearchEngine> GetSelectedEngines(SearchEngineOptio
242
126
243
127
}
244
128
245
- #region
129
+ public static bool operator ==(BaseSearchEngine? left, BaseSearchEngine? right)
130
+ {
131
+ return Equals(left, right);
132
+ }
133
+
134
+ public static bool operator !=(BaseSearchEngine? left, BaseSearchEngine? right)
135
+ {
136
+ return !Equals(left, right);
137
+ }
246
138
247
- public bool Equals(BaseSearchEngine? other )
139
+ public virtual async Task<SearchResult> GetResultAsync(SearchQuery query, CancellationToken token = default )
248
140
{
249
- if (ReferenceEquals(null, other)) return false;
250
- if (ReferenceEquals(this, other)) return true;
141
+ var b = await VerifyQueryAsync(query);
251
142
252
- return EngineOption == other.EngineOption;
143
+ /*
144
+ if (!b) {
145
+ // throw new SmartImageException($"{query}");
146
+ Debug.WriteLine($"{query} : Verification error", LogCategories.C_ERROR);
147
+ }
148
+ */
149
+
150
+ var srs = b ? SearchResultStatus.None : SearchResultStatus.IllegalInput;
151
+
152
+ var res = new SearchResult(this)
153
+ {
154
+ RawUrl = GetRawUrl(query),
155
+ ErrorMessage = null,
156
+ Status = srs
157
+ };
158
+
159
+ lock (res.Results) {
160
+ res.Results.Add(res.GetRawResultItem());
161
+ }
162
+
163
+ Debug.WriteLine($"{Name} | {query} - {res.Status}", LogCategories.C_INFO);
164
+
165
+ return res;
166
+ }
167
+
168
+ protected virtual Url GetRawUrl(SearchQuery query)
169
+ {
170
+ //
171
+ Url u = ((BaseUrl + query.Upload));
172
+
173
+ return u;
174
+ }
175
+
176
+ public virtual ValueTask<bool> VerifyQueryAsync(SearchQuery q)
177
+ {
178
+ bool b = true;
179
+
180
+ if (MaxSize.HasValue) {
181
+ b = q.Source.Size <= MaxSize;
182
+ }
183
+
184
+ return ValueTask.FromResult(b);
185
+ }
186
+
187
+ public int GetHashCode(BaseSearchEngine obj)
188
+ {
189
+ return (int) obj.EngineOption;
190
+ }
191
+
192
+ public override string ToString()
193
+ {
194
+ return $"{Name}: {BaseUrl} {Timeout}";
253
195
}
254
196
255
197
public override bool Equals(object? obj)
256
198
{
257
- if (ReferenceEquals(null, obj)) return false;
258
- if (ReferenceEquals(this, obj)) return true;
259
- if (obj.GetType() != this.GetType()) return false;
199
+ if (obj is null) {
200
+ return false;
201
+ }
202
+
203
+ if (ReferenceEquals(this, obj)) {
204
+ return true;
205
+ }
206
+
207
+ if (obj.GetType() != GetType()) {
208
+ return false;
209
+ }
260
210
261
211
return Equals((BaseSearchEngine) obj);
262
212
}
@@ -266,21 +216,32 @@ public override int GetHashCode()
266
216
return (int) EngineOption;
267
217
}
268
218
269
- public static bool operator ==(BaseSearchEngine? left, BaseSearchEngine? right)
270
- {
271
- return Equals(left, right);
272
- }
219
+ public abstract void Dispose();
273
220
274
- public static bool operator != (BaseSearchEngine? left, BaseSearchEngine? right )
221
+ public bool Equals (BaseSearchEngine? other )
275
222
{
276
- return !Equals(left, right);
223
+ if (other is null) {
224
+ return false;
225
+ }
226
+
227
+ if (ReferenceEquals(this, other)) {
228
+ return true;
229
+ }
230
+
231
+ return EngineOption == other.EngineOption;
277
232
}
278
233
279
- public int GetHashCode(BaseSearchEngine obj )
234
+ /*protected IFlurlRequest Build(IFlurlRequest request )
280
235
{
281
- return (int) obj.EngineOption;
282
- }
236
+ return request.WithTimeout(Timeout);
237
+ }*/
238
+
283
239
284
- #endregion
240
+ // TODO: move config application to ctors?
241
+
242
+ /*
243
+ public static readonly BaseSearchEngine[] All =
244
+ ReflectionHelper.CreateAllInAssembly<BaseSearchEngine>(InheritanceProperties.Subclass).ToArray();
245
+ */
285
246
286
247
}
0 commit comments