Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Local favicon for bookmark plugin #3361

Draft
wants to merge 19 commits into
base: dev
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
152 changes: 145 additions & 7 deletions Plugins/Flow.Launcher.Plugin.BrowserBookmark/ChromiumBookmarkLoader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,23 @@
using System.IO;
using System.Text.Json;
using Flow.Launcher.Infrastructure.Logger;
using System;
using Microsoft.Data.Sqlite;

namespace Flow.Launcher.Plugin.BrowserBookmark;

public abstract class ChromiumBookmarkLoader : IBookmarkLoader
{
private readonly string _faviconCacheDir;

protected ChromiumBookmarkLoader()
{
_faviconCacheDir = Path.Combine(
Path.GetDirectoryName(typeof(ChromiumBookmarkLoader).Assembly.Location),
"FaviconCache");
Directory.CreateDirectory(_faviconCacheDir);
}

public abstract List<Bookmark> GetBookmarks();

protected List<Bookmark> LoadBookmarks(string browserDataPath, string name)
Expand All @@ -22,16 +34,36 @@ protected List<Bookmark> LoadBookmarks(string browserDataPath, string name)
if (!File.Exists(bookmarkPath))
continue;

Main.RegisterBookmarkFile(bookmarkPath);
// Register bookmark file monitoring (direct call to Main.RegisterBookmarkFile)
try
{
if (File.Exists(bookmarkPath))
{
//Main.RegisterBookmarkFile(bookmarkPath);
}
}
catch (Exception ex)
{
Log.Exception($"Failed to register bookmark file monitoring: {bookmarkPath}", ex);
}

var source = name + (Path.GetFileName(profile) == "Default" ? "" : $" ({Path.GetFileName(profile)})");
bookmarks.AddRange(LoadBookmarksFromFile(bookmarkPath, source));
var profileBookmarks = LoadBookmarksFromFile(bookmarkPath, source);

// Load favicons after loading bookmarks
var faviconDbPath = Path.Combine(profile, "Favicons");
if (File.Exists(faviconDbPath))
{
LoadFaviconsFromDb(faviconDbPath, profileBookmarks);
}

bookmarks.AddRange(profileBookmarks);
}

return bookmarks;
}

protected List<Bookmark> LoadBookmarksFromFile(string path, string source)
protected static List<Bookmark> LoadBookmarksFromFile(string path, string source)
{
var bookmarks = new List<Bookmark>();

Expand All @@ -45,23 +77,22 @@ protected List<Bookmark> LoadBookmarksFromFile(string path, string source)
return bookmarks;
}

private void EnumerateRoot(JsonElement rootElement, ICollection<Bookmark> bookmarks, string source)
private static void EnumerateRoot(JsonElement rootElement, ICollection<Bookmark> bookmarks, string source)
{
foreach (var folder in rootElement.EnumerateObject())
{
if (folder.Value.ValueKind != JsonValueKind.Object)
continue;

// Fix for Opera. It stores bookmarks slightly different than chrome. See PR and bug report for this change for details.
// If various exceptions start to build up here consider splitting this Loader into multiple separate ones.
// Fix for Opera. It stores bookmarks slightly different than chrome.
if (folder.Name == "custom_root")
EnumerateRoot(folder.Value, bookmarks, source);
else
EnumerateFolderBookmark(folder.Value, bookmarks, source);
}
}

private void EnumerateFolderBookmark(JsonElement folderElement, ICollection<Bookmark> bookmarks,
private static void EnumerateFolderBookmark(JsonElement folderElement, ICollection<Bookmark> bookmarks,
string source)
{
if (!folderElement.TryGetProperty("children", out var childrenElement))
Expand Down Expand Up @@ -91,4 +122,111 @@ private void EnumerateFolderBookmark(JsonElement folderElement, ICollection<Book
}
}
}

private void LoadFaviconsFromDb(string dbPath, List<Bookmark> bookmarks)
{
try
{
// Use a copy to avoid lock issues with the original file
var tempDbPath = Path.Combine(_faviconCacheDir, $"tempfavicons_{Guid.NewGuid()}.db");

try
{
File.Copy(dbPath, tempDbPath, true);
}
catch (Exception ex)
{
Log.Exception($"Failed to copy favicon DB: {dbPath}", ex);
return;
}

try
{
using var connection = new SqliteConnection($"Data Source={tempDbPath}");
connection.Open();

foreach (var bookmark in bookmarks)
{
try
{
var url = bookmark.Url;
if (string.IsNullOrEmpty(url)) continue;

// Extract domain from URL
if (!Uri.TryCreate(url, UriKind.Absolute, out Uri uri))
continue;

var domain = uri.Host;

using var cmd = connection.CreateCommand();
cmd.CommandText = @"
SELECT f.id, b.image_data
FROM favicons f
JOIN favicon_bitmaps b ON f.id = b.icon_id
JOIN icon_mapping m ON f.id = m.icon_id
WHERE m.page_url LIKE @url
ORDER BY b.width DESC
LIMIT 1";

cmd.Parameters.AddWithValue("@url", $"%{domain}%");

using var reader = cmd.ExecuteReader();
if (!reader.Read() || reader.IsDBNull(1))
continue;

var iconId = reader.GetInt64(0).ToString();
var imageData = (byte[])reader["image_data"];

if (imageData is not { Length: > 0 })
continue;

var faviconPath = Path.Combine(_faviconCacheDir, $"{domain}_{iconId}.png");
if (!File.Exists(faviconPath))
{
SaveBitmapData(imageData, faviconPath);
}
bookmark.FaviconPath = faviconPath;
}
catch (Exception ex)
{
Log.Exception($"Failed to extract bookmark favicon: {bookmark.Url}", ex);
}
}

// https://github.com/dotnet/efcore/issues/26580
SqliteConnection.ClearPool(connection);
connection.Close();
}
catch (Exception ex)
{
Log.Exception($"Failed to connect to SQLite: {tempDbPath}", ex);
}

// Delete temporary file
try
{
File.Delete(tempDbPath);
}
catch (Exception ex)
{
Log.Exception($"Failed to delete temporary favicon DB: {tempDbPath}", ex);
}
}
catch (Exception ex)
{
Log.Exception($"Failed to load favicon DB: {dbPath}", ex);
}
}

private static void SaveBitmapData(byte[] imageData, string outputPath)
{
try
{
File.WriteAllBytes(outputPath, imageData);
}
catch (Exception ex)
{
Log.Exception($"Failed to save image: {outputPath}", ex);
}
}
}
Loading
Loading