forked from microsoft/AzUrlShortener
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUrlRedirect.cs
66 lines (56 loc) · 2.28 KB
/
UrlRedirect.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
using System;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Cloud5mins.domain;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
namespace Cloud5mins.Function
{
public class UrlRedirect
{
private NLogWrapper logger;
private readonly ShortenerSettings _shortenerSettings;
public UrlRedirect(ILoggerFactory loggerFactory, ShortenerSettings settings)
{
logger = new NLogWrapper(LoggerType.UrlRedirect, settings);
_shortenerSettings = settings;
}
[Function("UrlRedirect")]
public async Task<HttpResponseData> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = "urlredirect/{shortUrl}")]
HttpRequestData req,
string shortUrl,
ExecutionContext context)
{
string redirectUrl = "https://azure.com";
if (!String.IsNullOrWhiteSpace(shortUrl))
{
redirectUrl = _shortenerSettings.defaultRedirectUrl;
StorageTableHelper stgHelper = new StorageTableHelper(_shortenerSettings.UlsDataStorage);
var tempUrl = new ShortUrlEntity(string.Empty, shortUrl);
var newUrl = await stgHelper.GetShortUrlEntity(tempUrl);
if (newUrl != null)
{
logger.Log(NLog.LogLevel.Info, "Redirect url found for short url {url.shortUrl} : {url.redirectUrl}", shortUrl, newUrl.Url);
newUrl.Clicks++;
await stgHelper.SaveClickStatsEntity(new ClickStatsEntity(newUrl.RowKey));
await stgHelper.SaveShortUrlEntity(newUrl);
redirectUrl = WebUtility.UrlDecode(newUrl.ActiveUrl);
}
else
{
logger.Log(NLog.LogLevel.Warn, "Redirect url not found for short url : {url.shortUrl}", shortUrl);
}
}
else
{
logger.Log(NLog.LogLevel.Error, "Bad Link, resorting to fallback.");
}
var res = req.CreateResponse(HttpStatusCode.Redirect);
res.Headers.Add("Location", redirectUrl);
return res;
}
}
}