1+ import 'package:iccm_eu_app/utils/debug.dart' ;
12import 'package:url_launcher/url_launcher.dart' ;
3+ import 'package:http/http.dart' as http;
4+ import 'package:html/parser.dart' as parser;
5+ import 'package:html/dom.dart' as dom;
26
37class UrlFunctions {
48 static Future <void > launch (String url) async {
@@ -21,4 +25,73 @@ class UrlFunctions {
2125 // }
2226 return url;
2327 }
28+
29+ ///////////////////////////////////////////////
30+ // Website icon parsing
31+ ///////////////////////////////////////////////
32+
33+ static Future <String ?> getFaviconUrl (String websiteUrl) async {
34+ try {
35+ // 1. Fetch the website's HTML
36+ final response = await http.get (Uri .parse (websiteUrl));
37+
38+ if (response.statusCode == 200 ) {
39+ // 2. Parse the HTML
40+ final document = parser.parse (response.body);
41+
42+ // 3. Find the favicon link
43+ final faviconLink = _findFaviconLink (document);
44+
45+ if (faviconLink != null ) {
46+ // 4. Extract the favicon URL
47+ final faviconUrl = _extractFaviconUrl (websiteUrl, faviconLink);
48+ return faviconUrl;
49+ } else {
50+ // 5. Try default favicon location
51+ final defaultFaviconUrl = _getDefaultFaviconUrl (websiteUrl);
52+ return defaultFaviconUrl;
53+ }
54+ } else {
55+ Debug .msg ('Failed to load website: ${response .statusCode }' );
56+ return null ;
57+ }
58+ } catch (e) {
59+ Debug .msg ('Error getting favicon: $e ' );
60+ return null ;
61+ }
62+ }
63+
64+ // Helper function to find the favicon link in the HTML
65+ static dom.Element ? _findFaviconLink (dom.Document document) {
66+ // Look for <link> tags with rel="icon" or rel="shortcut icon"
67+ final links = document.querySelectorAll ('link' );
68+ for (final link in links) {
69+ final rel = link.attributes['rel' ]? .toLowerCase ();
70+ if (rel == 'icon' || rel == 'shortcut icon' ) {
71+ return link;
72+ }
73+ }
74+ return null ;
75+ }
76+
77+ // Helper function to extract the favicon URL from the link tag
78+ static String _extractFaviconUrl (String websiteUrl, dom.Element link) {
79+ final href = link.attributes['href' ];
80+ if (href == null ) {
81+ return '' ;
82+ }
83+ // Handle relative URLs
84+ if (href.startsWith ('http' )) {
85+ return href;
86+ } else if (href.startsWith ('/' )) {
87+ return Uri .parse (websiteUrl).origin + href;
88+ } else {
89+ return '${Uri .parse (websiteUrl ).origin }/$href ' ;
90+ }
91+ }
92+
93+ // Helper function to get the default favicon URL
94+ static String _getDefaultFaviconUrl (String websiteUrl) {
95+ return '${Uri .parse (websiteUrl ).origin }/favicon.ico' ;
96+ }
2497}
0 commit comments