Skip to content

Commit d7a5c00

Browse files
committed
Various improvements
1 parent d2e955f commit d7a5c00

File tree

11 files changed

+115
-86
lines changed

11 files changed

+115
-86
lines changed

SmartImage.Lib/SearchClient.cs

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
// ReSharper disable UnusedMember.Global
2222

2323
[assembly: InternalsVisibleTo("SmartImage")]
24+
2425
namespace SmartImage.Lib;
2526

2627
/// <summary>
@@ -77,7 +78,9 @@ public SearchClient(SearchConfig config)
7778
/// </summary>
7879
public List<SearchResult> FilteredResults { get; }
7980

80-
81+
/// <summary>
82+
/// Number of pending results
83+
/// </summary>
8184
public int Pending { get; private set; }
8285

8386
/// <summary>
@@ -190,7 +193,7 @@ public async Task RunSearchAsync()
190193
var args = new SearchCompletedEventArgs
191194
{
192195
Results = Results,
193-
Detailed = PredicateFilter(Results, DetailPredicate),
196+
Detailed = ApplyPredicateFilter(Results, DetailPredicate),
194197
Direct = DirectResults,
195198
Filtered = FilteredResults
196199
};
@@ -206,12 +209,27 @@ public Task<List<ImageResult>> WaitForDirectResults()
206209
{
207210
return Task.Run(() =>
208211
{
209-
while (Results.Any() && !DirectResults.Any()) { }
212+
while (Results.Any() && !DirectResults.Any()) {
213+
if (IsComplete) {
214+
List<ImageResult> rescan = RescanImageResults(Results);
215+
DirectResults.AddRange(rescan);
216+
217+
break;
218+
}
219+
}
210220

211221
return DirectResults;
212222
});
213223
}
214224

225+
private static List<ImageResult> RescanImageResults(List<SearchResult> results)
226+
{
227+
var b = results.SelectMany(x => x.AllResults.Where(x2 => x2.Direct != null))
228+
.OrderByDescending(x => x.PixelResolution)
229+
.ToList();
230+
return b;
231+
}
232+
215233
/// <summary>
216234
/// Refines search results by searching with the most-detailed result (<see cref="FindDirectResults" />).
217235
/// </summary>
@@ -221,7 +239,6 @@ public async Task RefineSearchAsync()
221239
throw SearchException;
222240
}
223241

224-
225242
var directResult = DirectResults.FirstOrDefault();
226243

227244
if (directResult == null) {
@@ -264,7 +281,7 @@ private void FindDirectResults(object state, SearchResult value, int take1 = 10,
264281
}
265282

266283

267-
public static List<ImageResult> PredicateFilter(List<SearchResult> results, Predicate<SearchResult> predicate)
284+
public static List<ImageResult> ApplyPredicateFilter(List<SearchResult> results, Predicate<SearchResult> predicate)
268285
{
269286
var query = results.Where(r => predicate(r))
270287
.SelectMany(r => r.AllResults)
@@ -330,7 +347,6 @@ public static BaseSearchEngine[] GetAllSearchEngines()
330347
private static readonly SmartImageException SearchException = new("Search must be completed");
331348
}
332349

333-
334350
public sealed class DirectResultsFoundEventArgs : EventArgs
335351
{
336352
/// <remarks>

SmartImage.Lib/Searching/ImageResult.cs

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,15 @@
55
using System.Drawing;
66
using System.Linq;
77
using System.Reflection;
8+
using JetBrains.Annotations;
89
using Kantan.Model;
910
using Kantan.Numeric;
1011
using Kantan.Text;
1112
using SmartImage.Lib.Utilities;
1213

1314
// ReSharper disable CognitiveComplexity
1415
#pragma warning disable 8629,CA1416
15-
#nullable enable
16+
#nullable disable
1617

1718
namespace SmartImage.Lib.Searching;
1819

@@ -38,7 +39,8 @@ public sealed class ImageResult : IOutline
3839
/// <summary>
3940
/// Direct image link of <see cref="Url"/>
4041
/// </summary>
41-
public Uri? Direct { get; set; }
42+
[CanBeNull]
43+
public Uri Direct { get; set; }
4244

4345
/// <summary>
4446
/// Similarity
@@ -58,27 +60,32 @@ public sealed class ImageResult : IOutline
5860
/// <summary>
5961
/// Description, caption
6062
/// </summary>
61-
public string? Description { get; set; }
63+
[CanBeNull]
64+
public string Description { get; set; }
6265

6366
/// <summary>
6467
/// Artist, author, creator
6568
/// </summary>
66-
public string? Artist { get; set; }
69+
[CanBeNull]
70+
public string Artist { get; set; }
6771

6872
/// <summary>
6973
/// Source
7074
/// </summary>
71-
public string? Source { get; set; }
75+
[CanBeNull]
76+
public string Source { get; set; }
7277

7378
/// <summary>
7479
/// Character(s) present in image
7580
/// </summary>
76-
public string? Characters { get; set; }
81+
[CanBeNull]
82+
public string Characters { get; set; }
7783

7884
/// <summary>
7985
/// Site name
8086
/// </summary>
81-
public string? Site { get; set; }
87+
[CanBeNull]
88+
public string Site { get; set; }
8289

8390
/// <summary>
8491
/// Date of image
@@ -88,7 +95,8 @@ public sealed class ImageResult : IOutline
8895
/// <summary>
8996
/// Result name
9097
/// </summary>
91-
public string? Name { get; set; }
98+
[CanBeNull]
99+
public string Name { get; set; }
92100

93101
/// <summary>
94102
/// Whether <see cref="Width"/> and <see cref="Height"/> values are available
@@ -124,7 +132,8 @@ public float? MegapixelResolution
124132
/// </summary>
125133
public Dictionary<string, object> OtherMetadata { get; }
126134

127-
public Image? Image { get; set; }
135+
[CanBeNull]
136+
public Image Image { get; set; }
128137

129138
/// <summary>
130139
/// The display resolution of this image
@@ -248,9 +257,6 @@ public void UpdateImageData()
248257
Width = Image.Width;
249258
Height = Image.Height;
250259

251-
//
252-
// OtherMetadata.Add("Size", MathHelper.ConvertToUnit(rg.Length));
253-
// OtherMetadata.Add("Mime", MediaTypes.ResolveFromData(rg));
254260
}
255261
}
256262

