This repository has been archived by the owner on Jan 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 89
/
FavIcon.vala
382 lines (335 loc) · 10.3 KB
/
FavIcon.vala
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
// This file is part of FeedReader.
//
// FeedReader is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// FeedReader is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with FeedReader. If not, see <http://www.gnu.org/licenses/>.
public class FeedReader.FavIcon : GLib.Object
{
private static string m_icon_path = GLib.Environment.get_user_data_dir() + "/feedreader/data/feed_icons/";
private static Gee.Map<string?, FavIcon?> m_map = null;
public static FavIcon for_feed(Feed? feed)
{
if(m_map == null)
m_map = new Gee.HashMap<string?, FavIcon?>();
var feed_id = feed != null ? feed.getFeedID() : null;
var icon = m_map.get(feed_id);
if(icon == null)
{
icon = new FavIcon(feed);
m_map.set(feed_id, icon);
}
return icon;
}
private Feed? m_feed;
private Gee.Promise<Gdk.Pixbuf?> m_pixbuf = null;
private ResourceMetadata m_metadata;
public signal void surface_changed(Feed feed, Cairo.Surface surface);
private FavIcon(Feed? feed)
{
m_feed = feed;
}
private int get_scale_factor()
{
return MainWindow.get_default().get_style_context().get_scale();
}
private Cairo.Surface create_surface_from_pixbuf(Gdk.Pixbuf pixbuf)
{
return Gdk.cairo_surface_create_from_pixbuf(pixbuf, get_scale_factor(), null);
}
public async Cairo.Surface? get_surface()
{
// This can happen if an API gives us weird data by returning an article
// with no feed.
if(m_feed == null)
{
return null;
}
// wait for ready + expired so we don't make a bunch of requests at once
if(m_pixbuf == null || (m_pixbuf.future.ready && m_metadata.is_expired()))
{
m_pixbuf = new Gee.Promise<Gdk.Pixbuf?>();
load.begin((obj, res) => {
load.end(res);
});
}
try
{
Gdk.Pixbuf pixbuf = yield m_pixbuf.future.wait_async();
if(pixbuf == null)
return null;
return create_surface_from_pixbuf(pixbuf);
}
catch(Error e)
{
Logger.error("FavIcon.get_pixbuf: " + e.message);
return null;
}
}
private async void load()
{
try
{
var stream = yield downloadFavIcon();
if(stream == null)
return;
var pixbuf = yield new Gdk.Pixbuf.from_stream_async(stream);
stream.close();
if(pixbuf.get_height() <= 1 && pixbuf.get_width() <= 1)
{
Logger.warning("FavIcon: Icon for feed %s is too small".printf(m_feed.getTitle()));
return;
}
int scale = get_scale_factor();
pixbuf = pixbuf.scale_simple(24 * scale, 24 * scale, Gdk.InterpType.BILINEAR);
m_pixbuf.set_value(pixbuf);
if(pixbuf != null)
surface_changed(m_feed, create_surface_from_pixbuf(pixbuf));
}
catch(Error e)
{
Logger.error("FavIcon.load: %s - %s".printf(m_feed.getTitle(), e.message));
}
finally
{
if(!m_pixbuf.future.ready)
m_pixbuf.set_value(null);
}
}
private InputStream? try_load_data_uri(string? icon_url)
{
if(icon_url == null || !icon_url.has_prefix("data"))
return null;
// LibSoup doesn't seem to handle data URI's properly, so handle them
// ourselves..
int comma = icon_url.index_of_char(',');
if(comma == -1)
{
Logger.warning(@"Invalid data URI: $icon_url");
return null;
}
int semicolon = icon_url.index_of_char(';');
string data_str = icon_url[comma:icon_url.length];
uint8[] data;
if(semicolon != -1 && semicolon < comma && icon_url[semicolon + 1:comma] == "base64")
{
data = Base64.decode(data_str);
}
else
{
data = data_str.data;
}
return new MemoryInputStream.from_data(data);
}
private async InputStream? downloadFavIcon(GLib.Cancellable? cancellable = null) throws GLib.Error
{
var datastream = try_load_data_uri(m_feed.getIconURL());
if(datastream != null)
return datastream;
string filename_prefix = m_icon_path + m_feed.getFeedFileName();
string local_filename = @"$filename_prefix.ico";
string metadata_filename = @"$filename_prefix.txt";
if(!yield Utils.ensure_path(m_icon_path))
return null;
m_metadata = yield ResourceMetadata.from_file_async(metadata_filename);
DateTime? expires = m_metadata.expires;
if(cancellable != null && cancellable.is_cancelled())
return null;
bool use_cached = false;
if(!m_metadata.is_expired())
{
Logger.debug("Favicon for %s is valid until %s, skipping this time".printf(m_feed.getTitle(), expires.to_string()));
use_cached = true;
}
else if(!NetworkMonitor.get_default().network_available)
{
Logger.debug("Network not available, skipping favicon download");
use_cached = true;
}
if(use_cached)
{
var file = File.new_for_path(local_filename);
try
{
return yield file.read_async();
}
catch(IOError.NOT_FOUND e)
{
return null;
}
}
try
{
var obvious_icons = new Gee.ArrayList<string>();
if(m_feed.getIconURL() != null)
obvious_icons.add(m_feed.getIconURL());
// try domainname/favicon.ico
var uri = new Soup.URI(m_feed.getURL());
string? siteURL = null;
if(uri != null)
{
string hostname = uri.get_host();
siteURL = uri.get_scheme() + "://" + hostname;
var icon_url = siteURL;
if(!icon_url.has_suffix("/"))
icon_url += "/";
icon_url += "favicon.ico";
obvious_icons.add(icon_url);
}
// Try to find one of those icons
foreach(var url in obvious_icons)
{
var stream = yield downloadIcon(url, cancellable);
if(stream != null)
return stream;
if(cancellable != null && cancellable.is_cancelled())
return null;
}
// If all else fails, download html and parse to find location of favicon
if(siteURL == null)
return null;
var message_html = new Soup.Message("GET", siteURL);
if(Settings.tweaks().get_boolean("do-not-track"))
message_html.request_headers.append("DNT", "1");
string html;
try
{
var bodyStream = yield Utils.getSession().send_async(message_html);
html = (string)yield Utils.inputStreamToArray(bodyStream, cancellable);
}
catch (Error e)
{
Logger.warning(@"Request for $siteURL failed: " + e.message);
return null;
}
if(html != null && message_html.status_code == 200)
{
var html_cntx = new Html.ParserCtxt();
html_cntx.use_options(Html.ParserOption.NOERROR + Html.ParserOption.NOWARNING);
Html.Doc* doc = html_cntx.read_doc(html, siteURL, null, Html.ParserOption.NOERROR + Html.ParserOption.NOWARNING);
if(doc == null)
{
Logger.debug(@"Utils.downloadFavIcon: parsing html on $siteURL failed");
return null;
}
try
{
// check for <link rel="icon">
var xpath = grabberUtils.getURL(doc, "//link[@rel='icon']");
if(xpath == null)
// check for <link rel="shortcut icon">
xpath = grabberUtils.getURL(doc, "//link[@rel='shortcut icon']");
if(xpath == null)
// check for <link rel="apple-touch-icon">
xpath = grabberUtils.getURL(doc, "//link[@rel='apple-touch-icon']");
if(xpath != null)
{
xpath = grabberUtils.completeURL(xpath, siteURL);
return yield downloadIcon(xpath, cancellable);
}
}
finally
{
delete doc;
}
}
return null;
}
finally
{
var default_expires = new DateTime.now_utc().add_days(Constants.REDOWNLOAD_FAVICONS_AFTER_DAYS);
if(m_metadata.expires == null || m_metadata.expires.to_unix() < default_expires.to_unix())
{
m_metadata.expires = default_expires;
}
yield m_metadata.save_to_file_async(metadata_filename);
}
}
private async InputStream? downloadIcon(string? icon_url, Cancellable? cancellable) throws GLib.Error
{
if(icon_url == "" || icon_url == null || GLib.Uri.parse_scheme(icon_url) == null)
{
Logger.warning(@"Utils.downloadIcon: icon_url not valid $icon_url");
return null;
}
string filename_prefix = m_icon_path + m_feed.getFeedFileName();
string local_filename = @"$filename_prefix.ico";
string etag = m_metadata.etag;
string last_modified = m_metadata.last_modified;
Logger.debug(@"Utils.downloadIcon: url = $icon_url");
var message = new Soup.Message("GET", icon_url);
if(message == null)
{
Logger.warning(@"Failed to create message for icon URL $icon_url");
return null;
}
if(Settings.tweaks().get_boolean("do-not-track"))
message.request_headers.append("DNT", "1");
if(etag != null)
message.request_headers.append("If-None-Match", etag);
if(last_modified != null)
message.request_headers.append("If-Modified-Since", last_modified);
uint8[]? data;
try
{
var bodyStream = yield Utils.getSession().send_async(message, cancellable);
data = yield Utils.inputStreamToArray(bodyStream, cancellable);
}
catch (Error e)
{
Logger.error(@"Request for $icon_url failed: " + e.message);
return null;
}
var status = message.status_code;
if(status == 304)
{
var file = File.new_for_path(local_filename);
return yield file.read_async();
}
else if(status == 404 || data == null)
{
return null;
}
else if(status == 200)
{
var local_file = File.new_for_path(local_filename);
try
{
yield local_file.replace_contents_async(data, null, false, FileCreateFlags.NONE, null, null);
}
catch(Error e)
{
Logger.error("Error writing icon: %s".printf(e.message));
return null;
}
m_metadata.etag = message.response_headers.get_one("ETag");
m_metadata.last_modified = message.response_headers.get_one("Last-Modified");
var cache_control = message.response_headers.get_list("Cache-Control");
if(cache_control != null)
{
foreach(var header in message.response_headers.get_list("Cache-Control").split(","))
{
var parts = header.split("=");
if(parts.length < 2 || parts[0] != "max-age")
continue;
var seconds = int64.parse(parts[1]);
var expires = new DateTime.now_utc();
expires.add_seconds(seconds);
m_metadata.expires = expires;
}
}
m_metadata.last_modified = message.response_headers.get_one("Last-Modified");
return new MemoryInputStream.from_data(data);
}
Logger.warning(@"Could not download icon for feed: %s $icon_url, got response code $status".printf(m_feed.getFeedID()));
return null;
}
}