-
Notifications
You must be signed in to change notification settings - Fork 3
/
fetch_preview.dart
69 lines (60 loc) · 1.91 KB
/
fetch_preview.dart
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
import 'package:html/parser.dart';
import 'package:http/http.dart';
class FetchPreview {
Future fetch(url) async {
final client = Client();
final response = await client.get(_validateUrl(url));
final document = parse(response.body);
String description, title, image, appleIcon, favIcon;
var elements = document.getElementsByTagName('meta');
final linkElements = document.getElementsByTagName('link');
elements.forEach((tmp) {
if (tmp.attributes['property'] == 'og:title') {
//fetch seo title
title = tmp.attributes['content'];
}
//if seo title is empty then fetch normal title
if (title == null || title.isEmpty) {
title = document.getElementsByTagName('title')[0].text;
}
//fetch seo description
if (tmp.attributes['property'] == 'og:description') {
description = tmp.attributes['content'];
}
//if seo description is empty then fetch normal description.
if (description == null || description.isEmpty) {
//fetch base title
if (tmp.attributes['name'] == 'description') {
description = tmp.attributes['content'];
}
}
//fetch image
if (tmp.attributes['property'] == 'og:image') {
image = tmp.attributes['content'];
}
});
linkElements.forEach((tmp) {
if (tmp.attributes['rel'] == 'apple-touch-icon') {
appleIcon = tmp.attributes['href'];
}
if (tmp.attributes['rel']?.contains('icon') == true) {
favIcon = tmp.attributes['href'];
}
});
return {
'title': title ?? '',
'description': description ?? '',
'image': image ?? '',
'appleIcon': appleIcon ?? '',
'favIcon': favIcon ?? ''
};
}
_validateUrl(String url) {
if (url?.startsWith('http://') == true || url?.startsWith('https://') == true) {
return url;
}
else {
return 'http://$url';
}
}
}