SmartImage.Lib/Searching/SearchResult.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,9 @@ public enum ResultStatus
4646
/// </summary>
4747
Extraneous,
4848

49+
/// <summary>
50+
/// Engine which returned the result is on cooldown
51+
/// </summary>
4952
Cooldown
5053
}
5154

SmartImage.Lib/Utilities/ImageHelper.cs

Lines changed: 24 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
using AngleSharp.Html.Dom;
1414
using JetBrains.Annotations;
1515
using Kantan.Net;
16+
using Kantan.Utilities;
1617
using Novus.Win32;
1718
using RestSharp;
1819
using static Kantan.Diagnostics.LogCategories;
@@ -82,7 +83,7 @@ public static Dictionary<string, string> UtilitiesMap
8283
[CanBeNull]
8384
public static string Download(Uri src, string path)
8485
{
85-
var filename = NormalizeFilename(src);
86+
var filename = UriUtilities.NormalizeFilename(src);
8687

8788
string combine = Path.Combine(path, filename);
8889

@@ -105,38 +106,7 @@ public static string Download(Uri src, string path)
105106
}
106107
}
107108

108-
private static string NormalizeFilename(Uri src)
109-
{
110-
string filename = Path.GetFileName(src.AbsolutePath);
111-
112-
if (!Path.HasExtension(filename)) {
113-
114-
// If no format is specified/found, just append a jpg extension
115-
string ext = ".jpg";
116-
117-
// For Pixiv (?)
118-
var kv = HttpUtility.ParseQueryString(src.Query);
119-
120-
var t = kv["format"];
121-
122-
if (t != null) {
123-
ext = $".{t}";
124-
}
125-
126-
filename += ext;
127-
128-
}
129-
130-
// Stupid URI parameter Twitter appends to filenames
131-
132-
var i = filename.IndexOf(":large", StringComparison.Ordinal);
133-
134-
if (i != -1) {
135-
filename = filename[..i];
136-
}
137-
138-
return filename;
139-
}
109+
140110

141111
/// <summary>
142112
/// Scans for direct images within a webpage.
@@ -146,7 +116,6 @@ private static string NormalizeFilename(Uri src)
146116
/// <param name="timeoutMS"></param>
147117
public static async Task<List<string>> ScanForImages(string url, int count = 10, long timeoutMS = TimeoutMS)
148118
{
149-
150119
var images = new List<string>();
151120

152121
IHtmlDocument document;
@@ -195,14 +164,7 @@ public static async Task<List<string>> ScanForImages(string url, int count = 10,
195164
count--;
196165
}
197166
}
198-
199-
/*for (int i = 0; i < images.Count; i++) {
200-
for (int j = i + 1; j < images.Count; j++) {
201-
if (UrlUtilities.UrlEqual(images[i], images[j])) {
202-
Debug.WriteLine($"{images[i]} = {images[j]}");
203-
}
204-
}
205-
}*/
167+
206168

207169
return images;
208170
}
@@ -229,10 +191,24 @@ public static bool IsImage(string url, long timeout, DirectImageCriterion direct
229191
return false;
230192
}
231193

232-
var a = response.ContentType.StartsWith("image") && response.ContentType != "image/svg+xml";
233-
var b = response.ContentLength >= 50_000;
194+
/* Check content-type */
234195

235-
return a && b;
196+
// The content-type returned from the response may not be the actual content-type, so
197+
// we'll resolve it using binary data instead to be sure
198+
199+
var stream = WebUtilities.GetStream(url);
200+
var buffer = new byte[256];
201+
stream.Read(buffer, 0, buffer.Length);
202+
// var rg = response.RawBytes;
203+
var m = MediaTypes.ResolveFromData(buffer);
204+
205+
// var a = response.ContentType.StartsWith("image") && response.ContentType != "image/svg+xml";
206+
// var b = response.ContentLength >= 50_000;
207+
208+
var a = m.StartsWith("image") && m != "image/svg+xml";
209+
// var b = stream.Length >= 50_000;
210+
211+
return a;
236212
default:
237213
throw new ArgumentOutOfRangeException(nameof(directCriterion), directCriterion, null);
238214
}
@@ -291,6 +267,9 @@ public static DisplayResolutionType GetDisplayResolution(int w, int h)
291267
public static Bitmap ResizeImage(Bitmap mg, Size newSize)
292268
{
293269
// todo
270+
/*
271+
* Adapted from https://stackoverflow.com/questions/5243203/how-to-compress-jpg-image
272+
*/
294273
double ratio = 0d;
295274
double myThumbWidth = 0d;
296275
double myThumbHeight = 0d;

SmartImage/Core/AppInfo.cs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -96,14 +96,11 @@ public static void Setup()
9696
foreach (string s in oldFolders) {
9797
FileSystem.RemoveFromPath(s);
9898
}
99-
100-
99+
101100
if (!IsAppFolderInPath) {
102101
AppIntegration.HandlePath(true);
103102
}
104103

105104
Debug.WriteLine($"Cli utilities: {ImageHelper.Utilities.QuickJoin()}", C_INFO);
106-
107-
108105
}
109106
}

0 commit comments

Comments
 (0)