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

70 lines
2.3 KiB
C#
Raw Normal View History

using System;
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 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
{
2017-10-09 13:35:07 -04:00
private readonly IMemoryCache _memoryCache;
private readonly IDomainMappingService _domainMappingService;
private readonly IIconFetchingService _iconFetchingService;
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,
IIconFetchingService iconFetchingService,
2017-10-09 14:54:32 -04:00
IconsSettings iconsSettings)
{
2017-10-09 13:35:07 -04:00
_memoryCache = memoryCache;
_domainMappingService = domainMappingService;
_iconFetchingService = iconFetchingService;
2017-10-09 14:54:32 -04:00
_iconsSettings = iconsSettings;
}
2017-10-12 10:00:44 -04:00
[HttpGet("{hostname}/icon.png")]
2017-10-25 12:52:55 -04:00
[ResponseCache(Duration = 604800 /*7 days*/)]
2017-10-12 10:00:44 -04:00
public async Task<IActionResult> Get(string hostname)
{
2017-10-12 10:00:44 -04:00
if(string.IsNullOrWhiteSpace(hostname) || !hostname.Contains("."))
2017-10-09 14:34:44 -04:00
{
return new BadRequestResult();
}
2017-10-12 10:00:44 -04:00
var url = $"http://{hostname}";
2017-10-09 16:21:37 -04:00
if(!Uri.TryCreate(url, UriKind.Absolute, out Uri uri))
2017-10-09 13:35:07 -04:00
{
return new BadRequestResult();
}
var mappedDomain = _domainMappingService.MapDomain(uri.Host);
2017-10-12 10:41:13 -04:00
if(!_memoryCache.TryGetValue(mappedDomain, out Icon icon))
{
var result = await _iconFetchingService.GetIconAsync(mappedDomain);
if(result == null)
{
2017-10-12 10:41:13 -04:00
return new NotFoundResult();
}
icon = result.Icon;
2018-03-19 08:11:23 -04:00
2017-10-12 10:41:13 -04:00
// Only cache smaller images (<= 50kb)
if(icon.Image.Length <= 50012)
2017-10-12 10:41:13 -04:00
{
_memoryCache.Set(mappedDomain, icon, new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = new TimeSpan(_iconsSettings.CacheHours, 0, 0)
});
}
}
return new FileContentResult(icon.Image, icon.Format);
}
}
}