Skip to content

Commit 04b2bab

Browse files
author
LAB02 Research
committed
v2022.3.15.0
1 parent e325cb3 commit 04b2bab

File tree

8 files changed

+134
-52
lines changed

8 files changed

+134
-52
lines changed

src/DeepLClient/Controls/TextPage.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -214,7 +214,7 @@ private void TbSource_TextChanged(object sender, EventArgs e)
214214
LblCharacters.Text = TbSource.Text.Length.ToString();
215215
LblCost.Text = SubscriptionManager.CalculateCost(TbSource.Text.Length, false);
216216
}
217-
217+
218218
/// <summary>
219219
/// Shows the dragdrop effect when hovering a file or text.
220220
/// </summary>
@@ -300,7 +300,7 @@ private void CopyToClipboard(bool force = false)
300300
{
301301
// copy the text
302302
var cleanText = TbTranslated.Text.Trim();
303-
303+
304304
// copy it to the clipboard if not empty and configured as such
305305
if (string.IsNullOrWhiteSpace(cleanText) || (!force && !Variables.AppSettings.CopyTranslationToClipboard)) return;
306306

@@ -327,7 +327,7 @@ private void CopyToClipboard(bool force = false)
327327
Log.Fatal(ex, "[TEXT] Error while copying to clipboard: {err}", ex.Message);
328328
}
329329
}
330-
330+
331331
/// <summary>
332332
/// Resets and hides the detected source language info
333333
/// </summary>

src/DeepLClient/Controls/TextPage.resx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@
6161
<data name="resource.Image" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
6262
<value>
6363
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAO
64-
vgAADr4B6kKxwAAAAIJJREFUOE+1kNENgCAMBRnYPRjAARyBDwdxFWABLVhMpRQU8ZKLTX15ARTFOTeD
64+
vAAADrwBlbxySQAAAIJJREFUOE+1kNENgCAMBRnYPRjAARyBDwdxFWABLVhMpRQU8ZKLTX15ARTFOTeD
6565
e0ODcU4I4ChSzXwu6AIan9xb0sQjvdV7v8BXh7mrANTW2inMvQWX4wvwbUVYni0KoWSxAB5jvS0a0Cy4
6666
4fokFWShaAwAdGZUfyL/FuTvIUjurdQBaE0luFgHKUIAAAAASUVORK5CYII=
6767
</value>

src/DeepLClient/Controls/UrlPage.Designer.cs

Lines changed: 5 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/DeepLClient/Controls/UrlPage.cs

Lines changed: 23 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -184,26 +184,26 @@ internal async void ExecuteTranslation()
184184
LblState.Visible = true;
185185

186186
// get the content
187-
var (success, isReadable, sourceText, error) = await UrlManager.GetReadableContentAsync(url, isLocal);
188-
if (!success)
187+
var webpageResult = await UrlManager.GetReadableContentAsync(url, isLocal);
188+
if (!webpageResult.Success)
189189
{
190-
LblState.Text = !string.IsNullOrEmpty(error)
191-
? $"something went wrong while trying to fetch your webpage:\r\n\r\n{error}"
190+
LblState.Text = !string.IsNullOrEmpty(webpageResult.Error)
191+
? $"something went wrong while trying to fetch your webpage:\r\n\r\n{webpageResult.Error}"
192192
: "something went wrong while trying to fetch your webpage";
193193
return;
194194
}
195195

196196
// check it
197-
if (string.IsNullOrWhiteSpace(sourceText))
197+
if (string.IsNullOrWhiteSpace(webpageResult.Content))
198198
{
199199
LblState.Text = "your webpage doesn't seem to contain any text";
200200
return;
201201
}
202202

