forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHtmlWebResponseObject.Common.cs
More file actions
511 lines (421 loc) · 16.8 KB
/
Copy pathHtmlWebResponseObject.Common.cs
File metadata and controls
511 lines (421 loc) · 16.8 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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
#if !CORECLR
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Management.Automation;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using mshtml;
using System.Diagnostics;
using System.Threading;
using ExecutionContext = System.Management.Automation.ExecutionContext;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Response object for html content
/// </summary>
public partial class HtmlWebResponseObject : WebResponseObject, IDisposable
{
#region Properties
/// <summary>
/// gets or protected sets the Content property
/// </summary>
public new string Content { get; private set; }
// The HTML document
private IHTMLDocument2 _parsedHtml;
// The reset event for synchronizing the 'IHTMLDocument2.write()' call
private ManualResetEventSlim _stateChangeResetEvent;
// The reset event for synchronizing loading the document
private ManualResetEventSlim _loadDocumentResetEvent;
// The handler for the 'onreadystatechange' event
private HTMLDocumentEvents2_onreadystatechangeEventHandler _onreadystatechangeEventHandler;
// The exception thrown during the parsing
private Exception _parsingException;
// The current execution context
private readonly ExecutionContext _executionContext;
// The flag that notifies the worker thread to stop loading the document
private bool _stopWorkerThread;
// The flag that indicates the html is parsed
private bool _htmlParsed = false;
/// <summary>
/// gets the ParsedHtml property
/// </summary>
public IHTMLDocument2 ParsedHtml
{
get
{
EnsureHtmlParser();
return _parsedHtml;
}
}
private FormObjectCollection _forms;
/// <summary>
/// gets the Forms property
/// </summary>
public FormObjectCollection Forms
{
get
{
if (_forms == null)
{
_forms = BuildFormsCollection();
}
return _forms;
}
}
private WebCmdletElementCollection _inputFields;
/// <summary>
/// gets the Fields property
/// </summary>
public WebCmdletElementCollection InputFields
{
get
{
if (_inputFields == null)
{
EnsureHtmlParser();
List<PSObject> parsedFields = new List<PSObject>();
foreach (IHTMLElement element in _parsedHtml.all)
{
if (element.tagName.Equals("INPUT", StringComparison.OrdinalIgnoreCase))
{
parsedFields.Add(CreateHtmlObject(element, true));
}
System.Runtime.InteropServices.Marshal.ReleaseComObject(element);
}
_inputFields = new WebCmdletElementCollection(parsedFields);
}
return _inputFields;
}
}
private WebCmdletElementCollection _links;
/// <summary>
/// gets the Links property
/// </summary>
public WebCmdletElementCollection Links
{
get
{
if (_links == null)
{
EnsureHtmlParser();
List<PSObject> parsedLinks = new List<PSObject>();
foreach (IHTMLElement element in _parsedHtml.links)
{
parsedLinks.Add(CreateHtmlObject(element, true));
System.Runtime.InteropServices.Marshal.ReleaseComObject(element);
}
_links = new WebCmdletElementCollection(parsedLinks);
}
return _links;
}
}
private WebCmdletElementCollection _images;
/// <summary>
/// gets the Images property
/// </summary>
public WebCmdletElementCollection Images
{
get
{
if (_images == null)
{
EnsureHtmlParser();
List<PSObject> parsedImages = new List<PSObject>();
foreach (IHTMLElement element in _parsedHtml.images)
{
parsedImages.Add(CreateHtmlObject(element, true));
System.Runtime.InteropServices.Marshal.ReleaseComObject(element);
}
_images = new WebCmdletElementCollection(parsedImages);
}
return _images;
}
}
private WebCmdletElementCollection _scripts;
/// <summary>
/// gets the Scripts property
/// </summary>
public WebCmdletElementCollection Scripts
{
get
{
if (_scripts == null)
{
EnsureHtmlParser();
List<PSObject> parsedScripts = new List<PSObject>();
foreach (IHTMLElement element in _parsedHtml.scripts)
{
parsedScripts.Add(CreateHtmlObject(element, true));
System.Runtime.InteropServices.Marshal.ReleaseComObject(element);
}
_scripts = new WebCmdletElementCollection(parsedScripts);
}
return _scripts;
}
}
private WebCmdletElementCollection _allElements;
/// <summary>
/// gets the Elements property
/// </summary>
public WebCmdletElementCollection AllElements
{
get
{
if (_allElements == null)
{
EnsureHtmlParser();
List<PSObject> parsedElements = new List<PSObject>();
foreach (IHTMLElement element in _parsedHtml.all)
{
parsedElements.Add(CreateHtmlObject(element, true));
System.Runtime.InteropServices.Marshal.ReleaseComObject(element);
}
_allElements = new WebCmdletElementCollection(parsedElements);
}
return _allElements;
}
}
#endregion Properties
#region Private Fields
private static Regex _tagRegex;
private static Regex _attribsRegex;
private static Regex _attribNameValueRegex;
#endregion Private Fields
#region Methods
// The "onreadystatechange" event handler
private void ReadyStateChanged(IHTMLEventObj obj)
{
if (String.Equals("complete", _parsedHtml.readyState, StringComparison.OrdinalIgnoreCase))
{
_stateChangeResetEvent.Set();
}
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
}
// Load the document in a worker thread
private void LoadDocumentInMtaThread(Object state)
{
try
{
// Create a new IHTMLDocument2 object
_parsedHtml = (IHTMLDocument2)new HTMLDocument();
// Attach the event handler
var events = (HTMLDocumentEvents2_Event)_parsedHtml;
events.onreadystatechange += _onreadystatechangeEventHandler;
// Write the content and close the document
_parsedHtml.write(Content);
_parsedHtml.close();
// Wait for the onReadyStateChange event to be fired. On IE9, this never happens
// so we check the readyState directly as well.
bool wait = true;
while (wait && !_stopWorkerThread)
{
if (String.Equals("complete", _parsedHtml.readyState, StringComparison.OrdinalIgnoreCase))
{
break;
}
wait = !_stateChangeResetEvent.Wait(100);
}
// Detach the event handler
events.onreadystatechange -= _onreadystatechangeEventHandler;
}
catch (Exception e)
{
_parsingException = e;
}
finally
{
_loadDocumentResetEvent.Set();
}
}
private void EnsureHtmlParser()
{
if (_htmlParsed == false)
{
// Initialization
_stopWorkerThread = false;
_parsingException = null;
_stateChangeResetEvent = new ManualResetEventSlim();
_loadDocumentResetEvent = new ManualResetEventSlim();
_onreadystatechangeEventHandler = new HTMLDocumentEvents2_onreadystatechangeEventHandler(ReadyStateChanged);
// The IHTMLDocument events cannot be handled in STA ApartmentState, so we use a worker thread to load the document
ThreadPool.QueueUserWorkItem(new WaitCallback(LoadDocumentInMtaThread));
// Wait for the worker thread to finish loading the document. In the meantime, we check the Ctrl-C every 500ms
bool wait = true;
while (wait)
{
if (_executionContext.CurrentPipelineStopping)
{
// Signal and wait for the worker thread to exit, then break out the loop
_stopWorkerThread = true;
_loadDocumentResetEvent.Wait();
break;
}
wait = !_loadDocumentResetEvent.Wait(500);
}
// Ctrl-C is typed
if (_executionContext.CurrentPipelineStopping)
{
throw new PipelineStoppedException();
}
// If there is no Ctrl-C, throw if an exception happened during the parsing
if (_parsingException != null)
{
throw _parsingException;
}
// Parsing was successful
_htmlParsed = true;
}
if (_tagRegex == null)
{
_tagRegex = new Regex(@"<\w+((\s+[^""'>/=\s\p{Cc}]+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)+\s*|\s*)/?>",
RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled);
}
if (_attribsRegex == null)
{
_attribsRegex = new Regex(@"(?<=\s+)([^""'>/=\s\p{Cc}]+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)",
RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled);
}
if (_attribNameValueRegex == null)
{
_attribNameValueRegex = new Regex(@"([^""'>/=\s\p{Cc}]+)(?:\s*=\s*(?:""(.*?)""|'(.*?)'|([^'"">\s]+)))?",
RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled);
}
}
private PSObject CreateHtmlObject(IHTMLElement element, bool addTagName)
{
PSObject elementObject = new PSObject();
elementObject.Properties.Add(new PSNoteProperty("innerHTML", element.innerHTML));
elementObject.Properties.Add(new PSNoteProperty("innerText", element.innerText));
elementObject.Properties.Add(new PSNoteProperty("outerHTML", element.outerHTML));
elementObject.Properties.Add(new PSNoteProperty("outerText", element.outerText));
if (addTagName)
{
elementObject.Properties.Add(new PSNoteProperty("tagName", element.tagName));
}
ParseAttributes(element.outerHTML, elementObject);
return elementObject;
}
private void ParseAttributes(string outerHtml, PSObject elementObject)
{
// We might get an empty input for a directive from the HTML file
if (!string.IsNullOrEmpty(outerHtml))
{
// Extract just the opening tag of the HTML element (omitting the closing tag and any contents,
// including contained HTML elements)
var match = _tagRegex.Match(outerHtml);
// Extract all the attribute specifications within the HTML element opening tag
var attribMatches = _attribsRegex.Matches(match.Value);
foreach (Match attribMatch in attribMatches)
{
// Extract the name and value for this attribute (allowing for variations like single/double/no
// quotes, and no value at all)
var nvMatches = _attribNameValueRegex.Match(attribMatch.Value);
Debug.Assert(nvMatches.Groups.Count == 5);
// Name is always captured by group #1
string name = nvMatches.Groups[1].Value;
// The value (if any) is captured by group #2, #3, or #4, depending on quoting or lack thereof
string value = null;
if (nvMatches.Groups[2].Success)
{
value = nvMatches.Groups[2].Value;
}
else if (nvMatches.Groups[3].Success)
{
value = nvMatches.Groups[3].Value;
}
else if (nvMatches.Groups[4].Success)
{
value = nvMatches.Groups[4].Value;
}
elementObject.Properties.Add(new PSNoteProperty(name, value));
}
}
}
private FormObjectCollection BuildFormsCollection()
{
FormObjectCollection forms = new FormObjectCollection();
EnsureHtmlParser();
foreach (IHTMLFormElement form in _parsedHtml.forms)
{
string id = GetElementId(form as IHTMLElement);
if (null == id)
{
id = form.name;
}
FormObject f = new FormObject(id, form.method, form.action);
foreach (IHTMLElement element in form)
{
IHTMLInputElement input = element as IHTMLInputElement;
if (null != input)
{
id = GetElementId(input as IHTMLElement);
if (null == id)
{
id = input.name;
}
f.AddField(id, input.value);
}
System.Runtime.InteropServices.Marshal.ReleaseComObject(element);
}
forms.Add(f);
System.Runtime.InteropServices.Marshal.ReleaseComObject(form);
}
return (forms);
}
private string GetElementId(IHTMLElement element)
{
return (null == element ? null : element.id);
}
/// <summary>
/// Reads the response content from the web response.
/// </summary>
private void InitializeContent()
{
string contentType = ContentHelper.GetContentType(BaseResponse);
if (ContentHelper.IsText(contentType))
{
// fill the Content buffer
string characterSet = WebResponseHelper.GetCharacterSet(BaseResponse);
this.Content = StreamHelper.DecodeStream(RawContentStream, characterSet);
}
else
{
this.Content = string.Empty;
}
}
#endregion Methods
/// <summary>
/// Dispose the the instance of the class.
/// </summary>
public void Dispose()
{
CleanupNativeResources();
if (_loadDocumentResetEvent != null)
{
_loadDocumentResetEvent.Dispose();
}
if (_stateChangeResetEvent != null)
{
_stateChangeResetEvent.Dispose();
}
GC.SuppressFinalize(this);
}
/// <summary>
/// Finalizer to free the COM objects.
/// </summary>
~HtmlWebResponseObject()
{
CleanupNativeResources();
}
private void CleanupNativeResources()
{
if (_parsedHtml != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(_parsedHtml);
}
}
}
}
#endif