-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathHttpScriptResource.cs
More file actions
333 lines (289 loc) · 9.72 KB
/
HttpScriptResource.cs
File metadata and controls
333 lines (289 loc) · 9.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Waher.Content;
using Waher.Networking.HTTP.HeaderFields;
using Waher.Script;
using Waher.Script.Abstraction.Elements;
using Waher.Script.Exceptions;
using Waher.Script.Model;
using Waher.Script.Objects;
namespace Waher.Networking.HTTP
{
/// <summary>
/// Publishes a web resource whose contents is produced by script.
/// </summary>
public class HttpScriptResource : HttpSynchronousResource, IHttpGetMethod
{
private readonly Expression script;
private readonly ScriptNode scriptNode;
private readonly string referenceFileName;
private readonly bool userSessions;
private readonly HttpAuthenticationScheme[] authenticationSchemes;
/// <summary>
/// Publishes a web resource whose contents is produced by script.
/// </summary>
/// <param name="ResourceName">Name of resource.</param>
/// <param name="Script">Script expression.</param>
/// <param name="ReferenceFileName">Optional reference file name for script.</param>
/// <param name="UserSessions">If the resource uses user sessions.</param>
/// <param name="AuthenticationSchemes">Any authentication schemes used to authenticate users before access is granted.</param>
public HttpScriptResource(string ResourceName, string Script, string ReferenceFileName, bool UserSessions, params HttpAuthenticationScheme[] AuthenticationSchemes)
: this(ResourceName, new Expression(Script), ReferenceFileName, UserSessions, AuthenticationSchemes)
{
}
/// <summary>
/// Publishes a web resource whose contents is produced by script.
/// </summary>
/// <param name="ResourceName">Name of resource.</param>
/// <param name="Script">Script expression.</param>
/// <param name="ReferenceFileName">Optional reference file name for script.</param>
/// <param name="UserSessions">If the resource uses user sessions.</param>
/// <param name="AuthenticationSchemes">Any authentication schemes used to authenticate users before access is granted.</param>
public HttpScriptResource(string ResourceName, Expression Script, string ReferenceFileName, bool UserSessions, params HttpAuthenticationScheme[] AuthenticationSchemes)
: base(ResourceName)
{
this.script = Script;
this.scriptNode = null;
this.referenceFileName = ReferenceFileName;
this.userSessions = UserSessions;
this.authenticationSchemes = AuthenticationSchemes;
}
/// <summary>
/// Publishes a web resource whose contents is produced by script.
/// </summary>
/// <param name="ResourceName">Name of resource.</param>
/// <param name="Script">Script expression.</param>
/// <param name="ReferenceFileName">Optional reference file name for script.</param>
/// <param name="UserSessions">If the resource uses user sessions.</param>
/// <param name="AuthenticationSchemes">Any authentication schemes used to authenticate users before access is granted.</param>
public HttpScriptResource(string ResourceName, ScriptNode Script, string ReferenceFileName, bool UserSessions, params HttpAuthenticationScheme[] AuthenticationSchemes)
: base(ResourceName)
{
this.script = null;
this.scriptNode = Script;
this.referenceFileName = ReferenceFileName;
this.userSessions = UserSessions;
this.authenticationSchemes = AuthenticationSchemes;
}
/// <summary>
/// If the resource handles sub-paths.
/// </summary>
public override bool HandlesSubPaths => true;
/// <summary>
/// If the resource uses user sessions.
/// </summary>
public override bool UserSessions => this.userSessions;
/// <summary>
/// If the GET method is allowed.
/// </summary>
public bool AllowsGET => true;
/// <summary>
/// Any authentication schemes used to authenticate users before access is granted to the corresponding resource.
/// </summary>
/// <param name="Request">Current request</param>
public override HttpAuthenticationScheme[] GetAuthenticationSchemes(HttpRequest Request)
{
return this.authenticationSchemes;
}
/// <summary>
/// Executes the GET method on the resource.
/// </summary>
/// <param name="Request">HTTP Request</param>
/// <param name="Response">HTTP Response</param>
/// <exception cref="HttpException">If an error occurred when processing the method.</exception>
public async Task GET(HttpRequest Request, HttpResponse Response)
{
SessionVariables v = Request.Session ?? new SessionVariables();
bool SessionLocked;
if (v.Locked)
SessionLocked = false;
else
{
v = new SessionVariables();
await v.LockAsync();
v.CurrentRequest = Request;
v.CurrentResponse = Response;
SessionLocked = true;
}
try
{
object Result;
if (!(this.script is null))
Result = await this.script.EvaluateAsync(v);
else if (!(this.scriptNode is null))
{
IElement E;
try
{
if (this.scriptNode.IsAsynchronous)
E = await this.scriptNode.EvaluateAsync(v);
else
E = this.scriptNode.Evaluate(v);
}
catch (ScriptReturnValueException ex)
{
E = ex.ReturnValue;
//ScriptReturnValueException.Reuse(ex);
}
catch (ScriptBreakLoopException ex)
{
E = ex.LoopValue ?? ObjectValue.Null;
//ScriptBreakLoopException.Reuse(ex);
}
catch (ScriptContinueLoopException ex)
{
E = ex.LoopValue ?? ObjectValue.Null;
//ScriptContinueLoopException.Reuse(ex);
}
Result = E.AssociatedObjectValue;
}
else
Result = null;
if (Response.ResponseSent)
return;
HttpRequestHeader Header = Request.Header;
if (Header.Accept is null)
{
await Response.Return(Result);
return;
}
ContentResponse P = await InternetContent.EncodeAsync(Result, Encoding.UTF8);
if (P.HasError)
{
await Response.SendResponse(P.Error);
return;
}
byte[] Binary = P.Encoded;
string ContentType = P.ContentType;
bool Acceptable = Header.Accept.IsAcceptable(ContentType, out double Quality, out AcceptanceLevel TypeAcceptance, null);
if (!Acceptable || TypeAcceptance == AcceptanceLevel.Wildcard)
{
IContentConverter Converter = null;
string NewContentType = null;
int i = ContentType.IndexOf(';');
string ContentTypeNoParams = i < 0 ? ContentType : ContentType.Substring(0, i).TrimEnd();
foreach (AcceptRecord AcceptRecord in Header.Accept.Records)
{
NewContentType = AcceptRecord.Item;
if (NewContentType.EndsWith("/*"))
{
NewContentType = null;
continue;
}
if (InternetContent.CanConvert(ContentTypeNoParams, NewContentType, out Converter))
{
Acceptable = true;
break;
}
}
if (Converter is null)
{
IContentConverter[] Converters = InternetContent.GetConverters(ContentTypeNoParams);
if (!(Converters is null))
{
string BestContentType = null;
double BestQuality = 0;
IContentConverter Best = null;
bool Found;
foreach (IContentConverter Converter2 in Converters)
{
Found = false;
foreach (string FromContentType in Converter2.FromContentTypes)
{
if (ContentTypeNoParams == FromContentType)
{
Found = true;
break;
}
}
if (!Found)
continue;
foreach (string ToContentType in Converter2.ToContentTypes)
{
if (Header.Accept.IsAcceptable(ToContentType, out double Quality2) && Quality > BestQuality)
{
BestContentType = ToContentType;
BestQuality = Quality;
Best = Converter2;
}
else if (BestQuality == 0 && ToContentType == "*")
{
BestContentType = ContentType;
BestQuality = double.Epsilon;
Best = Converter2;
}
}
}
if (!(Best is null) && (!Acceptable || BestQuality >= Quality))
{
Acceptable = true;
Converter = Best;
NewContentType = BestContentType;
}
}
}
if (Acceptable && !(Converter is null))
{
MemoryStream f2 = null;
MemoryStream f = new MemoryStream(Binary);
try
{
f2 = new MemoryStream();
List<string> Alternatives = null;
string[] Range = Converter.ToContentTypes;
bool All = Range.Length == 1 && Range[0] == "*";
foreach (AcceptRecord AcceptRecord in Header.Accept.Records)
{
if (AcceptRecord.Item.EndsWith("/*") || AcceptRecord.Item == NewContentType)
continue;
if (All || Array.IndexOf(Range, AcceptRecord.Item) >= 0)
{
if (Alternatives is null)
Alternatives = new List<string>();
Alternatives.Add(AcceptRecord.Item);
}
}
ConversionState State = new ConversionState(ContentType, f, this.referenceFileName, this.ResourceName,
Request.Header.GetURL(false, false), NewContentType, f2, Request.Session, Response.Progress,
Request.Server, Request.TryGetLocalResourceFileName, Alternatives?.ToArray());
if (await Converter.ConvertAsync(State))
Response.SetHeader("Cache-Control", "max-age=0, no-cache, no-store");
if (State.HasError)
{
await Response.SendResponse(State.Error);
return;
}
NewContentType = State.ToContentType;
ContentType = NewContentType;
Acceptable = true;
Binary = f2.ToArray();
}
finally
{
f?.Dispose();
f2?.Dispose();
}
}
}
if (!Acceptable)
{
await Response.SendResponse(new NotAcceptableException());
return;
}
await Response.Return(ContentType, true, Binary);
}
finally
{
if (SessionLocked)
{
v.CurrentRequest = null;
v.CurrentResponse = null;
v.Release();
}
}
}
}
}