forked from microsoft/AzUrlShortener
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUrlShortener.cs
147 lines (121 loc) · 4.66 KB
/
UrlShortener.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
/*
```c#
Input:
{
// [Required] The url you wish to have a short version for
"url": "https://docs.microsoft.com/en-ca/azure/azure-functions/functions-create-your-first-function-visual-studio",
// [Optional] Title of the page, or text description of your choice.
"title": "Quickstart: Create your first function in Azure using Visual Studio"
// [Optional] the end of the URL. If nothing one will be generated for you.
"vanity": "azFunc"
}
Output:
{
"ShortUrl": "http://c5m.ca/azFunc",
"LongUrl": "https://docs.microsoft.com/en-ca/azure/azure-functions/functions-create-your-first-function-visual-studio"
}
*/
using System;
using System.IO;
using System.Net;
using System.Text.Json;
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 UrlShortener
{
private readonly ILogger _logger;
//private readonly AdminApiSettings _adminApiSettings;
private readonly ShortenerSettings _shortenerSettings;
public UrlShortener(ILoggerFactory loggerFactory, ShortenerSettings shortenerSettings)
{
_logger = loggerFactory.CreateLogger<UrlShortener>();
_shortenerSettings = shortenerSettings;
}
[Function("UrlShortener")]
public async Task<HttpResponseData> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestData req,
ExecutionContext context
)
{
_logger.LogInformation($"__trace creating shortURL: {req}");
string userId = string.Empty;
ShortRequest input;
var result = new ShortResponse();
try
{
//var invalidCode = ClaimsUtility.CatchUnauthorize(req, _logger);
//if (invalidCode != HttpStatusCode.Continue)
//{
// return req.CreateResponse(invalidCode);
//}
// Validation of the inputs
if (req == null)
{
return req.CreateResponse(HttpStatusCode.NotFound);
}
using (var reader = new StreamReader(req.Body))
{
var strBody = reader.ReadToEnd();
input = JsonSerializer.Deserialize<ShortRequest>(strBody, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
if (input == null)
{
return req.CreateResponse(HttpStatusCode.NotFound);
}
}
// If the Url parameter only contains whitespaces or is empty return with BadRequest.
if (string.IsNullOrWhiteSpace(input.Url))
{
var badResponse = req.CreateResponse(HttpStatusCode.BadRequest);
await badResponse.WriteAsJsonAsync(new { Message = "The url parameter can not be empty." });
return badResponse;
}
// Validates if input.url is a valid aboslute url, aka is a complete refrence to the resource, ex: http(s)://google.com
if (!Uri.IsWellFormedUriString(input.Url, UriKind.Absolute))
{
var badResponse = req.CreateResponse(HttpStatusCode.BadRequest);
await badResponse.WriteAsJsonAsync(new { Message = $"{input.Url} is not a valid absolute Url. The Url parameter must start with 'http://' or 'http://'." });
return badResponse;
}
StorageTableHelper stgHelper = new StorageTableHelper(_shortenerSettings.UlsDataStorage);
string longUrl = input.Url.Trim();
string vanity = string.IsNullOrWhiteSpace(input.Vanity) ? "" : input.Vanity.Trim();
string title = string.IsNullOrWhiteSpace(input.Title) ? "" : input.Title.Trim();
ShortUrlEntity newRow;
if (!string.IsNullOrEmpty(vanity))
{
newRow = new ShortUrlEntity(longUrl, vanity, title, input.Schedules);
if (await stgHelper.IfShortUrlEntityExist(newRow))
{
var badResponse = req.CreateResponse(HttpStatusCode.Conflict);
await badResponse.WriteAsJsonAsync(new { Message = "This Short URL already exist." });
return badResponse;
}
}
else
{
newRow = new ShortUrlEntity(longUrl, await Utility.GetValidEndUrl(vanity, stgHelper), title, input.Schedules);
}
await stgHelper.SaveShortUrlEntity(newRow);
var host = "oneholt.io";// string.IsNullOrEmpty(_adminApiSettings.customDomain) ? req.Url.Host : _adminApiSettings.customDomain.ToString();
result = new ShortResponse(host, newRow.Url, newRow.RowKey, newRow.Title);
_logger.LogInformation("Short Url created.");
}
catch (Exception ex)
{
_logger.LogError(ex, "An unexpected error was encountered.");
var badResponse = req.CreateResponse(HttpStatusCode.BadRequest);
await badResponse.WriteAsJsonAsync(new { Message = ex.Message });
return badResponse;
}
var response = req.CreateResponse(HttpStatusCode.OK);
await response.WriteAsJsonAsync(result);
return response;
}
}
}