getPreviewData function
Parses provided text and returns PreviewData for the first found link.
Implementation
Future<PreviewData> getPreviewData(
String text, {
String? proxy,
Duration? requestTimeout,
String? userAgent,
}) async {
const previewData = PreviewData();
String? previewDataDescription;
PreviewDataImage? previewDataImage;
String? previewDataTitle;
String? previewDataUrl;
try {
final emailRegexp = RegExp(regexEmail, caseSensitive: false);
final textWithoutEmails = text
.replaceAllMapped(
emailRegexp,
(match) => '',
)
.trim();
if (textWithoutEmails.isEmpty) return previewData;
final urlRegexp = RegExp(regexLink, caseSensitive: false);
final matches = urlRegexp.allMatches(textWithoutEmails);
if (matches.isEmpty) return previewData;
var url = textWithoutEmails.substring(
matches.first.start,
matches.first.end,
);
if (!url.toLowerCase().startsWith('http')) {
url = 'https://$url';
}
previewDataUrl = _calculateUrl(url, proxy);
final uri = Uri.parse(previewDataUrl);
final response = await http.get(uri, headers: {
'User-Agent': userAgent ?? 'WhatsApp/2',
}).timeout(requestTimeout ?? const Duration(seconds: 5));
final document = parser.parse(utf8.decode(response.bodyBytes));
final imageRegexp = RegExp(regexImageContentType);
if (imageRegexp.hasMatch(response.headers['content-type'] ?? '')) {
final imageSize = await _getImageSize(previewDataUrl);
previewDataImage = PreviewDataImage(
height: imageSize.height,
url: previewDataUrl,
width: imageSize.width,
);
return PreviewData(
image: previewDataImage,
link: previewDataUrl,
);
}
if (!_hasUTF8Charset(document)) {
return previewData;
}
final title = _getTitle(document);
if (title != null) {
previewDataTitle = title.trim();
}
final description = _getDescription(document);
if (description != null) {
previewDataDescription = description.trim();
}
final imageUrls = _getImageUrls(document, url);
Size imageSize;
String imageUrl;
if (imageUrls.isNotEmpty) {
imageUrl = imageUrls.length == 1 ? _calculateUrl(imageUrls[0], proxy) : await _getBiggestImageUrl(imageUrls, proxy);
imageSize = await _getImageSize(imageUrl);
previewDataImage = PreviewDataImage(
height: imageSize.height,
url: imageUrl,
width: imageSize.width,
);
}
return PreviewData(
description: previewDataDescription,
image: previewDataImage,
link: previewDataUrl,
title: previewDataTitle,
);
} catch (e) {
return PreviewData(
description: previewDataDescription,
image: previewDataImage,
link: previewDataUrl,
title: previewDataTitle,
);
}
}