-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFaviconFetcher.cs
82 lines (70 loc) · 2.82 KB
/
FaviconFetcher.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
using System;
using Community.PowerToys.Run.Plugin.TabPort.util;
using Microsoft.Data.Sqlite;
using Wox.Plugin.Logger;
namespace Community.PowerToys.Run.Plugin.TabPort;
public class FaviconFetcher
{
private const int MaxRetryCount = 1;
private const string FirefoxQuery =
"""
SELECT data FROM moz_pages_w_icons
INNER JOIN moz_icons_to_pages ON moz_pages_w_icons.id = moz_icons_to_pages.page_id
INNER JOIN moz_icons ON moz_icons_to_pages.icon_id = moz_icons.id
WHERE moz_pages_w_icons.page_url LIKE @domain
ORDER BY width DESC LIMIT 1;
""";
private const string ChromiumQuery =
"""
SELECT image_data FROM icon_mapping
INNER JOIN favicon_bitmaps ON icon_mapping.icon_id = favicon_bitmaps.icon_id
WHERE icon_mapping.page_url LIKE @domain
ORDER BY width DESC LIMIT 1;
""";
public static bool TemporarilyDisabled { get; set; }
public static byte[] FetchFaviconLocalDatabase(string domain, int retryCount = 0)
{
if (TemporarilyDisabled) return null;
if (retryCount > MaxRetryCount) return null;
try
{
var connection = SqliteConnectionUtils.Instance.GetConnection();
var query = Main.Setting.FaviconDbPathPriority == Settings.FaviconDbPathPriorityItem.Firefox
? FirefoxQuery
: ChromiumQuery;
using var command = new SqliteCommand(query, connection);
command.Parameters.AddWithValue("@domain", $"%{GetHostName(domain)}%");
using var reader = command.ExecuteReader();
if (reader.Read())
{
var bufferSize = reader.GetBytes(0, 0, null, 0, 0);
var icoBlob = new byte[bufferSize];
long bytesRead = 0;
var offset = 0;
while (bytesRead < bufferSize)
{
bytesRead += reader.GetBytes(0, offset, icoBlob, offset, (int)(bufferSize - bytesRead));
offset += (int)bytesRead;
}
return icoBlob;
}
}
catch (SqliteException ex)
{
Log.Info(
$"[FaviconFetcher] SQLite error: {ex.Message}, Database Path: {SqliteConnectionUtils.Instance.GetConnection().DataSource}",
typeof(FaviconFetcher));
SqliteConnectionUtils.Instance.ReopenConnection();
return retryCount < MaxRetryCount ? FetchFaviconLocalDatabase(domain, retryCount + 1) : null;
}
catch (Exception ex)
{
Log.Info($"[FaviconFetcher] General error: {ex.Message}", typeof(FaviconFetcher));
}
return null;
}
private static string GetHostName(string url)
{
return new Uri(url).Host;
}
}