public async Task TestGetFaviconFromUrl() { string html = @" <html> <head> <meta charset=""utf-8""> <link rel=""shortcut icon"" href=""http://a.b.c.de/img/favicon.png""> </head> <body>html</body> </html> "; using (var httpTest = new HttpTest()) { // arrange var fetcher = new IconFetcher(Logger); httpTest .RespondWith(html) // first call to fetch the html .RespondWith(buildContent: () => { // second call to get the payload return(new ByteArrayContent(Image)); }); // act var result = await fetcher.GetFaviconFromUrl("http://a.b.c.de"); // assert result.filename .Should().Be("favicon.png"); result.payload .Should().NotBeNull(); result.payload.Length .Should().Be(Image.Length); } }
async Task FetchFavicon(BookmarkEntity bookmark, string url) { try { if (_fetcher == null || _servicesFactory == null) { return; } var scope = _servicesFactory.CreateScope(); var repository = scope.ServiceProvider.GetService(typeof(IBookmarkRepository)) as IBookmarkRepository; if (repository == null) { _logger.LogWarning("Unable to get a repository from ServicesScopeFactory!"); return; } var result = await _fetcher.GetFaviconFromUrl(url); var filename = result.filename; var payload = result.payload; // combine icon with bookmark id filename = bookmark.Id + "_" + filename; if (payload != null && payload.Length > 0) { _logger.LogDebug($"got a favicon payload of length '{payload.Length}' for url '{url}'"); var rootPath = _webHostEnv.ContentRootPath; var iconPath = _faviconSettings.StoragePath; var storagePath = Path.Combine(rootPath, iconPath); var path = Path.Combine(storagePath, filename); await System.IO.File.WriteAllBytesAsync(path, payload); if (System.IO.File.Exists(path)) { // also update the favicon await repository !.InUnitOfWorkAsync <bool>(async() => { var bm = bookmark; bm.Favicon = filename; var updated = await repository.Update(bm); return(updated != null ? (true, true) : (false, false)); }); } } else { _logger.LogDebug($"No favicon payload for url '{url}'."); } } catch (Exception EX) { _logger.LogError($"Error during favicon fetch/update: {EX.Message}; stack: {EX.StackTrace}"); } }