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;
2using System.Collections.Generic;
3using System.Threading.Tasks;
4using System.Xml;
5using Waher.Content;
16using Waher.Script;
23
25{
30 {
34 public GetContract()
35 : base("Legal/GetContract",
36 new KeyValuePair<Type, Expression>(typeof(Dictionary<string, object>), new Expression(jsonPattern)),
37 new KeyValuePair<Type, Expression>(typeof(XmlDocument), new Expression(xmlPattern)))
38 {
39 }
40
41 private static readonly string jsonPattern = Resources.LoadResourceAsText(typeof(GetContract).Namespace + ".JSON.GetContract.req");
42 private static readonly string xmlPattern = Resources.LoadResourceAsText(typeof(GetContract).Namespace + ".XML.GetContract.req");
43
48 public override bool Synchronous => false;
49
58 public override async Task POST(HttpRequest Request, HttpResponse Response, Dictionary<string, IElement> Parameters)
59 {
61 string ContractId = (string)Parameters["PContractId"].AssociatedObjectValue;
62 string FormatStr = (string)Parameters["PFormat"]?.AssociatedObjectValue;
63 int i = ContractId.IndexOf('@');
64 if (i < 0)
65 throw new BadRequestException("Invalid Contract ID.");
66
67 ReportFormat? Format = null;
68
69 if (!string.IsNullOrEmpty(FormatStr))
70 {
71 if (Enum.TryParse(FormatStr, out ReportFormat F))
72 Format = F;
73 else
74 throw new BadRequestException("Unsupported report format: " + FormatStr);
75 }
76
77 string LegalDomain = ContractId.Substring(i + 1);
78
79 if (XmppServerModule.Server is null)
80 {
82
83 if (Client is null)
84 {
85 if (Types.TryGetModuleParameter("XMPP", out object Obj) && Obj is XmppClient Client2)
86 Client = Client2;
87 }
88
89 if (Client is null)
90 throw new ServiceUnavailableException("XMPP Client not available.");
91
92 await Client.SendIqGet(LegalDomain, "<getContract id=\"" + XML.Encode(ContractId) + "\" xmlns=\"" +
93 LegalComponent.NamespaceSmartContracts(NamespaceSet.Current) + "\"/>", async (Sender, e) =>
94 {
95 XmlElement E;
96
97 if (e.Ok && !((E = e.FirstElement) is null) && E.LocalName == "contract")
98 {
99 if (Format.HasValue)
100 {
101 ParsedContract ParsedContract = await Contract.Parse(E, XmppServerModule.Legal);
102 if (!(ParsedContract.Contract is null))
103 E = await FormatHumanReadableText(E, Format.Value, ParsedContract.Contract);
104 }
105
106 await Response.Return(new NamedDictionary<string, object>("ContractResponse", AgentNamespace)
107 {
108 { "Contract", E }
109 });
110 }
111 else
112 await Response.SendResponse(ToHttpException(e.StanzaError) ?? new ServiceUnavailableException("Unable to get contract."));
113
114 }, null);
115 }
116 else
117 {
118 await XmppServerModule.Server.SendIqRequest("get",
119 User.UserName + "@" + (Gateway.Domain?.Value ?? string.Empty),
120 LegalDomain, string.Empty, "<getContract id=\"" + XML.Encode(ContractId) + "\" xmlns=\"" +
121 LegalComponent.NamespaceSmartContracts(NamespaceSet.Current) + "\"/>", async (Sender, e) =>
122 {
123 XmlElement E;
124
125 if (e.Ok && !((E = e.FirstElement) is null) && E.LocalName == "contract")
126 {
127 if (Format.HasValue)
128 {
129 ParsedContract ParsedContract = await Contract.Parse(E, XmppServerModule.Legal);
130 if (!(ParsedContract.Contract is null))
131 E = await FormatHumanReadableText(E, Format.Value, ParsedContract.Contract);
132 }
133
134 await Response.Return(new NamedDictionary<string, object>("ContractResponse", AgentNamespace)
135 {
136 { "Contract", E }
137 });
138 }
139 else
140 await Response.SendResponse(ToHttpException(XmppClient.GetExceptionObject(e.ErrorElement)) ?? new ServiceUnavailableException("Unable to get contract."));
141
142 }, null);
143 }
144 }
145
146 private static async Task<XmlElement> FormatHumanReadableText(XmlElement E, ReportFormat Format, Contract Contract)
147 {
148 XmlElement E2;
149
150 if (E.LocalName == "description" ||
151 E.LocalName == "humanReadableText" ||
152 E.LocalName == "label")
153 {
155
156 if (!(Text is null))
157 {
160
161 string Markdown = MarkdownOutput.ToString();
162 MarkdownDocument Doc = await MarkdownDocument.CreateAsync(Markdown);
163
164 E2 = E.OwnerDocument.CreateElement(E.Prefix, E.LocalName + Format.ToString(), E.NamespaceURI);
165
166 if (!string.IsNullOrEmpty(Text.Language))
167 E2.SetAttribute("xml:lang", Text.Language);
168
169 switch (Format)
170 {
171 case ReportFormat.Markdown:
172 E2.InnerText = await Doc.GenerateMarkdown(true);
173 break;
174
175 case ReportFormat.Html:
176 E2.InnerText = HtmlDocument.GetBody(await Doc.GenerateHTML());
177 break;
178
179 case ReportFormat.Text:
180 E2.InnerText = await Doc.GeneratePlainText();
181 break;
182
183 case ReportFormat.Xaml:
184 E2.InnerText = await Doc.GenerateXAML();
185 break;
186
187 case ReportFormat.XamarinXaml:
188 E2.InnerText = await Doc.GenerateXamarinForms();
189 break;
190
191 case ReportFormat.SmartContract:
192 E2.InnerText = await Doc.GenerateSmartContractXml();
193 break;
194 }
195 }
196 else
197 E2 = E;
198 }
199 else
200 {
201 E2 = E.OwnerDocument.CreateElement(E.Prefix, E.LocalName, E.NamespaceURI);
202
203 foreach (XmlAttribute Attr in E.Attributes)
204 E2.SetAttribute(Attr.Name, Attr.NamespaceURI, Attr.Value);
205
206 foreach (XmlNode N in E.ChildNodes)
207 {
208 if (N is XmlElement E3)
209 E2.AppendChild(await FormatHumanReadableText(E3, Format, Contract));
210 }
211 }
212
213 return E2;
214 }
215
216 }
217}
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 ...
Static class managing loading of resources stored as embedded resources or in content files.
Definition: Resources.cs:15
static string LoadResourceAsText(string ResourceName)
Loads a text resource from an embedded resource.
Definition: Resources.cs:96
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 runtime environment of the IoT Gateway.
Definition: Gateway.cs:126
static CaseInsensitiveString Domain
Domain name.
Definition: Gateway.cs:2354
static XmppClient XmppClient
XMPP Client connection of gateway.
Definition: Gateway.cs:3187
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:18
Represets a response of an HTTP client request.
Definition: HttpResponse.cs:21
async Task SendResponse()
Sends the response back to the client. If the resource is synchronous, there's no need to call this m...
async Task Return(object Object)
Returns an object to the client. This method can only be called once per response,...
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:59
static XmppException GetExceptionObject(XmlElement StanzaElement)
Gets an XMPP Exception object corresponding to its XML definition.
Definition: XmppClient.cs:3301
Task< uint > SendIqGet(string To, string Xml, EventHandlerAsync< IqResultEventArgs > Callback, object State)
Sends an IQ Get request.
Definition: XmppClient.cs:3559
Static class that dynamically manages types and interfaces available in the runtime environment.
Definition: Types.cs:14
static bool TryGetModuleParameter(string Name, out object Value)
Tries to get a module parameter value.
Definition: Types.cs:583
Class managing a script expression.
Definition: Expression.cs:39
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(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