Files
server/src/Icons/Controllers/IconsController.cs

76 lines
2.4 KiB
C#
Raw Normal View History

using System;
using System.Net.Http;
using System.Threading.Tasks;
2017-10-09 13:35:07 -04:00
using Bit.Icons.Models;
using Bit.Icons.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
2017-10-09 14:02:57 -04:00
using Microsoft.Extensions.Options;
2017-10-09 13:35:07 -04:00
namespace Bit.Icons.Controllers
{
2017-10-09 13:35:07 -04:00
[Route("")]
2017-10-09 14:02:57 -04:00
public class IconsController : Controller
{
private static readonly HttpClient _httpClient = new HttpClient();
2017-10-09 13:35:07 -04:00
private readonly IMemoryCache _memoryCache;
private readonly IDomainMappingService _domainMappingService;
2017-10-09 14:02:57 -04:00
private readonly IconsSettings _iconsSettings;
2017-10-09 14:02:57 -04:00
public IconsController(
IMemoryCache memoryCache,
IDomainMappingService domainMappingService,
2017-10-09 14:02:57 -04:00
IOptions<IconsSettings> iconsSettingsOptions)
{
2017-10-09 13:35:07 -04:00
_memoryCache = memoryCache;
_domainMappingService = domainMappingService;
2017-10-09 14:02:57 -04:00
_iconsSettings = iconsSettingsOptions.Value;
}
2017-10-09 13:35:07 -04:00
[HttpGet("")]
public async Task<IActionResult> Get([FromQuery]string domain)
{
2017-10-09 14:34:44 -04:00
if(string.IsNullOrWhiteSpace(domain))
{
return new BadRequestResult();
}
2017-10-09 13:35:07 -04:00
if(!domain.StartsWith("http://") || !domain.StartsWith("https://"))
{
domain = "http://" + domain;
}
2017-10-09 13:35:07 -04:00
if(!Uri.TryCreate(domain, UriKind.Absolute, out Uri uri))
{
return new BadRequestResult();
}
var mappedDomain = _domainMappingService.MapDomain(uri.Host);
2017-10-09 14:43:33 -04:00
var icon = await _memoryCache.GetOrCreateAsync(mappedDomain, async entry =>
{
2017-10-09 14:45:00 -04:00
entry.AbsoluteExpirationRelativeToNow = new TimeSpan(_iconsSettings.CacheHours, 0, 0);
var iconUrl = $"{_iconsSettings.BestIconBaseUrl}/icon?url={mappedDomain}&size=16..24..32";
var response = await _httpClient.GetAsync(iconUrl);
2017-10-09 13:35:07 -04:00
if(!response.IsSuccessStatusCode)
{
return null;
}
2017-10-09 13:35:07 -04:00
return new Icon
{
Image = await response.Content.ReadAsByteArrayAsync(),
Format = response.Content.Headers.ContentType.MediaType
};
});
2017-10-09 13:35:07 -04:00
if(icon == null)
{
2017-10-09 13:35:07 -04:00
return new NotFoundResult();
}
return new FileContentResult(icon.Image, icon.Format);
}
}
}