203203
// do we have enough chars left?
204-
if (await SubscriptionManager.CharactersWillExceedLimitAsync(sourceText.Length))
204+
if (await SubscriptionManager.CharactersWillExceedLimitAsync(webpageResult.Content.Length))
205205
{
206-
using var limit = new LimitExceeded(sourceText.Length);
206+
using var limit = new LimitExceeded(webpageResult.Content.Length);
207207
var ignoreLimit = limit.ShowDialog();
208208
if (ignoreLimit != DialogResult.OK)
209209
{
@@ -213,7 +213,7 @@ internal async void ExecuteTranslation()
213213
}
214214

215215
// readable?
216-
if (!isReadable) PbWarning.Visible = true;
216+
if (!webpageResult.IsReadable) PbWarning.Visible = true;
217217

218218
// fetch the source language
219219
string sourceLanguage = null;
@@ -250,21 +250,24 @@ internal async void ExecuteTranslation()
250250

251251
// don't use formality, send the text as-is to DeepL for translation
252252
var translatedText = await Variables.Translator.TranslateTextAsync(
253-
sourceText,
253+
webpageResult.Content,
254254
sourceLanguage,
255255
targetLanguage,
256256
options);
257-
258-
// hide info
259-
LblState.Text = string.Empty;
260-
LblState.Visible = false;
261-
257+
262258
// set the cost
263259
LblCharacters.Text = translatedText.Text.Length.ToString();
264260
LblCost.Text = SubscriptionManager.CalculateCost(translatedText.Text.Length, false);
265261

262+
// wrap it in html for styling
263+
var source = UrlManager.WrapContentInHtml(translatedText.Text, webpageResult.Title);
264+
266265
// set the translated text
267-
WebView.NavigateToString(translatedText.Text);
266+
WebView.NavigateToString(source);
267+
268+
// hide info
269+
LblState.Text = string.Empty;
270+
LblState.Visible = false;
268271

269272
// store the selected languages
270273
SettingsManager.StoreSelectedLanguages(CbSourceLanguage, CbTargetLanguage);
@@ -318,7 +321,7 @@ private void ClearWebpageInterface(bool clearStateLabel = true)
318321

319322
WebView.NavigateToString(string.Empty);
320323
}
321-
324+
322325
/// <summary>
323326
/// Shows the dragdrop effect when hovering a file or text.
324327
/// </summary>
@@ -405,7 +408,7 @@ private void ProcessDrop(DragEventArgs e)
405408

406409
// set the value
407410
TbUrl.Text = value;
408-
411+
409412
// enable auto detect
410413
CbSourceLanguage.SelectedItem = Variables.SourceLanguages.GetEntry("AUTO DETECT");
411414

@@ -417,7 +420,7 @@ private void ProcessDrop(DragEventArgs e)
417420
Log.Fatal(ex, "[URL] Error while processing dropped content: {err}", ex.Message);
418421
}
419422
}
420-
423+
421424
/// <summary>
422425
/// Copies the current webview text to clipboard
423426
/// </summary>
@@ -430,12 +433,8 @@ private async void CopySourceToClipboard(bool force = false)
430433
var cleanText = await WebView.ExecuteScriptAsync("document.body.innerText");
431434
if (string.IsNullOrWhiteSpace(cleanText)) return;
432435

433-
// trim
436+
// clean it up
434437
cleanText = UrlManager.CleanText(cleanText.Trim());
435-
436-
// optionally remove start & end quotes
437-
if (cleanText.StartsWith("\"")) cleanText = cleanText.Remove(0, 1);
438-
if (cleanText.EndsWith("\"")) cleanText = cleanText.Remove(cleanText.Length - 1, 1);
439438

440439
// copy it to the clipboard if not empty and configured as such
441440
if (string.IsNullOrWhiteSpace(cleanText) || (!force && !Variables.AppSettings.CopyTranslationToClipboard)) return;
@@ -629,7 +628,7 @@ private async void BtnOpenInBrowser_Click(object sender, EventArgs e)
629628

630629
// prepare a temp file
631630
var tempFile = Path.Combine(Variables.WebPagesCachePath, $"{Guid.NewGuid().ToString().Replace("-", "")}.html");
632-
631+
633632
// write the source to it
634633
await File.WriteAllTextAsync(tempFile, source);
635634

src/DeepLClient/Controls/UrlPage.resx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@
7575
<data name="resource.Image" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
7676
<value>
7777
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAO
78-
vgAADr4B6kKxwAAAAIJJREFUOE+1kNENgCAMBRnYPRjAARyBDwdxFWABLVhMpRQU8ZKLTX15ARTFOTeD
78+
vAAADrwBlbxySQAAAIJJREFUOE+1kNENgCAMBRnYPRjAARyBDwdxFWABLVhMpRQU8ZKLTX15ARTFOTeD
7979
e0ODcU4I4ChSzXwu6AIan9xb0sQjvdV7v8BXh7mrANTW2inMvQWX4wvwbUVYni0KoWSxAB5jvS0a0Cy4
8080
4fokFWShaAwAdGZUfyL/FuTvIUjurdQBaE0luFgHKUIAAAAASUVORK5CYII=
8181
</value>

