This repository has been archived by the owner on May 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 51
/
Program.cs
520 lines (470 loc) · 20.1 KB
/
Program.cs
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
512
513
514
515
516
517
518
519
520
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Security;
using TrifleJS.Properties;
using TrifleJS.Native;
namespace TrifleJS
{
class Program
{
public static API.Context Context { get; set; }
public static List<string> Args { get; set; }
public static bool Verbose { get; set; }
public static bool SecureMode { get; set; }
public static bool InEventLoop { get; set; }
/// <summary>
/// Help message
/// </summary>
static void Help()
{
Console.WriteLine();
Console.WriteLine("==========================");
Console.WriteLine("TrifleJS.exe");
Console.WriteLine("Headless automation for Internet Explorer");
Console.WriteLine("==========================");
Console.WriteLine("http://triflejs.org/");
Console.WriteLine();
Console.WriteLine("Headless Internet Explorer with JavaScript API running on V8 engine.");
Console.WriteLine("PhantomJS for the Trident Engine.");
Console.WriteLine();
Console.WriteLine("(c) Steven de Salas 2015 - MIT Licence");
Console.WriteLine();
Console.WriteLine("Usage: triflejs.exe [options] somescript.js [argument [argument [...]]]");
Console.WriteLine();
Console.WriteLine("Options: ");
Console.WriteLine(" --debug=[true|false] Prints additional warning and debug messages");
//Console.WriteLine(" --ignore-ssl-errors=[true|false] Ignores SSL errors (cert expired, invalid etc). Defaults to 'false'.");
Console.WriteLine(" --render=[url] Opens a url, renders into a file and quits");
Console.WriteLine(" --emulate=[version] Emulate IE7, IE8, IE9, IE10, IE11 or EDGE12");
Console.WriteLine(" --output-encoding=[enc] Encoding for terminal output (default utf8)");
Console.WriteLine(" --script-encoding=[enc] Encoding for starting script (default utf8)");
Console.WriteLine(" --clear-cache Clears IE cache history before starting");
Console.WriteLine(" --secure-mode Disables ChildProcess and FileSystem modules");
Console.WriteLine(" --ignore-popups Ignores window popups (default false)");
Console.WriteLine(" --proxy=[address:port] Specifies proxy server to use");
Console.WriteLine(" --proxy-auth=[user:passw] Authentication information for the proxy");
Console.WriteLine();
Console.WriteLine(" -h, --help Show this message and quits");
Console.WriteLine(" -u, --unit-test Runs a full system test and quits");
Console.WriteLine(" -v, --version Prints out TrifleJS version and quits");
Console.WriteLine();
Console.WriteLine("Without arguments, TrifleJS will launch in interactive mode (REPL)");
Console.WriteLine();
}
/// <summary>
/// Program entry point
/// </summary>
/// <param name="args"></param>
[STAThread]
static void Main(string[] args)
{
// Commence
Program.Args = new List<string>();
#if DEBUG
Program.Verbose = true;
#endif
// Define environment
bool isExecuted = false;
bool isVersionSet = false;
bool optClearCache = false;
List<string> configLoop = new List<string>(args);
List<string> commandLoop = new List<string>();
API.Phantom.outputEncoding = "UTF-8";
API.Phantom.cookiesEnabled = true;
API.Phantom.libraryPath = Environment.CurrentDirectory;
// Check OS Support
CheckSupport();
// No arguments? Run in interactive mode.
if (args.Length < 1) {
Interactive();
return;
}
// Config Loop (Set IE version etc)
foreach (string arg in configLoop)
{
string[] parts = arg.Split('=');
switch (parts[0])
{
case "-?":
case "/?":
case "-h":
case "--help":
Help();
return;
case "--debug":
Program.Verbose = arg.Replace("--debug=", "").ToLower() != "false";
break;
case "-v":
case "--version":
var v = API.Trifle.Version;
Console.WriteLine("{0}.{1}.{2}", v["major"], v["minor"], v["patch"]);
return;
case "--emulate":
isVersionSet = Browser.Emulate(arg.Replace("--emulate=", "").ToUpper());
break;
case "--output-encoding":
API.Phantom.outputEncoding = arg.Replace("--output-encoding=", "");
break;
case "--script-encoding":
API.Phantom.scriptEncoding = arg.Replace("--script-encoding=", "");
break;
case "--clear-cache":
optClearCache = true;
break;
case "--secure-mode":
Program.SecureMode = true;
break;
case "--proxy":
Proxy.server = arg.Replace("--proxy=", "");
break;
case "--proxy-auth":
Proxy.auth = arg.Replace("--proxy-auth=", "");
break;
case "--proxy-type":
Proxy.type = arg.Replace("--proxy-type=", "");
break;
case "--ignore-popups":
Browser.IgnorePopups = true;
break;
case "--ignore-ssl-errors":
if (arg.Replace("--ignore-ssl-errors=", "").ToLower().Equals("true")) {
Browser.IgnoreSSLErrors = true;
}
break;
default:
commandLoop.Add(arg);
break;
}
}
// Echo input?
if (Program.Verbose) {
Utils.Debug("{0} {1}", AppDomain.CurrentDomain.FriendlyName, String.Join(" ", args));
}
// Clear cache?
if (optClearCache)
{
API.Console.xdebug("Clearing IE Cache History...");
Native.CacheHelper.ClearCache(false);
}
// Default to Installed Version
if (!isVersionSet)
{
String version = Browser.InstalledVersion();
if (!String.IsNullOrEmpty(version))
Browser.Emulate(version);
else
// No version? use IE7
Browser.Emulate("IE7");
}
// Set proxy information if needed
if (!String.IsNullOrEmpty(Proxy.server)) {
Proxy.Set();
}
// Command Loop - Execution
foreach (string arg in commandLoop)
{
Program.Args = new List<string> { arg };
string[] parts = arg.Split('=');
switch (parts[0])
{
case "-u":
case "--unit-test":
UnitTest();
Exit(0);
return;
case "-p":
case "--phantom-test":
PhantomTest();
Exit(0);
return;
case "--render":
string url = arg.Replace("--render=", "");
Render(url);
return;
default:
// If no switch is defined then we are dealing
// with javascript files that need executing
if (arg == parts[0] && !isExecuted)
{
Open(arg);
isExecuted = true;
}
else if (parts[0].StartsWith("--")) {
Help();
Exit(0);
}
break;
}
}
Exit(0);
}
/// <summary>
/// Checks support for various OS features
/// </summary>
private static void CheckSupport()
{
if (!System.Net.HttpListener.IsSupported)
{
API.Console.error("Windows XP SP2 or Server 2003 is required.");
Program.Exit(1);
}
// TODO: There has to be a better way to do this.
// 1. Why doesnt it work with older VC2008 redistributables?
// 2. If we need exact VC2008 distro, why cant we bundle it up?
if (!Native.Methods.MsiProductInstalled(new string[] {
"{FF66E9F6-83E7-3A3E-AF14-8DE9A809A6A4}",
"{9A25302D-30C0-39D9-BD6F-21E6EC160475}",
"{1F1C2DFC-2D24-3E06-BCB8-725134ADF989}",
"{9BE518E6-ECC6-35A9-88E4-87755C07200F}"}))
{
// @see https://github.com/sdesalas/trifleJS/issues/25
// @see http://blogs.msdn.com/b/astebner/archive/2009/01/29/9384143.aspx
API.Console.error("Latest Visual C++ 2008 SP1 Redistributable x86 is required.");
API.Console.error("Please download. http://www.microsoft.com/en-us/download/details.aspx?id=26368");
Program.Exit(1);
}
}
/// <summary>
/// Exits the current thread
/// </summary>
/// <param name="exitCode"></param>
public static void Exit(int exitCode)
{
Proxy.Backup.Restore();
if (Program.Verbose)
{
// Debugging? Wait for input
Console.WriteLine();
Console.WriteLine("Press any key to finish...");
Console.Read();
}
Environment.Exit(exitCode);
}
/// <summary>
/// Runs compatibility tests
/// </summary>
static void PhantomTest() {
Console.WriteLine();
Console.WriteLine("============================================");
Console.WriteLine("TrifleJS -- Phantom Compatibility Test");
Console.WriteLine("============================================");
Console.WriteLine();
using (Program.Context = Initialise())
{
try
{
// Load libs
Context.RunScript(Resources.test_lib_jasmine, "test/lib/jasmine.js");
Context.RunScript(Resources.test_lib_jasmine_console, "test/lib/jasmine-console.js");
Context.RunScript(Resources.test_unit_phantom_tools, "test/unit/phantom/tools.js");
// Load Spec
Context.RunScript(Resources.test_unit_phantom_spec_phantom, "test/unit/phantom/spec/phantom.js");
Context.RunScript(Resources.test_unit_phantom_spec_webserver, "test/unit/phantom/spec/webserver.js");
Context.RunScript(Resources.test_unit_phantom_spec_webserver, "test/unit/phantom/spec/webpage.js");
// Execute
Context.RunScript(Resources.test_unit_phantom_runjasmine, "test/unit/phantom/run-jasmine.js");
// Keep running until told to stop
// This is to make sure asynchronous code gets executed
while (true)
{
Program.DoEvents();
}
}
catch (Exception ex)
{
// Handle any exceptions
API.Context.Handle(ex);
}
}
}
/// <summary>
/// Runs unit tests
/// </summary>
static void UnitTest()
{
Console.WriteLine();
Console.WriteLine("============================================");
Console.WriteLine("TrifleJS -- Unit Tests");
Console.WriteLine("============================================");
Program.Verbose = false;
using (Program.Context = Initialise())
{
API.Phantom.scriptName = "-u";
try
{
// Add self-signed SSL cert on port 8043 if needed
bool sslSupport = true;
if (!Test.SSL.HttpApi.IsSslRegistered(8043)) {
Console.WriteLine("Generate Self-Signed SSL Certificate for Testing (Y/N)?");
if (Console.ReadLine().ToUpper() == "Y")
Test.SSL.CertEnroll.GenerateAndRegister(8043);
else
sslSupport = false;
}
// Initialise globals
Context.SetParameter("sslSupport", sslSupport);
// Load libs
Context.RunScript(Resources.test_unit_tools, "test/unit/tools.js");
// Execute Specs
// These are held as internal resources to enable scripts
// to be executed on any machine where the application is running.
Context.RunScript(Resources.test_unit_spec_env, "test/unit/spec/env.js");
Context.RunScript(Resources.test_unit_spec_require, "test/unit/spec/require.js");
Context.RunScript(Resources.test_unit_spec_system, "test/unit/spec/system.js");
Context.RunScript(Resources.test_unit_spec_fs, "test/unit/spec/fs.js");
Context.RunScript(Resources.test_unit_spec_webserver, "test/unit/spec/webserver.js");
Context.RunScript(Resources.test_unit_spec_phantom, "test/unit/spec/phantom.js");
Context.RunScript(Resources.test_unit_spec_webpage, "test/unit/spec/webpage.js");
Context.RunScript(Resources.test_unit_spec_ssl, "test/unit/spec/ssl.js");
Context.RunScript(Resources.test_unit_spec_child_process, "test/unit/spec/child_process.js");
// Finish
Context.RunScript(Resources.test_unit_finish, "test/unit/finish.js");
// Keep running until told to stop
// This is to make sure asynchronous code gets executed
while (true)
{
Program.DoEvents();
}
}
catch (Exception ex)
{
// Handle any exceptions
API.Context.Handle(ex);
Program.Exit(1);
}
}
}
/// <summary>
/// Run TrifleJS in interactive mode
/// </summary>
static void Interactive()
{
// Initialize and start console read loop;
using (Program.Context = Initialise())
{
while (true)
{
Console.Write("triflejs> ");
try
{
API.Console.log(Context.Run(Console.ReadLine(), "REPL"));
}
catch (Exception ex)
{
API.Context.Handle(ex);
}
}
}
}
/// <summary>
/// Renders a url
/// </summary>
/// <param name="url"></param>
static void Render(string url)
{
Console.WriteLine("Rendering " + url + "...");
// Check the URL
Uri uri = Browser.TryParse(url);
if (uri == null) {
Console.Error.WriteLine("Unable to open url: " + url);
return;
}
// Continue if ok
using (var browser = new Browser())
{
browser.Size = new Size(1024, 700);
browser.Navigate(url);
browser.RenderOnLoad(String.IsNullOrEmpty(uri.Host) ? "page.png" : uri.Host + ".png");
while (browser.ReadyState != System.Windows.Forms.WebBrowserReadyState.Complete)
{
Program.DoEvents();
}
}
}
/// <summary>
/// Opens a javascript file and executes in host environment
/// </summary>
/// <param name="filename">Path to a javascript file</param>
static void Open(string filename)
{
// Check file
if (!File.Exists(filename))
{
Console.Error.WriteLine(String.Format("File does not exist: {0}", filename));
Exit(1);
}
//Initialize a context
using (Program.Context = Initialise())
{
// Set Library Path
API.Phantom.libraryPath = new FileInfo(filename).DirectoryName;
API.Phantom.scriptName = new FileInfo(filename).Name;
try
{
// Run the script
Context.RunFile(filename);
// Keep running until told to stop
// This is to make sure asynchronous code gets executed
while (true) {
Program.DoEvents();
}
}
catch (Exception ex) {
// Handle any exceptions
API.Context.Handle(ex);
}
}
}
/// <summary>
/// Runs background events while waiting,
/// make sure that we track when we are on the
/// event loop to avoid recursion.
/// </summary>
public static void DoEvents()
{
Program.InEventLoop = true;
GC.Collect();
API.Window.CheckTimers();
API.Modules.WebServer.ProcessConnections();
Callback.ProcessQueue();
System.Windows.Forms.Application.DoEvents();
Program.InEventLoop = false;
}
/// <summary>
/// Initialises the environment
/// </summary>
/// <returns></returns>
static API.Context Initialise()
{
// Create new context
API.Context context = new API.Context();
API.Phantom.scriptName = "";
// Setting core global variables
context.SetParameter("console", new API.Console());
context.SetParameter("phantom", new API.Phantom());
context.SetParameter("trifle", new API.Trifle());
context.SetParameter("window", new API.Window());
try
{
// Initialise host env
context.RunScript(Resources.bootstrap, "bootstrap.js");
context.RunScript(Resources.trifle_Callback, "trifle.Callback.js");
context.RunScript(Resources.trifle_modules_WebPage, "trifle.modules.WebPage.js");
context.RunScript(Resources.trifle_modules_FileSystem, "trifle.modules.FileSystem.js");
context.RunScript(Resources.trifle_modules_System, "trifle.modules.System.js");
context.RunScript(Resources.trifle_modules_WebServer, "trifle.modules.WebServer.js");
context.RunScript(Resources.trifle_modules_ChildProcess, "trifle.modules.ChildProcess.js");
}
catch (Exception ex)
{
API.Context.Handle(ex);
}
// Return context
return context;
}
}
}