Neuron®
The Neuron® is the basis for the creation of open and secure federated networks for smart societies.
Loading...
Searching...
No Matches
ProposeTemplate.cs
1using System;
3using System.Text;
4using System.Threading.Tasks;
5using System.Xml;
6using Waher.Content;
9using Waher.Events;
15using Waher.Script;
22
24{
29 {
34 : base("Legal/ProposeTemplate",
35 new KeyValuePair<Type, Expression>(typeof(Dictionary<string, object>), new Expression(jsonPattern)),
36 new KeyValuePair<Type, Expression>(typeof(XmlDocument), new Expression(xmlPattern)))
37 {
38 }
39
40 private static readonly string jsonPattern = Resources.LoadResourceAsText(typeof(ProposeTemplate).Namespace + ".JSON.ProposeTemplate.req");
41 private static readonly string xmlPattern = Resources.LoadResourceAsText(typeof(ProposeTemplate).Namespace + ".XML.ProposeTemplate.req");
42
51 public override async Task POST(HttpRequest Request, HttpResponse Response, Dictionary<string, IElement> Parameters)
52 {
54
55 string TemplateBase64 = (string)Parameters["PTemplateBase64"].AssociatedObjectValue;
56 byte[] TemplateBin;
57 string TemplateXmlString;
58 XmlDocument TemplateXml;
59 ParsedContract Parsed;
60 Contract Template;
61
62 try
63 {
64 TemplateBin = Convert.FromBase64String(TemplateBase64);
65 }
66 catch (Exception)
67 {
68 throw new BadRequestException("Invalid BASE64-encoding of template.");
69 }
70
71 try
72 {
73 TemplateXmlString = Strings.GetString(TemplateBin, Encoding.UTF8);
74
75 TemplateXml = XML.ParseXml(TemplateXmlString, true);
76 }
77 catch (Exception ex)
78 {
79 throw new BadRequestException("Invalid template XML, or encoding of template XML: " + ex.Message);
80 }
81
82 try
83 {
84 Parsed = await Contract.Parse(TemplateXml.DocumentElement, XmppServerModule.Legal);
85 }
86 catch (Exception ex)
87 {
88 throw new BadRequestException("Unable to parse contract XML: " + ex.Message);
89 }
90
91 Template = Parsed.Contract
92 ?? throw new BadRequestException("Unable to parse contract XML.");
93
94 if (Parsed.HasStatus)
95 throw new BadRequestException("Status element not permitted when creating new contract.");
96
98 throw new BadRequestException("id attribute must not be set by client.");
99
100 if (!(Template.ClientSignatures is null) && Template.ClientSignatures.Length > 0)
101 throw new BadRequestException("Predefined signatures not permitted.");
102
103 if (!(Template.ServerSignature is null))
104 throw new BadRequestException("Server signature cannot be provided by client.");
105
106 if (Template.PartsMode == ContractParts.ExplicitlyDefined && (Template.Parts is null || Template.Parts.Length == 0))
107 throw new BadRequestException("No explicit parts defined.");
108
109 if (Template.PartsMode != ContractParts.TemplateOnly)
110 throw new BadRequestException("Contract is not a template.");
111
112 if (Template.Duration <= Duration.Zero)
113 throw new BadRequestException("Contract duration must be positive.");
114
115 CaseInsensitiveString LegalDomain;
116
117 if (XmppServerModule.Legal is null)
118 LegalDomain = "legal.example.com";
119 else
120 {
121 string Errors = await XmppServerModule.Legal?.CheckContentIntegrity(Template);
122 if (!string.IsNullOrEmpty(Errors))
123 throw new BadRequestException(Errors);
124
126 ?? throw new ForbiddenException(Request, "No current approved legal identity found for account.");
127
128 Errors = await XmppServerModule.Legal.ValidateContent(Template, null);
129 if (!string.IsNullOrEmpty(Errors))
130 throw new BadRequestException(Errors);
131
132 LegalDomain = Identity.Provider;
133 }
134
135 Template.State = ContractState.Proposed;
136 Template.Provider = LegalDomain;
137 Template.Account = User.UserName;
138 Template.Created = LegalComponent.UtcNowSecond;
139 Template.Updated = DateTime.MinValue;
140
141 await Database.Insert(Template);
142
143 Template.ContractId = Template.ObjectId + "@" + Template.Provider;
144 await Template.Sign(XmppServerModule.Legal);
145
146 await Database.Update(Template);
147
148 if (Template.CanActAsTemplate)
149 await RuntimeCounters.IncrementCounter("Legal.Template." + Template.State.ToString());
150 else
151 await RuntimeCounters.IncrementCounter("Legal.Contract." + Template.State.ToString());
152
153 KeyValuePair<string, object>[] Tags = Template.GetTags();
154 string FromJid = User.UserName + "@" + Request.Host;
155
156 Log.Notice("Contract proposal registered.",
157 Template.ContractId.Value, FromJid, "ContractRegistered", Tags);
158
160 {
161 StringBuilder Markdown = new StringBuilder();
162
163 Markdown.Append("Contract proposal received: [");
164 Markdown.Append(MarkdownDocument.Encode(Template.ContractId));
165 Markdown.Append("](");
166 Markdown.Append(Gateway.GetUrl("/Contract.md?ID=" + Template.ContractId));
167 Markdown.AppendLine(")");
168 Markdown.AppendLine();
169 LegalComponent.Output(Markdown, Tags);
170
171 await Gateway.SendNotification(Markdown.ToString());
172 }
173
174 XmppServerModule.Legal?.ContractAuthorization(FromJid, FromJid, Template.ContractId, true);
175
176 if (!(XmppServerModule.Legal is null))
177 await XmppServerModule.Legal.SendContractUpdatedEvent(Template, true);
178
179 StringBuilder Xml = new StringBuilder();
180 await Template.Serialize(Xml, true, true, true, true, true, true, true, null, XmppServerModule.Legal);
181 TemplateXmlString = Xml.ToString();
182
183 TemplateXml = XML.ParseXml(TemplateXmlString, true);
184
185 await Response.Return(new NamedDictionary<string, object>("TemplateResponse", AgentNamespace)
186 {
187 { "Template", TemplateXml },
188 });
189 }
190
191 }
192}
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 ...
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 XmlDocument ParseXml(string Xml)
Parses an XML Document from its string representation.
Definition: XML.cs:713
Static class managing the application event log. Applications and services log events on this static ...
Definition: Log.cs:14
static void Notice(string Message, string Object, string Actor, string EventId, EventLevel Level, string Facility, string Module, string StackTrace, params KeyValuePair< string, object >[] Tags)
Logs a notice event.
Definition: Log.cs:460
Static class managing the runtime environment of the IoT Gateway.
Definition: Gateway.cs:147
static Task SendNotification(Graph Graph)
Sends a graph as a notification message to configured notification recipients.
Definition: Gateway.cs:4677
static string GetUrl(string LocalResource)
Gets a URL for a resource.
Definition: Gateway.cs:5079
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...
Represents an HTTP request.
Definition: HttpRequest.cs:22
string Host
Host reference. (Value of Host header, without the port number)
Definition: HttpRequest.cs:263
Represets a response of an HTTP client request.
Definition: HttpResponse.cs:23
Task Return(Exception ex)
Returns an error to the client.
Represents a case-insensitive string.
string Value
String-representation of the case-insensitive string. (Representation is case sensitive....
static bool IsNullOrEmpty(CaseInsensitiveString value)
Indicates whether the specified string is null or an CaseInsensitiveString.Empty string.
Static interface for database persistence. In order to work, a database provider has to be assigned t...
Definition: Database.cs:21
static async Task Update(object Object)
Updates an object in the database.
Definition: Database.cs:1211
static async Task Insert(object Object)
Inserts an object into the default collection of the database.
Definition: Database.cs:97
Static class managing persistent counters.
static Task< long > IncrementCounter(CaseInsensitiveString Key)
Increments a counter.
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 managing binary representations of strings.
Definition: Strings.cs:10
static string GetString(byte[] Data, int Offset, int Count, Encoding DefaultEncoding)
Gets a string from its binary representation, taking any Byte Order Mark (BOM) into account.
Definition: Strings.cs:148
Class managing a script expression.
Definition: Expression.cs:41
Provides the user with options to control notifications from the Broker.
static BrokerNotificationConfiguration Instance
Current instance of configuration.
bool ContractProposalReceived
If a notification should be sent when a contract proposal has been received.
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
Service Module hosting the XMPP broker and its components.
Represents a duration value, as defined by the xsd:duration data type: http://www....
Definition: Duration.cs:14
static readonly Duration Zero
Zero value
Definition: Duration.cs:577