src/DeepLClient/DeepLClient.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
<ImplicitUsings>enable</ImplicitUsings>
99
<ApplicationIcon>Resources\icon_white_32.ico</ApplicationIcon>
1010
<Title>DeepL Translator</Title>
11-
<Version>2023.3.14.0</Version>
11+
<Version>2023.3.15.0</Version>
1212
<Authors>LAB02 RESEARCH</Authors>
1313
<Description>Front-end client for DeepL translation services.</Description>
1414
</PropertyGroup>

src/DeepLClient/Managers/UrlManager.cs

Lines changed: 51 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,10 @@
66
using System.Net.Sockets;
77
using System.Text;
88
using System.Threading.Tasks;
9+
using AngleSharp.Dom;
910
using Serilog;
10-
using static System.Net.Mime.MediaTypeNames;
11+
using DeepLClient.Models;
12+
using Newtonsoft.Json;
1113

1214
namespace DeepLClient.Managers
1315
{
@@ -19,33 +21,35 @@ internal static class UrlManager
1921
/// <param name="url"></param>
2022
/// <param name="isLocaLFile"></param>
2123
/// <returns></returns>
22-
internal static async Task<(bool success, bool isReadable, string content, string error)> GetReadableContentAsync(string url, bool isLocaLFile = false)
24+
internal static async Task<WebpageResult> GetReadableContentAsync(string url, bool isLocaLFile = false)
2325
{
26+
var webpageResult = new WebpageResult();
27+
2428
try
2529
{
2630
// fetch the content if it's a local file, otherwise download it
2731
var reader = isLocaLFile
2832
? new Reader(url, await File.ReadAllTextAsync(url))
2933
: new Reader(url);
30-
34+
3135
// get the article
3236
var article = await reader.GetArticleAsync();
33-
37+
3438
// readable?
3539
if (!article.IsReadable)
3640
{
3741
// nope
3842
Log.Warning("[URL] Fetching readable text failed: {url}", url);
39-
return (true, false, article.Content, "unable to determine what part of the site is relevant text");
43+
return webpageResult.SetReadableFailed(article.Content, article.Title);
4044
}
41-
42-
// yep
43-
return (true, true, article.Content, string.Empty);
45+
46+
// done
47+
return webpageResult.SetSuccess(article.Content, article.Title);
4448
}
4549
catch (UriFormatException ex)
4650
{
4751
Log.Fatal(ex, "[URL] Unable to parse host '{url}': {err}", url, ex.Message);
48-
return (false, false, string.Empty, "provided url is in the wrong format");
52+
return webpageResult.SetFailed("provided url is in the wrong format");
4953
}
5054
catch (HttpRequestException ex)
5155
{
@@ -57,25 +61,25 @@ internal static class UrlManager
5761

5862
return exc.SocketErrorCode switch
5963
{
60-
SocketError.HostNotFound => (false, false, string.Empty, "the remote host address wasn't found"),
61-
SocketError.AccessDenied => (false, false, string.Empty, "access denied by the remote host"),
62-
SocketError.TimedOut => (false, false, string.Empty, "the host didn't respond"),
63-
SocketError.HostDown => (false, false, string.Empty, "the remote host is offline"),
64-
SocketError.HostUnreachable or SocketError.NetworkUnreachable => (false, false, string.Empty, "the remote host couldn't be reached"),
65-
SocketError.NotConnected => (false, false, string.Empty, "no internet connection"),
66-
_ => (false, false, string.Empty, $"error trying to contact the host: {exc.SocketErrorCode.ToString().ToLower()}")
64+
SocketError.HostNotFound => webpageResult.SetFailed("the remote host address wasn't found"),
65+
SocketError.AccessDenied => webpageResult.SetFailed("access denied by the remote host"),
66+
SocketError.TimedOut => webpageResult.SetFailed("the host didn't respond"),
67+
SocketError.HostDown => webpageResult.SetFailed("the remote host is offline"),
68+
SocketError.HostUnreachable or SocketError.NetworkUnreachable => webpageResult.SetFailed("the remote host couldn't be reached"),
69+
SocketError.NotConnected => webpageResult.SetFailed("no internet connection"),
70+
_ => webpageResult.SetFailed($"error trying to contact the host: {exc.SocketErrorCode.ToString().ToLower()}")
6771
};
6872
}
6973

7074
var statusCode = ex.StatusCode.ToString();
71-
return !string.IsNullOrWhiteSpace(statusCode)
72-
? (false, false, string.Empty, $"error trying to contact the host: {statusCode}")
73-
: (false, false, string.Empty, "unknown error trying to contact the host");
75+
return !string.IsNullOrWhiteSpace(statusCode)
76+
? webpageResult.SetFailed($"error trying to contact the host: {statusCode}")
77+
: webpageResult.SetFailed("unknown error trying to contact the host");
7478
}
7579
catch (Exception ex)
7680
{
7781
Log.Fatal(ex, "[URL] Unable to process host '{url}': {err}", url, ex.Message);
78-
return (false, false, string.Empty, "unknown error trying to contact the host");
82+
return webpageResult.SetFailed("unknown error trying to contact the host");
7983
}
8084
}
8185

