Neuron®
The Neuron® is the basis for the creation of open and secure federated networks for smart societies.
Loading...
Searching...
No Matches
PublicTokenView.cs
1using System;
3using System.Text;
4using System.Threading.Tasks;
8using Waher.Events;
12
14{
19 {
20 private readonly Dictionary<string, TaskCompletionSource<string>> renderings = new Dictionary<string, TaskCompletionSource<string>>();
21
26 : base("/NF")
27 {
28 }
29
30 public override bool HandlesSubPaths => true;
31 public override bool UserSessions => true;
32 public bool AllowsGET => true;
33
35
36 public async Task GET(HttpRequest Request, HttpResponse Response)
37 {
38 if (string.IsNullOrEmpty(Request.SubPath))
39 {
40 await Response.SendResponse(new BadRequestException("Missing Token ID."));
41 return;
42 }
43
44 string TokenId = Request.SubPath[1..];
45 int i = TokenId.IndexOf('@');
46 if (i < 0 || !Guid.TryParse(TokenId[..i], out _))
47 {
48 await Response.SendResponse(new BadRequestException("Invalid Token ID."));
49 return;
50 }
51
52 Token Token = await NeuroFeaturesProcessor.GetToken(TokenId, true);
53 if (Token is null)
54 {
55 await Response.SendResponse(new NotFoundException("Token '" + TokenId + "' not found on this neuron."));
56 return;
57 }
58
59 if (!Token.IsPublic)
60 {
61 await Response.SendResponse(new ForbiddenException("Token not publicly accissible via the web."));
62 return;
63 }
64
66 {
67 await Response.SendResponse(new BadRequestException("Token does not have an associated state-machine."));
68 return;
69 }
70
71 TaskCompletionSource<string> Pending;
72 bool WaitPending;
73 string Result;
74
75 lock (this.renderings)
76 {
77 if (this.renderings.TryGetValue(TokenId, out Pending))
78 WaitPending = true;
79 else
80 {
81 WaitPending = false;
82 Pending = new TaskCompletionSource<string>();
83 this.renderings[TokenId] = Pending;
84 }
85 }
86
87 try
88 {
89 if (WaitPending)
90 Result = await Pending.Task;
91 else
92 {
93 StringBuilder Html = new StringBuilder();
94 string s;
95
97 string Description = await Doc.GeneratePlainText();
98
99 Html.AppendLine("<!DOCTYPE html>");
100 Html.AppendLine("<html itemscope itemtype=\"http://schema.org/WebPage\">");
101 Html.AppendLine("<head>");
102 Html.Append("<title>");
104 Html.AppendLine("</title>");
105 Html.Append("<meta name=\"twitter:title\" content=\"");
106 Html.Append(s = XML.HtmlAttributeEncode(Token.FriendlyName));
107 Html.AppendLine("\"/>");
108 Html.Append("<meta name=\"og:title\" content=\"");
109 Html.Append(s);
110 Html.AppendLine("\"/>");
111 Html.Append("<meta itemprop=\"description\" content=\"");
112 Html.Append(s = XML.HtmlAttributeEncode(Description));
113 Html.AppendLine("\"/>");
114 Html.Append("<meta name=\"twitter:description\" content=\"");
115 Html.Append(s);
116 Html.AppendLine("\"/>");
117 Html.Append("<meta name=\"og:description\" content=\"");
118 Html.Append(s);
119 Html.AppendLine("\"/>");
120 Html.Append("<meta name=\"description\" content=\"");
121 Html.Append(s);
122 Html.Append(" Author: ");
123 Html.Append(s = MarkdownDocument.Encode(Token.Creator.Value));
124 Html.Append(", Date: ");
125 Html.Append(XML.Encode(Token.Created, true));
126 Html.AppendLine("\"/>");
127 Html.AppendLine("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"/>");
128 Html.Append("<meta name=\"author\" content=\"");
129 Html.Append(s);
130 Html.AppendLine("\"/>");
131 Html.AppendLine("<link rel=\"shortcut icon\" href=\"/favicon.ico\"/>");
132 Html.Append("<link rel=\"stylesheet\" href=\"");
133 Html.Append(XML.HtmlAttributeEncode(Theme.CurrentTheme.CSSX));
134 Html.AppendLine("\"/>");
135 Html.AppendLine("<script type=\"application/javascript\" src=\"/Events.js\"></script>");
136 Html.AppendLine("<script type=\"text/javascript\">");
137 Html.AppendLine("function UpdatePresent(Data) { document.getElementById('Present').innerHTML=Data; }");
138 Html.AppendLine("</script>");
139 Html.AppendLine("</head>");
140 Html.AppendLine("<body>");
141 Html.AppendLine("<main>");
142 Html.AppendLine("<section id='Present'>");
143
144 Html.AppendLine(await Token.GeneratePresentReport(ReportFormat.Html));
145
146 Html.AppendLine("</section>");
147 Html.AppendLine("</main>");
148 Html.AppendLine("</body>");
149 Html.AppendLine("</html>");
150
151 Result = Html.ToString();
152 Pending.TrySetResult(Result);
153 }
154 }
155 catch (Exception ex)
156 {
157 if (WaitPending)
158 Pending.TrySetException(ex);
159
160 await Response.SendResponse(ex);
161 return;
162 }
163 finally
164 {
165 if (!WaitPending)
166 {
167 lock (this.renderings)
168 {
169 this.renderings.Remove(TokenId);
170 }
171 }
172 }
173
174 Response.ContentType = HtmlCodec.DefaultContentType;
175 Response.SetHeader("Cache-Control", "max-age=0, no-cache, no-store");
176
177 await Response.Write(Result);
178 await Response.SendResponse();
179 }
180
181 internal static async Task UpdatePresent(string[] TabIDs, Token Token)
182 {
183 try
184 {
185 string Html = await Token.GeneratePresentReport(ReportFormat.Html);
186 await ClientEvents.PushEvent(TabIDs, "UpdatePresent", Html, false);
187 }
188 catch (Exception ex)
189 {
190 Log.Exception(ex);
191 }
192 }
193 }
194}
HTML encoder/decoder.
Definition: HtmlCodec.cs:15
const string DefaultContentType
Default Content-Type for HTML: text/html
Definition: HtmlCodec.cs:26
Contains a markdown document. This markdown document class supports original markdown,...
static string Encode(string s)
Encodes all special characters in a string so that it can be included in a markdown document without ...
async Task< string > GeneratePlainText()
Generates Plain Text from the markdown text.
static Task< MarkdownDocument > CreateAsync(string MarkdownText, params Type[] TransparentExceptionTypes)
Contains a markdown document. This markdown document class supports original markdown,...
Helps with common XML-related tasks.
Definition: XML.cs:21
static string HtmlValueEncode(string s)
Differs from Encode(String), in that it does not encode the aposotrophe or the quote.
Definition: XML.cs:211
static string Encode(string s)
Encodes a string for use in XML.
Definition: XML.cs:29
static string HtmlAttributeEncode(string s)
Differs from Encode(String), in that it does not encode the aposotrophe.
Definition: XML.cs:121
Static class managing the application event log. Applications and services log events on this static ...
Definition: Log.cs:14
static void Exception(Exception Exception, string Object, string Actor, string EventId, EventLevel Level, string Facility, string Module, params KeyValuePair< string, object >[] Tags)
Logs an exception. Event type will be determined by the severity of the exception.
Definition: Log.cs:1657
The ClientEvents class allows applications to push information asynchronously to web clients connecte...
Definition: ClientEvents.cs:51
static Task< int > PushEvent(string[] TabIDs, string Type, object Data)
Puses an event to a set of Tabs, given their Tab IDs.
static ThemeDefinition CurrentTheme
Current theme.
Definition: Theme.cs:90
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repe...
The server understood the request, but is refusing to fulfill it. Authorization will not help and the...
Base class for all HTTP authentication schemes, as defined in RFC-7235: https://datatracker....
Represents an HTTP request.
Definition: HttpRequest.cs:22
string SubPath
Sub-path. If a resource is found handling the request, this property contains the trailing sub-path o...
Definition: HttpRequest.cs:194
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 Write(byte[] Data)
Returns binary data in the response.
void SetHeader(string FieldName, string Value)
Sets a custom header field value.
Base class for all synchronous HTTP resources. A synchronous resource responds within the method hand...
The server has not found anything matching the Request-URI. No indication is given of whether the con...
Marketplace processor, brokering sales of items via tenders and offers defined in smart contracts.
Task< string > GeneratePresentReport()
Generates a present report for the token, if the token is associated with a state-machine,...
Definition: Token.cs:1463
bool HasStateMachine
If the token has an associated state-machine.
Definition: Token.cs:1345
bool IsPublic
If the token is public.
Definition: Token.cs:181
string FriendlyName
A friendly name for the token.
Definition: Token.cs:512
string Description
Description Markdown for the token.
Definition: Token.cs:531
DateTime Created
When token was created.
Definition: Token.cs:384
CaseInsensitiveString Creator
Creator of token
Definition: Token.cs:189
override HttpAuthenticationScheme[] GetAuthenticationSchemes(HttpRequest Request)
Any authentication schemes used to authenticate users before access is granted to the corresponding r...
async Task GET(HttpRequest Request, HttpResponse Response)
Executes the GET method on the resource.
GET Interface for HTTP resources.
Definition: ImplTypes.g.cs:58
ReportFormat
Desired report format
Definition: ReportFormat.cs:7