getTrendingRepositories function
A method to get trending repositories
Implementation
Future<List<TrendingRepository>> getTrendingRepositories({
String since,
String language,
}) async {
var url = '${URL}/trending';
if (language != null) {
url += '/$language';
}
if (since != null) {
url += '?since=$since';
}
var res = await http.get(url);
var document = parse(res.body);
var items = document.querySelectorAll('.Box-row');
return items.map((item) {
PrimaryLanguage primaryLanguage;
var colorNode = item.querySelector('.repo-language-color');
if (colorNode != null) {
primaryLanguage = PrimaryLanguage(
name: colorNode.nextElementSibling?.innerHtml?.trim(),
color: RegExp(r'#[0-9a-fA-F]{3,6}')
.firstMatch(colorNode.attributes['style'])
?.group(0));
}
var starCountStr = item
.querySelector('.f6')
?.querySelector('.octicon-star')
?.parent
?.innerHtml
?.replaceAll(RegExp(r'^[\s\S]*svg>'), '')
?.replaceAll(',', '')
?.trim();
var starCount = starCountStr == null ? null : int.tryParse(starCountStr);
var forkCountStr = item
.querySelector('.octicon-repo-forked')
?.parent
?.innerHtml
?.replaceAll(RegExp(r'^[\s\S]*svg>'), '')
?.replaceAll(',', '')
?.trim();
var forkCount = forkCountStr == null ? null : int.tryParse(forkCountStr);
var starsStr = item
.querySelector('.float-sm-right')
?.innerHtml
?.replaceAll(RegExp(r'^[\s\S]*svg>'), '')
?.replaceAll(',', '')
?.trim();
String description;
String descriptionHTML;
var descriptionRawHtml = item.querySelector('p')?.innerHtml?.trim();
if (descriptionRawHtml != null) {
description = descriptionRawHtml
?.replaceAll(RegExp(r'<g-emoji.*?>'), '')
?.replaceAll(RegExp(r'</g-emoji>'), '')
?.replaceAll(RegExp(r'<a.*?>'), '')
?.replaceAll(RegExp(r'</a>'), '');
descriptionHTML = '<div>$descriptionRawHtml</div>';
}
List<RepositoryBuildBy> buildBys = [];
var buildByNodes = item.querySelectorAll('.avatar');
if (buildByNodes != null && buildByNodes.isNotEmpty) {
buildByNodes.forEach((e) {
buildBys.add(RepositoryBuildBy(
avatar: e.attributes['src'],
username: e.attributes['alt'].replaceFirst('@', ''),
));
});
}
var username = item
.querySelector('.text-normal')
?.innerHtml
?.replaceFirst('/', '')
?.trim();
var name = item
.querySelector('.text-normal')
?.parent
?.innerHtml
?.replaceAll(RegExp(r'^[\s\S]*span>'), '')
?.trim();
return TrendingRepository(
owner: username,
avatar: '${URL}/${username}.png',
name: name,
description: description,
descriptionHTML: descriptionHTML,
starCount: starCount,
forkCount: forkCount,
stars: starsStr,
primaryLanguage: primaryLanguage,
buildBys: buildBys,
);
}).toList();
}