Neuron®
The Neuron® is the basis for the creation of open and secure federated networks for smart societies.
Loading...
Searching...
No Matches
WebNode.cs
1using System;
2using System.IO;
3using System.Text;
4using System.Threading.Tasks;
5using System.Web;
6using System.Xml;
10using Waher.Events;
15using Waher.Script;
17
19{
21 {
22 private readonly CaseInsensitiveString nodeName;
23
24 public WebNode(CaseInsensitiveString NodeName)
25 : base("/" + NodeName)
26 {
27 this.nodeName = NodeName;
28 }
29
30 public override bool HandlesSubPaths => true;
31 public override bool UserSessions => true;
32 public bool AllowsGET => true;
33
34 private static async Task<PubSubContent.Content> GetContent(PubSubItem Item)
35 {
36 if (!(Item.Tag is PubSubContent.Content Content))
37 {
38 XmlDocument Xml = new XmlDocument()
39 {
40 PreserveWhitespace = true
41 };
42 Xml.LoadXml(Item.Payload);
43
44 Content = await PubSubContent.Content.Deserialize(Xml.DocumentElement, Item.Publisher,
45 new PubSubContent.NodeReference[] { new PubSubContent.NodeReference(Item.Node, Item.Service) }, Item.ItemId);
46 Item.Tag = Content;
47 }
48
49 return Content;
50 }
51
52 public async Task GET(HttpRequest Request, HttpResponse Response)
53 {
54 Variables v;
55 MarkdownSettings Settings;
57 CaseInsensitiveString ItemId = Request.SubPath;
58 string Markdown;
59 string HTML;
60 string FileName;
61
62 if (string.IsNullOrEmpty(ItemId) || ItemId == "/")
63 {
64 PubSubNode Node = await XmppServerModule.GetPubSubNodeAsync(this.nodeName)
65 ?? throw new NotFoundException();
66
67 v = new Variables(new Variable("Node", Node));
68 FileName = Path.Combine(Gateway.RootFolder, "PublicNode.md");
69 }
70 else
71 {
72 PubSubItem Item = await XmppServerModule.PubSub.LoadItem(CaseInsensitiveString.Empty, this.nodeName, ItemId);
73
74 if (Item is null && ItemId.StartsWith("/"))
75 Item = await XmppServerModule.PubSub.LoadItem(CaseInsensitiveString.Empty, this.nodeName, ItemId.Substring(1));
76
77 if (Item is null)
78 {
79 string ItemId2 = HttpUtility.UrlDecode(ItemId);
80
81 if (ItemId != ItemId2)
82 {
83 ItemId = ItemId2;
84 Item = await XmppServerModule.PubSub.LoadItem(CaseInsensitiveString.Empty, this.nodeName, ItemId);
85
86 if (Item is null && ItemId.StartsWith("/"))
87 Item = await XmppServerModule.PubSub.LoadItem(CaseInsensitiveString.Empty, this.nodeName, ItemId.Substring(1));
88 }
89
90 if (Item is null)
91 throw new NotFoundException();
92 }
93
94 PubSubContent.Content Content = await GetContent(Item);
95
96 v = new Variables(new Variable("Content", Content), new Variable("Item", Item), new Variable("ShowLink", false));
97 FileName = Path.Combine(Gateway.RootFolder, "PublicItem.md");
98 }
99
100 Settings = PubSubContent.MarkdownContent.GetMarkdownSettings(v, true);
101 Markdown = File.ReadAllText(FileName);
102 Doc = await MarkdownDocument.CreateAsync(Markdown, Settings, FileName, string.Empty, Request.Header.GetURL());
103 HTML = await Doc.GenerateHTML();
104
105 Response.ContentType = HtmlCodec.DefaultContentType;
106 await Response.Write(HTML);
107 }
108
109 public static async Task<string> GetItemTitle(PubSubContent.Content Content, PubSubItem Item)
110 {
111 string s;
112
113 if (Content is null)
114 return string.Empty;
115
116 try
117 {
118 if (Content is PubSubContent.MarkdownContent MarkdownContent)
119 {
120 s = await MarkdownContent.TryGetMetaDataValue("Title");
121 if (!string.IsNullOrEmpty(s))
122 return s;
123 }
124 }
125 catch (Exception ex)
126 {
127 Log.Exception(ex);
128 }
129
130 s = Content.ObjectOrItemId ?? string.Empty;
131 int i = s.LastIndexOf('/');
132 if (i >= 0)
133 s = s.Substring(i + 1);
134
135 StringBuilder sb = new StringBuilder();
136 bool Capital = true;
137
138 foreach (char ch in s)
139 {
140 if (ch == '_')
141 {
142 sb.Append(' ');
143 Capital = true;
144 }
145 else if (Capital)
146 {
147 sb.Append(char.ToUpper(ch));
148 Capital = false;
149 }
150 else
151 sb.Append(char.ToLower(ch));
152 }
153
154 return sb.ToString().Trim();
155 }
156
157 public static async Task<string> GetItemDescription(PubSubContent.Content Content, PubSubItem Item)
158 {
159 string s;
160
161 try
162 {
163 if (Content is null)
164 return string.Empty;
165
166 if (Content is PubSubContent.MarkdownContent MarkdownContent)
167 {
168 s = await MarkdownContent.TryGetMetaDataValue("Description");
169 if (!string.IsNullOrEmpty(s))
170 return s;
171 }
172 }
173 catch (Exception ex)
174 {
175 Log.Exception(ex);
176 }
177
178 return "Item published on node " + Item?.Node;
179 }
180
181 public static async Task<string> GetItemDate(PubSubContent.Content Content, PubSubItem Item)
182 {
183 string s;
184
185 if (Content is null)
186 return string.Empty;
187
188 try
189 {
190 if (Content is PubSubContent.MarkdownContent MarkdownContent)
191 {
192 s = await MarkdownContent.TryGetMetaDataValue("Date");
193 if (!string.IsNullOrEmpty(s))
194 return s;
195 }
196 }
197 catch (Exception ex)
198 {
199 Log.Exception(ex);
200 }
201
202 if (Item is null)
203 return string.Empty;
204 else
205 return XML.Encode(Item.Created, true);
206 }
207
208 public static async Task<string> GetItemAuthor(PubSubContent.Content Content, PubSubItem Item)
209 {
210 string s;
211
212 if (Content is null)
213 return string.Empty;
214
215 try
216 {
217 if (Content is PubSubContent.MarkdownContent MarkdownContent)
218 {
219 s = await MarkdownContent.TryGetMetaDataValue("Author");
220 if (!string.IsNullOrEmpty(s))
221 return s;
222 }
223 }
224 catch (Exception ex)
225 {
226 Log.Exception(ex);
227 }
228
229 return Item?.Publisher ?? string.Empty;
230 }
231
232 public static PubSubItem[] GetItems(CaseInsensitiveString Node, string From, int MaxCount, out bool More, out string Last)
233 {
234 Tuple<PubSubItem[], bool, string> T = GetItemsAsync(Node, From, MaxCount).Result;
235
236 More = T.Item2;
237 Last = T.Item3;
238
239 return T.Item1;
240 }
241
242 public static async Task<Tuple<PubSubItem[], bool, string>> GetItemsAsync(CaseInsensitiveString Node, string From, int MaxCount)
243 {
245 if (PubSubNode is null || !PubSubNode.PublishOnWeb)
246 return new Tuple<PubSubItem[], bool, string>(null, false, string.Empty);
247
248 Tuple<PubSubItem[], bool, string> Result = await XmppServerModule.PubSub.LoadItems(string.Empty, Node, From, MaxCount)
249 ?? throw new NotFoundException();
250
251 foreach (PubSubItem Item in Result.Item1)
252 await GetContent(Item);
253
254 return Result;
255 }
256
257 }
258}
HTML encoder/decoder.
Definition: HtmlCodec.cs:13
const string DefaultContentType
Default Content-Type for HTML: text/html
Definition: HtmlCodec.cs:24
Class that can be used to encapsulate Markdown to be returned from a Web Service, bypassing any encod...
Contains a markdown document. This markdown document class supports original markdown,...
async Task< string > GenerateHTML()
Generates HTML from the markdown text.
static Task< MarkdownDocument > CreateAsync(string MarkdownText, params Type[] TransparentExceptionTypes)
Contains a markdown document. This markdown document class supports original markdown,...
Contains settings that the Markdown parser uses to customize its behavior.
Helps with common XML-related tasks.
Definition: XML.cs:19
static string Encode(string s)
Encodes a string for use in XML.
Definition: XML.cs:27
Static class managing the application event log. Applications and services log events on this static ...
Definition: Log.cs:13
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:1647
Static class managing the runtime environment of the IoT Gateway.
Definition: Gateway.cs:126
static string RootFolder
Web root folder.
Definition: Gateway.cs:2379
string GetURL()
Gets an absolute URL for the request.
Represents an HTTP request.
Definition: HttpRequest.cs:18
HttpRequestHeader Header
Request header.
Definition: HttpRequest.cs:134
string SubPath
Sub-path. If a resource is found handling the request, this property contains the trailing sub-path o...
Definition: HttpRequest.cs:146
Represets a response of an HTTP client request.
Definition: HttpResponse.cs:21
async Task Write(byte[] Data)
Returns binary data in the response.
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...
Contains information about one XMPP address.
Definition: XmppAddress.cs:9
static readonly XmppAddress Empty
Empty address.
Definition: XmppAddress.cs:31
Represents a case-insensitive string.
static readonly CaseInsensitiveString Empty
Empty case-insensitive string
bool StartsWith(CaseInsensitiveString value)
Determines whether the beginning of this string instance matches the specified string.
CaseInsensitiveString Substring(int startIndex, int length)
Retrieves a substring from this instance. The substring starts at a specified character position and ...
Contains information about a variable.
Definition: Variable.cs:10
Collection of variables.
Definition: Variables.cs:25
async Task< PubSubNode > GetNodeAsync(CaseInsensitiveString Service, CaseInsensitiveString NodeName, NodeAccessModel? AutoCreateAccess, XmppAddress From, CaseInsensitiveString Domain)
Gets a pubsub node.
CaseInsensitiveString Node
Name of node.
Definition: PubSubItem.cs:83
CaseInsensitiveString Publisher
Publisher of content.
Definition: PubSubItem.cs:92
object Tag
Allows the caller to tag the object with an arbitrary value.
Definition: PubSubItem.cs:140
DateTime Created
When item was created.
Definition: PubSubItem.cs:101
CaseInsensitiveString ItemId
Item ID.
Definition: PubSubItem.cs:50
Defines a node on which items can be published.
Definition: PubSubNode.cs:19
bool PublishOnWeb
If the items published to the node should be available on the web or not.
Definition: PubSubNode.cs:654
async Task GET(HttpRequest Request, HttpResponse Response)
Executes the GET method on the resource.
Definition: WebNode.cs:52
bool AllowsGET
If the GET method is allowed.
Definition: WebNode.cs:32
Service Module hosting the XMPP broker and its components.
GET Interface for HTTP resources.