Neuron®
The Neuron® is the basis for the creation of open and secure federated networks for smart societies.
Loading...
Searching...
No Matches
UrlShortener.cs
1using System;
3using System.Text;
4using System.Threading.Tasks;
5using Waher.Content;
8
10{
15 {
16 private static readonly Cache<string, UrlRecord> shortUrls = new Cache<string, UrlRecord>(int.MaxValue, TimeSpan.FromDays(1), TimeSpan.FromHours(1));
17
21 public UrlShortener()
22 : this("/US")
23 {
24 }
25
31 : base(ResourceName)
32 {
33 }
34
35 private class UrlRecord
36 {
37 public string Url;
38 public bool OneTimeUse;
39 }
40
44 public bool AllowsGET => true;
45
49 public bool AllowsPOST => true;
50
54 public override bool HandlesSubPaths => true;
55
59 public override bool UserSessions => false;
60
67 public async Task GET(HttpRequest Request, HttpResponse Response)
68 {
69 string s = Request.SubPath;
70 if (s.StartsWith("/"))
71 s = s.Substring(1);
72
73 if (string.IsNullOrEmpty(s))
74 {
75 await Response.SendResponse(new BadRequestException("No short URL provided."));
76 return;
77 }
78
79 if (!(shortUrls?.TryGetValue(s, out UrlRecord Rec) ?? false))
80 {
81 await Response.SendResponse(new NotFoundException("Short URL not found."));
82 return;
83 }
84
85 if (Rec.OneTimeUse)
86 shortUrls?.Remove(s);
87
88 if ((Request.Header.QueryParameters?.Length ?? 0) > 0)
89 {
90 StringBuilder sb = new StringBuilder(Rec.Url);
91 bool First = Rec.Url.IndexOf('?') < 0;
92
93 foreach (KeyValuePair<string, string> P in Request.Header.QueryParameters)
94 {
95 if (First)
96 {
97 sb.Append('?');
98 First = false;
99 }
100 else
101 sb.Append('&');
102
103 sb.Append(System.Web.HttpUtility.UrlEncode(P.Key));
104 sb.Append('=');
105 sb.Append(System.Web.HttpUtility.UrlEncode(P.Value));
106 }
107
108 await Response.SendResponse(new MovedPermanentlyException(sb.ToString()));
109 }
110 else
111 await Response.SendResponse(new MovedPermanentlyException(Rec.Url));
112 }
113
120 public async Task POST(HttpRequest Request, HttpResponse Response)
121 {
122 ContentResponse Content = await Request.DecodeDataAsync();
123 if (Content.HasError)
124 {
125 await Response.SendResponse(Content.Error);
126 return;
127 }
128
129 if (!(Content.Decoded is Dictionary<string, object> Obj) ||
130 !Obj.TryGetValue("Url", out object Obj2) ||
131 !(Obj2 is string Url) ||
132 !Obj.TryGetValue("OneTimeUse", out Obj2) ||
133 !(Obj2 is bool OneTimeUse))
134 {
135 await Response.SendResponse(new BadRequestException("Invalid request."));
136 return;
137 }
138
139 await Response.Return(GetShortUrl(Url, OneTimeUse));
140 }
141
150 public static string GetShortUrl(string Url, bool OneTimeUse)
151 {
152 string Id;
153
154 do
155 {
157 }
158 while (shortUrls?.ContainsKey(Id) ?? false);
159
160 shortUrls?.Add(Id, new UrlRecord()
161 {
162 Url = Url,
163 OneTimeUse = OneTimeUse
164 });
165
166 return Gateway.GetUrl("/US/" + Id);
167 }
168 }
169}
Static class that does BASE64URL encoding (using URL and filename safe alphabet), as defined in RFC46...
Definition: Base64Url.cs:11
static string Encode(byte[] Data)
Converts a binary block of data to a Base64URL-encoded string.
Definition: Base64Url.cs:48
Contains information about a response to a content request.
bool HasError
If an error occurred.
object Decoded
Decoded object.
Exception Error
Error response.
Static class managing the runtime environment of the IoT Gateway.
Definition: Gateway.cs:147
static byte[] NextBytes(int NrBytes)
Generates an array of random bytes.
Definition: Gateway.cs:4335
static string GetUrl(string LocalResource)
Gets a URL for a resource.
Definition: Gateway.cs:5079
Web Service for working with short URLs.
Definition: UrlShortener.cs:15
bool AllowsGET
If the GET method is allowed.
Definition: UrlShortener.cs:44
static string GetShortUrl(string Url, bool OneTimeUse)
Shortens a URL temporarily. Shortened URLs are available at most for 24 hours (if used) and 1h if not...
UrlShortener(string ResourceName)
Web Service, generating QR-codes based on URI input.
Definition: UrlShortener.cs:30
override bool UserSessions
If the resource uses user sessions.
Definition: UrlShortener.cs:59
async Task GET(HttpRequest Request, HttpResponse Response)
Executes the GET method on the resource.
Definition: UrlShortener.cs:67
bool AllowsPOST
If the POST method is allowed.
Definition: UrlShortener.cs:49
UrlShortener()
Web Service, generating QR-codes based on URI input.
Definition: UrlShortener.cs:21
async Task POST(HttpRequest Request, HttpResponse Response)
Executes the POST method on the resource.
override bool HandlesSubPaths
If the resource handles sub-paths.
Definition: UrlShortener.cs:54
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repe...
KeyValuePair< string, string >[] QueryParameters
All query parameters.
Represents an HTTP request.
Definition: HttpRequest.cs:22
HttpRequestHeader Header
Request header.
Definition: HttpRequest.cs:182
string SubPath
Sub-path. If a resource is found handling the request, this property contains the trailing sub-path o...
Definition: HttpRequest.cs:194
async Task< ContentResponse > DecodeDataAsync()
Decodes data sent in request.
Definition: HttpRequest.cs:139
string ResourceName
Name of resource.
Represets a response of an HTTP client request.
Definition: HttpResponse.cs:23
async Task SendResponse()
Sends the response back to the client. If the resource is synchronous, there's no need to call this m...
Task Return(Exception ex)
Returns an error to the client.
Base class for all synchronous HTTP resources. A synchronous resource responds within the method hand...
The requested resource has been assigned a new permanent URI and any future references to this resour...
The server has not found anything matching the Request-URI. No indication is given of whether the con...
Implements an in-memory cache.
Definition: Cache.cs:17
GET Interface for HTTP resources.
POST Interface for HTTP resources.