@@ -88,6 +92,9 @@ internal static string CleanText(string rawText)
8892
{
8993
if (string.IsNullOrEmpty(rawText)) return string.Empty;
9094

95+
if (rawText.StartsWith("\"")) rawText = rawText.Remove(0, 1);
96+
if (rawText.EndsWith("\"")) rawText = rawText.Remove(rawText.Length - 1, 1);
97+
9198
rawText = rawText.Replace("\\n\\n", Environment.NewLine);
9299
rawText = rawText.Replace("\\n", Environment.NewLine);
93100
rawText = rawText.Replace("\\\"", "\"");
@@ -115,5 +122,29 @@ internal static bool IsLocalOrNetworkFile(string value)
115122
if (string.IsNullOrWhiteSpace(value)) return false;
116123
return value.Substring(1, 2) == ":\\" || value[..2] == "\\\\";
117124
}
125+
126+
/// <summary>
127+
/// Wraps the provided content into a reading mode html page, and adds the title
128+
/// </summary>
129+
/// <param name="content"></param>
130+
/// <param name="title"></param>
131+
/// <returns></returns>
132+
internal static string WrapContentInHtml(string content, string title)
133+
{
134+
var htmlContent = new StringBuilder();
135+
htmlContent.AppendLine("<html>");
136+
htmlContent.AppendLine("<head>");
137+
htmlContent.AppendLine($"<title>{title}</title>");
138+
htmlContent.AppendLine("<style>");
139+
htmlContent.AppendLine("a:link, a:visited, a:hover, a:active { color: #6590fd }");
140+
htmlContent.AppendLine("</style>");
141+
htmlContent.AppendLine("</head>");
142+
htmlContent.AppendLine("<body style=\"background-color: #3f3f46; color: #f1f1f1;\">");
143+
htmlContent.AppendLine(content);
144+
htmlContent.AppendLine("</body>");
145+
htmlContent.AppendLine("</html>");
146+
147+
return htmlContent.ToString();
148+
}
118149
}
119150
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
namespace DeepLClient.Models
2+
{
3+
public static class WebpageResultExtensions
4+
{
5+
public static WebpageResult SetReadableFailed(this WebpageResult webpageResult, string content, string title)
6+
{
7+
webpageResult.Success = true;
8+
webpageResult.IsReadable = false;
9+
webpageResult.Content = content;
10+
webpageResult.Title = title;
11+
webpageResult.Error = "unable to determine what part of the site is relevant text";
12+
13+
return webpageResult;
14+
}
15+
16+
public static WebpageResult SetSuccess(this WebpageResult webpageResult, string content, string title)
17+
{
18+
webpageResult.Success = true;
19+
webpageResult.IsReadable = true;
20+
webpageResult.Content = content;
21+
webpageResult.Title = title;
22+
23+
return webpageResult;
24+
}
25+
26+
public static WebpageResult SetFailed(this WebpageResult webpageResult, string error)
27+
{
28+
webpageResult.Success = false;
29+
webpageResult.IsReadable = false;
30+
webpageResult.Error = error;
31+
32+
return webpageResult;
33+
}
34+
}
35+
36+
public class WebpageResult
37+
{
38+
public WebpageResult()
39+
{
40+
//
41+
}
42+
43+
public bool Success { get; set; }
44+
public bool IsReadable { get; set; }
45+
public string Content { get; set; } = string.Empty;
46+
public string Title { get; set; } = string.Empty;
47+
public string Error { get; set; } = string.Empty;
48+
}
49+
}

0 commit comments

Comments
 (0)