Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Refactor to reduce complexity (#735)

Leendert de Borst6e244e611c14
diff --git a/src/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceCard.razor b/src/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceCard.razor
index 4da48577c..e1c9e6cc2 100644
--- a/src/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceCard.razor
+++ b/src/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceCard.razor
@@ -310,104 +310,141 @@
return;
}
- IsImporting = true;
- ImportError = null;
- ImportSuccessMessage = null;
- StateHasChanged();
-
- // Let UI update to start showing the loading indicator as the save database call below can block the UI thread momentarily.
- await Task.Delay(50);
+ await InitializeImport();
try
{
if (ExtractFavicons)
{
- IsExtractingFavicons = true;
- FaviconExtractionProgress = 0;
- ExtractedFavicons.Clear();
- FaviconExtractionCancellation = new CancellationTokenSource();
- StateHasChanged();
-
- // Get credentials with URLs
- var credentialsWithUrls = ImportedCredentials.Where(c => !string.IsNullOrEmpty(c.ServiceUrl)).ToList();
- TotalFaviconsToExtract = credentialsWithUrls.Count;
-
- // Extract favicons
- foreach (var credential in credentialsWithUrls)
+ await ExtractFaviconsForCredentials();
+ if (FaviconExtractionCancellation?.Token.IsCancellationRequested == true)
{
- if (FaviconExtractionCancellation.Token.IsCancellationRequested)
- {
- break;
- }
-
- try
- {
- var apiReturn = await HttpClient.GetFromJsonAsync<FaviconExtractModel>($"v1/Favicon/Extract?url={credential.ServiceUrl!}");
- if (apiReturn?.Image is not null)
- {
- ExtractedFavicons[credential.ServiceUrl!] = apiReturn.Image;
- }
- }
- catch
- {
- // Ignore favicon extraction errors
- }
-
- FaviconExtractionProgress++;
- StateHasChanged();
- }
-
- if (FaviconExtractionCancellation.Token.IsCancellationRequested)
- {
- IsImporting = false;
- IsExtractingFavicons = false;
- StateHasChanged();
+ CleanupImport();
return;
}
}
- // Convert imported credentials to AliasVault format and insert them to the database.
- var credentials = BaseImporter.ConvertToCredential(ImportedCredentials);
- foreach (var credential in credentials)
- {
- if (!string.IsNullOrEmpty(credential.Service.Url))
- {
- if (ExtractedFavicons.TryGetValue(credential.Service.Url, out var favicon))
- {
- credential.Service.Logo = favicon;
- }
- }
- await CredentialService.InsertEntryAsync(credential, false, false);
+ await ImportCredentialsToDatabase();
+ }
+ catch (Exception ex)
+ {
+ ImportError = $"Error importing credentials: {ex.Message}";
+ }
+ finally
+ {
+ CleanupImport();
+ }
+ }
- // Add small delay to avoid blocking the UI thread.
- await Task.Delay(2);
- }
+ /// <summary>
+ /// Initializes the import.
+ /// </summary>
+ private async Task InitializeImport()
+ {
+ IsImporting = true;
+ ImportError = null;
+ ImportSuccessMessage = null;
+ StateHasChanged();
+
+ // Let UI update to start showing the loading indicator
+ await Task.Delay(50);
+ }
- // Save the database
- var success = await DbService.SaveDatabaseAsync();
- if (success)
+ /// <summary>
+ /// Cleans up the import.
+ /// </summary>
+ private void CleanupImport()
+ {
+ IsImporting = false;
+ IsExtractingFavicons = false;
+ StateHasChanged();
+ }
+
+ /// <summary>
+ /// Extracts favicons for credentials.
+ /// </summary>
+ private async Task ExtractFaviconsForCredentials()
+ {
+ IsExtractingFavicons = true;
+ FaviconExtractionProgress = 0;
+ ExtractedFavicons.Clear();
+ FaviconExtractionCancellation = new CancellationTokenSource();
+ StateHasChanged();
+
+ var credentialsWithUrls = ImportedCredentials.Where(c => !string.IsNullOrEmpty(c.ServiceUrl)).ToList();
+ TotalFaviconsToExtract = credentialsWithUrls.Count;
+
+ foreach (var credential in credentialsWithUrls)
+ {
+ if (FaviconExtractionCancellation.Token.IsCancellationRequested)
{
- GlobalNotificationService.AddSuccessMessage($"Successfully imported {ImportedCredentials.Count} credentials.");
- NavigationManager.NavigateTo("/credentials");
+ break;
}
- else
+
+ await ExtractFaviconForCredential(credential);
+ FaviconExtractionProgress++;
+ StateHasChanged();
+ }
+ }
+
+ /// <summary>
+ /// Extracts a favicon for a credential.
+ /// </summary>
+ /// <param name="credential">The credential to extract the favicon for.</param>
+ private async Task ExtractFaviconForCredential(ImportedCredential credential)
+ {
+ try
+ {
+ var apiReturn = await HttpClient.GetFromJsonAsync<FaviconExtractModel>($"v1/Favicon/Extract?url={credential.ServiceUrl!}");
+ if (apiReturn?.Image is not null)
{
- ImportError = "Error saving database.";
+ ExtractedFavicons[credential.ServiceUrl!] = apiReturn.Image;
}
}
- catch (Exception ex)
+ catch
{
- ImportError = $"Error importing credentials: {ex.Message}";
+ // Ignore favicon extraction errors
}
- finally
+ }
+
+ /// <summary>
+ /// Imports the credentials to the database.
+ /// </summary>
+ private async Task ImportCredentialsToDatabase()
+ {
+ var credentials = BaseImporter.ConvertToCredential(ImportedCredentials);
+ foreach (var credential in credentials)
{
- IsImporting = false;
- IsExtractingFavicons = false;
- StateHasChanged();
+ await ProcessSingleCredential(credential);
+ await Task.Delay(2); // Small delay to avoid blocking the UI thread
+ }
+
+ var success = await DbService.SaveDatabaseAsync();
+ if (success)
+ {
+ GlobalNotificationService.AddSuccessMessage($"Successfully imported {ImportedCredentials.Count} credentials.");
+ NavigationManager.NavigateTo("/credentials");
+ }
+ else
+ {
+ ImportError = "Error saving database.";
}
}
- /// <summary>
+ /// <summary>
+ /// Processes a single credential.
+ /// </summary>
+ /// <param name="credential">The credential to process.</param>
+ private async Task ProcessSingleCredential(Credential credential)
+ {
+ if (!string.IsNullOrEmpty(credential.Service.Url) && ExtractedFavicons.TryGetValue(credential.Service.Url, out var favicon))
+ {
+ credential.Service.Logo = favicon;
+ }
+ await CredentialService.InsertEntryAsync(credential, false, false);
+ }
+
+ /// <summary>
/// Handles the file upload.
/// </summary>
private async Task HandleFileUpload(InputFileChangeEventArgs e)
@@ -465,8 +502,11 @@
private int GetFaviconProgressPercentage()
{
- if (TotalFaviconsToExtract == 0) return 0;
- return (int)((FaviconExtractionProgress * 100) / TotalFaviconsToExtract);
+ if (TotalFaviconsToExtract == 0) {
+ return 0;
+ }
+
+ return (FaviconExtractionProgress * 100) / TotalFaviconsToExtract;
}
private void CancelFaviconExtraction()
diff --git a/src/Utilities/AliasVault.FaviconExtractor/FaviconExtractor.cs b/src/Utilities/AliasVault.FaviconExtractor/FaviconExtractor.cs
index 2e5679dd8..b70e627b3 100644
--- a/src/Utilities/AliasVault.FaviconExtractor/FaviconExtractor.cs
+++ b/src/Utilities/AliasVault.FaviconExtractor/FaviconExtractor.cs
@@ -30,67 +30,102 @@ public static class FaviconExtractor
/// <returns>Byte array for favicon image.</returns>
public static async Task<byte[]?> GetFaviconAsync(string url)
{
- // Add URL normalization - if no scheme is provided, try with https://
- if (!url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) && !url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
+ url = NormalizeUrl(url);
+ Uri uri = new(url);
+
+ if (!IsValidUri(uri))
{
- url = "https://" + url;
+ return null;
}
- Uri uri = new(url);
+ using HttpClient client = CreateHttpClient();
- // Only allow HTTP and HTTPS schemes and default ports.
- if (!_allowedSchemes.Contains(uri.Scheme) || !uri.IsDefaultPort)
+ HttpResponseMessage response = await client.GetAsync(uri);
+ if (!response.IsSuccessStatusCode)
{
return null;
}
- using HttpClient client = new(new HttpClientHandler
+ var faviconNodes = await GetFaviconNodesFromHtml(response, uri);
+ return await TryExtractFaviconFromNodes(faviconNodes, client, uri);
+ }
+
+ /// <summary>
+ /// Normalizes the URL by adding a scheme if it is missing.
+ /// </summary>
+ /// <param name="url">The URL to normalize.</param>
+ /// <returns>The normalized URL.</returns>
+ private static string NormalizeUrl(string url)
+ {
+ if (!url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) && !url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
+ {
+ return "https://" + url;
+ }
+
+ return url;
+ }
+
+ /// <summary>
+ /// Checks if the URI is valid.
+ /// </summary>
+ /// <param name="uri">The URI to check.</param>
+ /// <returns>True if the URI is valid, false otherwise.</returns>
+ private static bool IsValidUri(Uri uri)
+ {
+ return _allowedSchemes.Contains(uri.Scheme) && uri.IsDefaultPort;
+ }
+
+ /// <summary>
+ /// Creates a new HTTP client with default headers.
+ /// </summary>
+ /// <returns>The HTTP client.</returns>
+ private static HttpClient CreateHttpClient()
+ {
+ var client = new HttpClient(new HttpClientHandler
{
AllowAutoRedirect = true,
MaxAutomaticRedirections = 10,
- });
-
- // Set a timeout for the HTTP request to prevent long-running jobs which block the client UI.
- client.Timeout = TimeSpan.FromSeconds(5);
+ })
+ {
+ Timeout = TimeSpan.FromSeconds(5),
+ };
- // Add headers to mimic a browser.
client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
client.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
client.DefaultRequestHeaders.Add("Accept-Language", "en-US,en;q=0.5");
client.DefaultRequestHeaders.Add("Connection", "keep-alive");
client.DefaultRequestHeaders.Add("Upgrade-Insecure-Requests", "1");
- HttpResponseMessage response = await client.GetAsync(uri);
- if (!response.IsSuccessStatusCode)
- {
- return null;
- }
+ return client;
+ }
+ /// <summary>
+ /// Gets the favicon nodes from the HTML.
+ /// </summary>
+ /// <param name="response">The response to get the favicon nodes from.</param>
+ /// <param name="uri">The URI to get the favicon nodes from.</param>
+ /// <returns>The favicon nodes.</returns>
+ private static async Task<HtmlNodeCollection[]> GetFaviconNodesFromHtml(HttpResponseMessage response, Uri uri)
+ {
string htmlContent = await response.Content.ReadAsStringAsync();
HtmlDocument htmlDoc = new();
htmlDoc.LoadHtml(htmlContent);
- // Find all favicon links in the HTML with priority order
- var faviconNodes = new[]
- {
- // SVG icons
- htmlDoc.DocumentNode.SelectNodes("//link[@rel='icon' and @type='image/svg+xml']"),
+ var defaultFavicon = new HtmlNode(HtmlNodeType.Element, htmlDoc, 0);
+ defaultFavicon.Attributes.Add("href", $"{uri.GetLeftPart(UriPartial.Authority)}/favicon.ico");
- // Large icons
+ return
+ [
+ htmlDoc.DocumentNode.SelectNodes("//link[@rel='icon' and @type='image/svg+xml']"),
htmlDoc.DocumentNode.SelectNodes("//link[@rel='icon' and (@sizes='192x192' or @sizes='128x128')]"),
-
- // Apple touch icons
htmlDoc.DocumentNode.SelectNodes("//link[@rel='apple-touch-icon' or @rel='apple-touch-icon-precomposed']"),
-
- // Standard icons
htmlDoc.DocumentNode.SelectNodes("//link[@rel='icon' or @rel='shortcut icon']"),
- };
-
- // Add default favicon.ico as fallback
- var defaultFavicon = new HtmlNode(HtmlNodeType.Element, htmlDoc, 0);
- defaultFavicon.Attributes.Add("href", $"{uri.GetLeftPart(UriPartial.Authority)}/favicon.ico");
- faviconNodes = faviconNodes.Append(new HtmlNodeCollection(htmlDoc.DocumentNode) { defaultFavicon }).ToArray();
+ new HtmlNodeCollection(htmlDoc.DocumentNode) { defaultFavicon },
+ ];
+ }
+ private static async Task<byte[]?> TryExtractFaviconFromNodes(HtmlNodeCollection[] faviconNodes, HttpClient client, Uri baseUri)
+ {
foreach (var nodeCollection in faviconNodes)
{
if (nodeCollection == null || nodeCollection.Count == 0)
@@ -106,10 +141,9 @@ public static class FaviconExtractor
continue;
}
- // If the favicon URL is relative, convert it to an absolute URL
if (!Uri.IsWellFormedUriString(faviconUrl, UriKind.Absolute))
{
- faviconUrl = new Uri(uri, faviconUrl).ToString();
+ faviconUrl = new Uri(baseUri, faviconUrl).ToString();
}
var faviconBytes = await FetchAndProcessFaviconAsync(client, faviconUrl);
@@ -123,6 +157,12 @@ public static class FaviconExtractor
return null;
}
+ /// <summary>
+ /// Fetches and processes the favicon.
+ /// </summary>
+ /// <param name="client">The HTTP client.</param>
+ /// <param name="url">The URL to fetch the favicon from.</param>
+ /// <returns>The favicon bytes.</returns>
private static async Task<byte[]?> FetchAndProcessFaviconAsync(HttpClient client, string url)
{
try
@@ -164,6 +204,12 @@ public static class FaviconExtractor
}
}
+ /// <summary>
+ /// Resizes the image to the target width.
+ /// </summary>
+ /// <param name="imageBytes">The image bytes to resize.</param>
+ /// <param name="contentType">The content type of the image.</param>
+ /// <returns>The resized image bytes.</returns>
private static byte[]? ResizeImageAsync(byte[] imageBytes, string contentType)
{
try