Neuron®
The Neuron® is the basis for the creation of open and secure federated networks for smart societies.
Loading...
Searching...
No Matches
SetContractState.cs
1using System;
3using System.Threading.Tasks;
4using Waher.Content;
6using Waher.Events;
13using Waher.Security;
16
18{
20 {
21 public SetContractState()
22 : base("/SetContractState")
23 {
24 }
25
26 public override bool HandlesSubPaths => false;
27 public override bool UserSessions => true;
28 public bool AllowsPOST => true;
29
30 public async Task POST(HttpRequest Request, HttpResponse Response)
31 {
32 IUser User = Gateway.AssertUserAuthenticated(Request, "Admin.Notarius.Contracts");
33
34 if (!Request.HasData)
35 {
36 await Response.SendResponse(new BadRequestException());
37 return;
38 }
39
40 ContentResponse Content = await Request.DecodeDataAsync();
41 if (Content.HasError || !(Content.Decoded is Dictionary<string, object> Form))
42 {
43 await Response.SendResponse(new BadRequestException());
44 return;
45 }
46
47 if (!Form.TryGetValue("contractId", out object Obj) || !(Obj is string ContractId) ||
48 !Form.TryGetValue("state", out Obj) || !(Obj is string StateStr) ||
49 !Enum.TryParse(StateStr, out ContractState State))
50 {
51 await Response.SendResponse(new BadRequestException());
52 return;
53 }
54
55 Dictionary<string, object> Result = await SetState(ContractId, State, User);
56
57 Response.StatusCode = 200;
58 Response.StatusMessage = "OK";
59 Response.ContentType = JsonCodec.DefaultContentType;
60
61 await Response.Write(JSON.Encode(Result, false));
62 }
63
64 internal static async Task<Dictionary<string, object>> SetState(string ContractId, ContractState State, IUser User)
65 {
66 using Semaphore Semaphore = await Semaphores.BeginWrite("iotsc:" + ContractId.ToLower());
67
68 Contract Contract = await Database.FindFirstIgnoreRest<Contract>(new FilterFieldEqualTo("ContractId", ContractId))
69 ?? throw new NotFoundException("Contract not found.");
70
71 if (Contract.State == State)
72 {
73 return new Dictionary<string, object>()
74 {
75 { "message", null }
76 };
77 }
78
79 DateTime Now = DateTime.Now;
80 string Message;
81
82 Contract.State = State;
83 await Contract.Sign(XmppServerModule.Legal);
84
85 if (State == ContractState.Deleted)
86 {
88 Message = "Contract deleted.";
89
90 if (!(XmppServerModule.Geo is null))
91 await XmppServerModule.Geo.Delete(Contract);
92 }
93 else
94 {
96 Message = "Contract state changed to " + State.ToString() + ".";
97
98 switch (State)
99 {
100 case ContractState.Approved:
101 if (Contract.CanActAsTemplate)
102 await StateMachineProcessor.ContractTemplateApproved(Contract);
103 break;
104
105 case ContractState.Signed:
106 if (!(XmppServerModule.Geo is null))
107 await XmppServerModule.Geo.Publish(Contract);
108 break;
109
110 case ContractState.Obsoleted:
111 case ContractState.Rejected:
112 case ContractState.Failed:
113 if (!(XmppServerModule.Geo is null))
114 await XmppServerModule.Geo.Publish(Contract);
115 break;
116 }
117 }
118
119 await XmppServerModule.Legal.SendContractUpdatedEvent(Contract, false);
120
121 Log.Informational(Message, ContractId, User.UserName,
122 new KeyValuePair<string, object>("State", State));
123
124 if (Contract.CanActAsTemplate)
125 await RuntimeCounters.IncrementCounter("Legal.Template." + Contract.State.ToString());
126 else
127 await RuntimeCounters.IncrementCounter("Legal.Contract." + Contract.State.ToString());
128
129 return new Dictionary<string, object>()
130 {
131 { "date", Now.ToShortDateString() },
132 { "time", Now.ToLongTimeString() },
133 { "type", EventType.Informational },
134 { "object", ContractId },
135 { "actor", User.UserName },
136 { "message", Message },
137 { "signDate", Contract.ServerSignature.Timestamp.ToShortDateString() },
138 { "signTime", Contract.ServerSignature.Timestamp.ToLongTimeString() },
139 { "signature", Convert.ToBase64String(Contract.ServerSignature.DigitalSignature) }
140 };
141 }
142 }
143}
Contains information about a response to a content request.
bool HasError
If an error occurred.
object Decoded
Decoded object.
Helps with common JSON-related tasks.
Definition: JSON.cs:16
static string Encode(string s)
Encodes a string for inclusion in JSON.
Definition: JSON.cs:537
const string DefaultContentType
application/json
Definition: JsonCodec.cs:20
Static class managing the application event log. Applications and services log events on this static ...
Definition: Log.cs:14
static void Informational(string Message, string Object, string Actor, string EventId, EventLevel Level, string Facility, string Module, string StackTrace, params KeyValuePair< string, object >[] Tags)
Logs an informational event.
Definition: Log.cs:344
Static class managing the runtime environment of the IoT Gateway.
Definition: Gateway.cs:147
static IUser AssertUserAuthenticated(HttpRequest Request, string Privilege)
Makes sure a request is being made from a session with a successful user login.
Definition: Gateway.cs:3868
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
bool HasData
If the request has data.
Definition: HttpRequest.cs:113
async Task< ContentResponse > DecodeDataAsync()
Decodes data sent in request.
Definition: HttpRequest.cs:139
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.
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...
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 Delete(object Object)
Deletes an object in the database.
Definition: Database.cs:1291
This filter selects objects that have a named field equal to a given value.
Static class managing persistent counters.
static Task< long > IncrementCounter(CaseInsensitiveString Key)
Increments a counter.
Represents a named semaphore, i.e. an object, identified by a name, that allows single concurrent wri...
Definition: Semaphore.cs:19
Static class of application-wide semaphores that can be used to order access to editable objects.
Definition: Semaphores.cs:17
static async Task< Semaphore > BeginWrite(string Key)
Waits until the semaphore identified by Key is ready for writing. Each call to BeginWrite must be fo...
Definition: Semaphores.cs:91
bool AllowsPOST
If the POST method is allowed.
async Task POST(HttpRequest Request, HttpResponse Response)
Executes the POST method on the resource.
Service Module hosting the XMPP broker and its components.
POST Interface for HTTP resources.
Basic interface for a user.
Definition: IUser.cs:7
string UserName
User Name.
Definition: IUser.cs:12