Neuron®
The Neuron® is the basis for the creation of open and secure federated networks for smart societies.
Loading...
Searching...
No Matches
GetContract.cs
1using System;
3using System.Threading.Tasks;
4using System.Xml;
5using Waher.Content;
17using Waher.Script;
24
26{
31 {
35 public GetContract()
36 : base("Legal/GetContract",
37 new KeyValuePair<Type, Expression>(typeof(Dictionary<string, object>), new Expression(jsonPattern)),
38 new KeyValuePair<Type, Expression>(typeof(XmlDocument), new Expression(xmlPattern)))
39 {
40 }
41
42 private static readonly string jsonPattern = Resources.LoadResourceAsText(typeof(GetContract).Namespace + ".JSON.GetContract.req");
43 private static readonly string xmlPattern = Resources.LoadResourceAsText(typeof(GetContract).Namespace + ".XML.GetContract.req");
44
49 public override bool Synchronous => false;
50
59 public override async Task POST(HttpRequest Request, HttpResponse Response, Dictionary<string, IElement> Parameters)
60 {
62 string ContractId = (string)Parameters["PContractId"].AssociatedObjectValue;
63 string FormatStr = (string)Parameters["PFormat"]?.AssociatedObjectValue;
64 int i = ContractId.IndexOf('@');
65 if (i < 0)
66 throw new BadRequestException("Invalid Contract ID.");
67
68 ReportFormat? Format = null;
69
70 if (!string.IsNullOrEmpty(FormatStr))
71 {
72 if (Enum.TryParse(FormatStr, out ReportFormat F))
73 Format = F;
74 else
75 throw new BadRequestException("Unsupported report format: " + FormatStr);
76 }
77
78 string LegalDomain = ContractId[(i + 1)..];
79
80 if (XmppServerModule.Server is null)
81 {
83
84 if (Client is null)
85 {
86 if (Types.TryGetModuleParameter("XMPP", out XmppClient Client2))
87 Client = Client2;
88 }
89
90 if (Client is null)
91 throw new ServiceUnavailableException("XMPP Client not available.");
92
93 await Client.SendIqGet(LegalDomain, "<getContract id=\"" + XML.Encode(ContractId) + "\" xmlns=\"" +
94 LegalComponent.NamespaceSmartContracts(NamespaceSet.Current) + "\"/>", async (Sender, e) =>
95 {
96 XmlElement E;
97
98 if (e.Ok && !((E = e.FirstElement) is null) && E.LocalName == "contract")
99 {
100 if (Format.HasValue)
101 {
102 ParsedContract ParsedContract = await Contract.Parse(E, XmppServerModule.Legal);
103 if (!(ParsedContract.Contract is null))
104 E = await FormatHumanReadableText(E, Format.Value, ParsedContract.Contract);
105 }
106
107 await Response.Return(new NamedDictionary<string, object>("ContractResponse", AgentNamespace)
108 {
109 { "Contract", E }
110 });
111 }
112 else
113 await Response.SendResponse(ToHttpException(Request, e.StanzaError) ?? new ServiceUnavailableException("Unable to get contract."));
114
115 }, null);
116 }
117 else
118 {
119 await XmppServerModule.Server.SendIqRequest("get",
120 User.UserName + "@" + (Gateway.Domain?.Value ?? string.Empty),
121 LegalDomain, string.Empty, "<getContract id=\"" + XML.Encode(ContractId) + "\" xmlns=\"" +
122 LegalComponent.NamespaceSmartContracts(NamespaceSet.Current) + "\"/>", true, async (Sender, e) =>
123 {
124 XmlElement E;
125
126 if (e.Ok && !((E = e.FirstElement) is null) && E.LocalName == "contract")
127 {
128 if (Format.HasValue)
129 {
130 ParsedContract ParsedContract = await Contract.Parse(E, XmppServerModule.Legal);
131 if (!(ParsedContract.Contract is null))
132 E = await FormatHumanReadableText(E, Format.Value, ParsedContract.Contract);
133 }
134
135 await Response.Return(new NamedDictionary<string, object>("ContractResponse", AgentNamespace)
136 {
137 { "Contract", E }
138 });
139 }
140 else
141 await Response.SendResponse(ToHttpException(Request, XmppClient.GetExceptionObject(e.ErrorElement)) ?? new ServiceUnavailableException("Unable to get contract."));
142
143 }, null);
144 }
145 }
146
147 private static async Task<XmlElement> FormatHumanReadableText(XmlElement E, ReportFormat Format, Contract Contract)
148 {
149 XmlElement E2;
150
151 if (E.LocalName == "description" ||
152 E.LocalName == "humanReadableText" ||
153 E.LocalName == "label")
154 {
156
157 if (!(Text is null))
158 {
161 {
162 Language = Text.Language,
164 Level = 2,
165 Indentation = 0
166 };
167
168 await Text.ToMarkdown(MarkdownOutput, State);
169
170 string Markdown = MarkdownOutput.ToString();
171 MarkdownDocument Doc = await MarkdownDocument.CreateAsync(Markdown);
172
173 E2 = E.OwnerDocument.CreateElement(E.Prefix, E.LocalName + Format.ToString(), E.NamespaceURI);
174
175 if (!string.IsNullOrEmpty(Text.Language))
176 E2.SetAttribute("xml:lang", Text.Language);
177
178 switch (Format)
179 {
180 case ReportFormat.Markdown:
181 E2.InnerText = await Doc.GenerateMarkdown(true);
182 break;
183
184 case ReportFormat.Html:
185 E2.InnerText = HtmlDocument.GetBody(await Doc.GenerateHTML());
186 break;
187
188 case ReportFormat.Text:
189 E2.InnerText = await Doc.GeneratePlainText();
190 break;
191
192 case ReportFormat.Xaml:
193 E2.InnerText = await Doc.GenerateXAML();
194 break;
195
196 case ReportFormat.XamarinXaml:
197 E2.InnerText = await Doc.GenerateXamarinForms();
198 break;
199
200 case ReportFormat.SmartContract:
201 E2.InnerText = await Doc.GenerateSmartContractXml();
202 break;
203 }
204 }
205 else
206 E2 = E;
207 }
208 else
209 {
210 E2 = E.OwnerDocument.CreateElement(E.Prefix, E.LocalName, E.NamespaceURI);
211
212 foreach (XmlAttribute Attr in E.Attributes)
213 E2.SetAttribute(Attr.Name, Attr.NamespaceURI, Attr.Value);
214
215 foreach (XmlNode N in E.ChildNodes)
216 {
217 if (N is XmlElement E3)
218 E2.AppendChild(await FormatHumanReadableText(E3, Format, Contract));
219 }
220 }
221
222 return E2;
223 }
224
225 }
226}
static string GetBody(string Html)
Extracts the contents of the BODY element in a HTML string.
Contains a markdown document. This markdown document class supports original markdown,...
Task< string > GenerateMarkdown()
Generates Markdown from the markdown text.
async Task< string > GeneratePlainText()
Generates Plain Text from the markdown text.
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,...
A Named dictionary is a dictionary, with a local name and a namespace. Use it to return content that ...
Helps with common XML-related tasks.
Definition: XML.cs:21
static string Encode(string s)
Encodes a string for use in XML.
Definition: XML.cs:29
Static class managing the runtime environment of the IoT Gateway.
Definition: Gateway.cs:147
static CaseInsensitiveString Domain
Domain name.
Definition: Gateway.cs:3087
static XmppClient XmppClient
XMPP Client connection of gateway.
Definition: Gateway.cs:4038
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repe...
Represents an HTTP request.
Definition: HttpRequest.cs:22
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.
The server is currently unable to handle the request due to a temporary overloading or maintenance of...
Manages an XMPP client connection. Implements XMPP, as defined in https://tools.ietf....
Definition: XmppClient.cs:58
static XmppException GetExceptionObject(XmlElement StanzaElement)
Gets an XMPP Exception object corresponding to its XML definition.
Definition: XmppClient.cs:3340
Task< uint > SendIqGet(string To, string Xml, EventHandlerAsync< IqResultEventArgs > Callback, object State)
Sends an IQ Get request.
Definition: XmppClient.cs:3598
Static class managing loading of resources stored as embedded resources or in content files.
Definition: Resources.cs:13
static string LoadResourceAsText(string ResourceName)
Loads a text resource from an embedded resource.
Definition: Resources.cs:55
Static class that dynamically manages types and interfaces available in the runtime environment.
Definition: Types.cs:15
static bool TryGetModuleParameter(string Name, out object Value)
Tries to get a module parameter value.
Definition: Types.cs:607
Class managing a script expression.
Definition: Expression.cs:41
Abstract base class for agent resources supporting the POST method.
static AccountUser AssertUserAuthenticated(HttpRequest Request)
Makes sure the request is made by an authenticated API user.
const string AgentNamespace
https://waher.se/Schema/BrokerAgent.xsd
static Exception ToHttpException(HttpRequest Request, XmppException ex)
Tries to convert an XMPP Exception to an HTTP Exception.
Service Module hosting the XMPP broker and its components.
ReportFormat
Desired report format
Definition: ReportFormat.cs:7
NamespaceSet
Namespace versions
Definition: NamespaceSet.cs:7