fromUri static method
- Uri url, [
- OEmbedProviders providers = const [],
- bool updateProviders = true
Retrieves oEmbed data from the given URL.
Returns a Future that completes with an OEmbedData object if successful,
or with a default OEmbedData object if oEmbed data is not found.
The url
parameter specifies the URL for which to retrieve the oEmbed data.
The providers
parameter specifies the list of oEmbed providers to search.
If no providers are specified, the list of providers is retrieved from the oEmbed website.
Implementation
static Future<OEmbedData> fromUri(Uri url, [OEmbedProviders providers = const [], bool updateProviders = true]) async {
try {
if (providers.isEmpty) {
providers = await getProviders(updateProviders);
}
// Find the provider that matches the given URL
final OEmbed? provider = providers.firstWhereOrNull((p) {
return url.host.flatEqual(p.providerUrl) ||
p.endpoints.any((ep) {
return ep.schemes.any((x) => url.toString().isLike(x));
});
});
if (provider != null) {
// Find the endpoint that supports oEmbed
final OEmbedEndpoint? oEmbedEndpoint = provider.endpoints.firstWhereOrNull((e) => e.schemes.any((x) => url.toString().isLike(x)));
if (oEmbedEndpoint != null) {
var r = await oEmbedEndpoint.getOEmbedData(url);
if (r != null) {
return r;
}
}
}
} catch (e) {
consoleLog('Error: $e');
}
// Default oEmbed data is an HTML link to the URL with the site title as the link text
try {
final response = await http.get(url);
if (response.statusCode == 200) {
final String html = response.body;
final String title = RegExp(r'<title>([^<]+)</title>').firstMatch(html)?.group(1) ?? url.host;
final String favicon = RegExp(r'<link rel="icon" href="([^"]+)"').firstMatch(html)?.group(1) ?? '';
final String author = RegExp(r'<meta name="author" content="([^"]+)"').firstMatch(html)?.group(1) ?? '';
return OEmbedData(
title: title,
authorName: author,
providerName: url.host,
providerUrl: url.host,
authorUrl: url.host,
thumbnailUrl: favicon,
thumbnailHeight: 16,
thumbnailWidth: 16,
html: '<a target="_blank" href="$url"><img src="$favicon" alt="$title" style="width: 16px; height: 16px;"> $title</a>',
);
}
} catch (e) {
consoleLog('Error: $e');
} finally {}
return OEmbedData(
title: "oEmbed not found",
html: '<a target="_blank" href="$url">${url.host}</a>',
providerUrl: url.host,
providerName: url.host,
);
}