var utils = require('utils');
// utils.dump() for debug
var fs = require('fs');

var scriptDir = fs.absolute(require('system').args[3]).replace('apple-membercenter-expires.js', '');

var select_team_page = 'https://developer.apple.com/account/selectTeam.action';
var distrib_certs_page = 'https://developer.apple.com/account/ios/certificate/certificateList.action?type=distribution';
var distrib_profiles_page = 'https://developer.apple.com/account/ios/profile/profileList.action?type=production';
var prog_summary_page = 'https://developer.apple.com/membercenter/index.action#progSummary';

var teams;
var certificates = {};
var profiles = {};
var programs = {};
var statfile;   
var hasExpirations = false;

var casper = require('casper').create({
  pageSettings: {
    loadImages:  false,
    loadPlugins: false
  },
  // logLevel: "debug",
  // logLevel: "info",
  // verbose: true
});

casper.on('remote.message', function(msg) {
  this.echo('remote message caught: ' + msg);
});
Beispiel #2
0
var webpage = require("webpage"),
    fs = require("fs");

var html_path = fs.absolute("test.html");
var examples = [];

function run_example(example_index) {
    if (example_index >= examples.length) {
        phantom.exit(0);
        return;
    }

    var example = examples[example_index];
    var snapshot_index = 0;
    var page = webpage.create();

    page.viewportSize = { width: 500, height: 300 };
    page.clipRect = { width: 500, height: 300 };
    page.onAlert = function(msg) {
        var e = JSON.parse(msg);
        if (e.fn == "snapshot") {
            page.render("output/" + example.name + snapshot_index + ".png");
            snapshot_index += 1;
        } else if (e.fn == "mousemove") {
            page.sendEvent("mousemove", e.x, e.y);
        }
    };

    page.open(html_path,
        function(status) {
            if (status == "fail") {
Beispiel #3
0
casper.test.begin( 'textfield  tests', function ( test ) {

    phantomcss.init( {
        rebase: casper.cli.get( "rebase" ),
        // SlimerJS needs explicit knowledge of this Casper, and lots of absolute paths
        casper: casper,
        libraryRoot: fs.absolute( fs.workingDirectory + '' ),
        screenshotRoot: fs.absolute( fs.workingDirectory + '/screenshots/textfield' ),
        failedComparisonsRoot: fs.absolute( fs.workingDirectory + '/failures/textfield' ),
        addLabelToFailedImage: false
    } );

    casper.on( 'remote.message', function ( msg ) {
        this.echo( msg );
    } );

    casper.on( 'error', function ( err ) {
        this.die( "PhantomJS has errored: " + err );
    } );

    casper.on( 'resource.error', function ( err ) {
        casper.log( 'Resource load error: ' + err, 'warning' );
    } );

    /*
     The test scenario
     */

    casper.start( config.getServerUrl()+'inputfield.html' );

    casper.viewport( 1600, 1000 );

    //capture state
    casper.then( function () {
        phantomcss.screenshot( 'div .col-md-10', 'textfield_with_indicators_page');
    } );

    casper.then( function () {
        phantomcss.screenshot( '#standardExample', 'textfield_standard' );
    } );

    casper.then( function () {
        phantomcss.screenshot( '#entryChangedExample', 'textfield_entryChanged' );
    } );



    casper.then( function () {
        // casper.evaluate(function triggerKeyDownEvent() {
        //     var e = jQuery.Event("keydown");
        //     e.which = 65;
        //     e.keyCode = 65;
        //     jQuery('#Example1').trigger(e);
        //     return true;
        // });
        casper.sendKeys('#with-clear-button', 'clear', {keepFocus: true});
        // this.page.sendEvent("keypress", this.page.event.key.A);
        this.wait(1000,function(){
            phantomcss.screenshot( 'body', 'textfield_with_clear_button' );
        });
    } );


    casper.then( function () {
        casper.sendKeys('#with-clear-button', 'text', {keepFocus: true});
        casper.mouse.click('#with-clear-button + a');
        this.wait(1000,function(){
            phantomcss.screenshot( 'body', 'textfield_after_clear_button' );
        });
    } );

    casper.then( function now_check_the_screenshots() {
        // compare screenshots
        phantomcss.compareAll();
    } );
    /*
     Casper runs tests
     */
    casper.run( function () {
        console.log( '\nTHE END.' );
        // phantomcss.getExitStatus() // pass or fail?
        casper.test.done();
    } );
} );
Beispiel #4
0
 this.on('fail', function(failure) {
     this.exporter.addFailure(fs.absolute(failure.file), failure.message, failure.details || "test failed", failure.type || "unknown");
     this.testResults.failures.push(failure);
 });
Beispiel #5
0
var require = patchRequire(require),
    casperjs = require("casper").create(),
    utils = require("utils"),
    sys = require("system"),
    fs = require("fs"),
    helper,
    args,
    options,
    agent,
    isValid,
    buildAgentInstance;

//change to crawler working directory
fs.changeWorkingDirectory("/data"); 

helper = require(fs.absolute(".") + "/lib/utility");

/**
 * Create an instance of the fetcher from the passed in parameter.
 */
buildAgentInstance = function () {
    "user strict";
    var args = casperjs.cli.args,
        agentPath = fs.workingDirectory + "/agents/" + args[0] + "/" + args[1] + ".js", //fs.absolute(".") + "/agents/" + args[0] + "/" + args[1] + ".js",
        fn = require(agentPath);
    fn = new fn(null, casperjs);
    fn.url = args[2];

    return fn;
};
Beispiel #6
0
 phantom.casperPath = phantom.args.map(function _map(i) {
     var match = i.match(/^--casper-path=(.*)/);
     if (match) {
         return fs.absolute(match[1]);
     }
 }).filter(function _filter(path) {
Beispiel #7
0
 return entries.filter(function(entry) {
     return utils.isJsFile(fs.absolute(fs.pathJoin(dir, entry)));
 });
Beispiel #8
0
    module.getFileUrl = function (filePath) {
        var fs = require("fs");

        return "file://" + fs.absolute(filePath);
    };
var page = require('webpage').create();
var fs = require('fs');
var fileName = fs.absolute('./eventos-simulados-click.html');
console.log('rendering '+fileName)
//page.open('file:///D:/hecho/npm/pruebas_de_concepto/eventos/eventos-simulados-click.html', function() {
page.open('file:///'+fileName, function() {
  page.render(fileName+'.png');
  phantom.exit();
});
casper.test.begin( 'begin test baidu ', function ( test ) {

	phantomcss.init( {
		rebase: casper.cli.get( "rebase" ),
		// SlimerJS needs explicit knowledge of this Casper, and lots of absolute paths
		casper: casper,
		libraryRoot: fs.absolute( fs.workingDirectory + '' ),
		screenshotRoot: fs.absolute( fs.workingDirectory + '/screenshots' ),
		failedComparisonsRoot: fs.absolute( fs.workingDirectory + '/demo/failures' ),
		addLabelToFailedImage: false,
		/*
		screenshotRoot: '/screenshots',
		failedComparisonsRoot: '/failures'
		casper: specific_instance_of_casper,
		libraryRoot: '/phantomcss',
		fileNameGetter: function overide_file_naming(){},
		onPass: function passCallback(){},
		onFail: function failCallback(){},
		onTimeout: function timeoutCallback(){},
		onComplete: function completeCallback(){},
		hideElements: '#thing.selector',
		addLabelToFailedImage: true,
		outputSettings: {
			errorColor: {
				red: 255,
				green: 255,
				blue: 0
			},
			errorType: 'movement',
			transparency: 0.3
		}*/
	} );

	casper.on( 'remote.message', function ( msg ) {
		this.echo( msg );
	} );

	casper.on( 'error', function ( err ) {
		this.die( "PhantomJS has errored: " + err );
	} );

	casper.on( 'resource.error', function ( err ) {
		casper.log( 'Resource load error: ' + err, 'warning' );
	} );
	/*
		The test scenario
	*/

	casper.start( 'https://www.baidu.com' );
  casper.echo("test start");
	casper.viewport( 1024, 768 );
  casper.then(function() {
    this.sendKeys(' input#kw.s_ipt', 'casper');
});
	casper.then( function () {
		phantomcss.screenshot( 'input#kw', 'get the input text' );
	} );

	casper.then( function () {
		casper.click( 'input#su' );

		// wait for modal to fade-in
		casper.waitForSelector( '#help a.feedback',
			function success() {
				phantomcss.screenshot( '#content_left', 'result left' );
			},
			function timeout() {
				casper.test.fail( 'fail' );
			}
		);
	} );

	// casper.then( function () {
	// 	casper.click( '#cappuccino-button' );
	// 	phantomcss.screenshot( '#myModal', 'cappuccino success' );
	// } );
  //
	// casper.then( function () {
	// 	casper.click( '#close' );
  //
	// 	// wait for modal to fade-out
	// 	casper.waitForSelector( '#myModal[style*="display: none"]',
	// 		function success() {
	// 			phantomcss.screenshot( {
	// 				'Coffee machine close success': {
	// 					selector: '#coffee-machine-wrapper',
	// 					ignore: '.selector'
	// 				},
	// 				'Coffee machine button success': '#coffee-machine-button'
	// 			} );
	// 		},
	// 		function timeout() {
	// 			casper.test.fail( 'Should be able to walk away from the coffee machine' );
	// 		}
	// 	);
	// } );

	casper.then( function now_check_the_screenshots() {
		// compare screenshots
		phantomcss.compareAll();
	} );

	/*
	Casper runs tests
	*/
	casper.run( function () {
		console.log( '\nTHE END.' );
		// phantomcss.getExitStatus() // pass or fail?
		casper.test.done();
	} );
} );
Beispiel #11
0
	Runner.resolve = function(path) {
		if (fs && this.resultsfolder) {
			return fs.absolute(this.resultsfolder + '/' + path);
		}
		return path;
	}
function getFilePath(x) {
	return fs.absolute(path + list[x]); 
}
Beispiel #13
0
            var comparisonCount = page.evaluate(getComparisonCount);

            assertEquals(comparisonCount, 2, "number of comparisons");
            if (withNavigationFallback) {
                assertEquals(page.url, pageUrl, "page url");
            } else {
                assertMatches(page.url, /\?$/, "page url");
            }
        })
        .then(null, function (e) {
            page.render('smokeTestError.png');
            throw e;
        });
};

runTestAgainst('file://' + fs.absolute(csscriticLoadingPage), {withNavigationFallback: true})
    .then(function () {
        startWebserver(webserverPort);
        return runTestAgainst(
            'http://localhost:' + webserverPort + '/' + csscriticLoadingPage,
            {withNavigationFallback: false}
        );
    })
    .then(function () {
        console.log('Smoke test successful');
        phantom.exit();
    }, function (err) {
        console.error(err);
        phantom.exit(1);
    });
Beispiel #14
0
(function() {
	'use strict';

	var args = require('system').args,
		fs = require('fs');

	// arg[0]: scriptName, args[1...]: arguments
	if (args.length !== 2) {
		console.error('Usage:\n  phantomjs runner.js [url-of-your-qunit-testsuite]');
		phantom.exit(1);
	}

	var url = 'file://' + fs.absolute(args[1]),
		page = require('webpage').create();

	// Route `console.log()` calls from within the Page context to the main Phantom context (i.e. current `this`)
	page.onConsoleMessage = function(msg) {
		console.log(msg);
	};

	page.onInitialized = function() {
		page.evaluate(addLogging);
	};

	page.onCallback = function(message) {
		var result,
			failed;

		if (message) {
			if (message.name === 'QUnit.done') {
				result = message.data;
				failed = !result || result.failed;

				phantom.exit(failed ? 1 : 0);
			}
		}
	};

	page.open(url, function(status) {
		if (status !== 'success') {
			console.error('Unable to access network: ' + status);
			phantom.exit(1);
		} else {
			// Cannot do this verification with the 'DOMContentLoaded' handler because it
			// will be too late to attach it if a page does not have any script tags.
			var qunitMissing = page.evaluate(function() { return (typeof QUnit === 'undefined' || !QUnit); });
			if (qunitMissing) {
				console.error('The `QUnit` object is not present on this page.');
				phantom.exit(1);
			}

			// Do nothing... the callback mechanism will handle everything!
		}
	});

	function addLogging() {
		window.document.addEventListener('DOMContentLoaded', function() {
            // Ignore other browser windows like "about:blank", which may get opened too.
            if (typeof QUnit === 'undefined') {
                return;
            }

			var current_test_assertions = [];

			QUnit.log(function(details) {
				var response;

				// Ignore passing assertions
				if (details.result) {
					return;
				}

				response = details.message || '';

				if (typeof details.expected !== 'undefined') {
					if (response) {
						response += ', ';
					}

					response += 'expected: ' + details.expected + ', but was: ' + details.actual;
					if (details.source) {
						response += "\n" + details.source;
					}
				}

				current_test_assertions.push('Failed assertion: ' + response);
			});

			QUnit.testDone(function(result) {
				var i,
					len,
					name = result.module + ': ' + result.name;

				if (result.failed) {
					console.log('Test failed: ' + name);

					for (i = 0, len = current_test_assertions.length; i < len; i++) {
						console.log('    ' + current_test_assertions[i]);
					}
				}

				current_test_assertions.length = 0;
			});

			QUnit.done(function(result) {
				console.log('Took ' + result.runtime +  'ms to run ' + result.total + ' tests. ' + result.passed + ' passed, ' + result.failed + ' failed.');

				if (typeof window.callPhantom === 'function') {
					window.callPhantom({
						'name': 'QUnit.done',
						'data': result
					});
				}
			});
		}, false);
	}
})();
Beispiel #15
0
tests.push([function () {
    require.paths.push(fs.absolute(module.dirname + '/dir/subdir'));
    this.add_cleanup(function () { require.paths.pop(); });
    require_paths_tests_1();
}, "absolute paths in require.paths"]);
Beispiel #16
0
 this.getCacheDirectory = function() {
    return fs.absolute(directoryOrFile);
 };
    var getFileUrl = function (address) {
        var fs = require("fs");

        return address.indexOf("://") === -1 ? "file://" + fs.absolute(address) : address;
    };
Beispiel #18
0
function l(path) {
	if (casper.cli.options["local"] == true)
		return 'file://' + fs.absolute(path);
	else
		return path;
}
Beispiel #19
0
 }).map(function(entry) {
     return fs.absolute(fs.pathJoin(dir, entry));
 });
Beispiel #20
0
var currentFile = require('system').args[3];
var fs = require('fs');
var dirname = fs.absolute(currentFile).split('/');
// Needs to be loaded to be available across the lifecycle.
var utils = require('utils');
var system = require('system');
var pid = system.pid;

// Pass the PhantomJS pid to the runner
console.log('PhantomJS PID: ' + pid);

var opts, currentTask;

if (dirname.length > 1) {
    dirname.pop();
    dirname = dirname.join('/');
    fs.changeWorkingDirectory(dirname);
}

var casper = require('casper').create({
    clientScripts: ['./includes/start.js'],
    pageSettings: {
        loadImages: true,
        loadPlugins: true,
        localToRemoteUrlAccessEnabled: true
    },
    requests: {},
    verbose: false,
    exitOnError: false,
    // Overwrite logs to avoid having them in the console.
    onDie: function (casp, message, status) {
Beispiel #21
0
 this.on('success', function(success) {
     this.exporter.addSuccess(fs.absolute(success.file), success.message);
 });
Beispiel #22
0
 function (filename) {
   return fs.absolute('test' + fs.separator + filename);
 }
exports.testIsAbsolute = function () {
    assert.isTrue(fs.isAbsolute(java.lang.System.getProperty("java.home")));
    assert.isTrue(fs.isAbsolute(fs.absolute(module.path)));
    assert.isTrue(fs.isRelative("./"));
};
var fs = require('fs'); //Always required to read from files
var path = fs.absolute('.');
var system = require('system');
var args = system.args;

//Read files from filesystem
var expected = fs.read(path + '/blocklyeditor/tests/com/google/appinventor/blocklyeditor/data/factorial/factorialExpected.yail');
var formJson = fs.read(path + '/blocklyeditor/tests/com/google/appinventor/blocklyeditor/data/factorial/Screen1.scm');
formJson = formJson.substring(9, formJson.length-2); // Cut off Leading $JSON
var blocks = fs.read(path + '/blocklyeditor/tests/com/google/appinventor/blocklyeditor/data/factorial/Screen1.bky');

// PhantomJS page object to open and load an URL
var page = require('webpage').create();
// Some debugging from PhantomJS
page.onConsoleMessage = function (msg) { console.log(msg); };
page.onError = function (msg, trace) {
    console.log(msg);
    trace.forEach(function(item) {
        console.log('  ', item.file, ':', item.line);
    })
}

// Open the actual page and load all the JavaScript in it
// If success is true, all went well
debugger;
page.open('blocklyeditor/src/demos/yail/yail_testing_index.html', function(status) {
    // The evaluate function has arguments passed after the callback
    // We are passing in the .bky, .scm, and expected .yail

    if (status != 'success') {
        console.log('load unsuccessful');
casper.test.begin( 'login account sign-up  tests', function ( test ) {

    phantomcss.init( {
        rebase: casper.cli.get( "rebase" ),
        // SlimerJS needs explicit knowledge of this Casper, and lots of absolute paths
        casper: casper,
        libraryRoot: fs.absolute( fs.workingDirectory + '' ),
        screenshotRoot: fs.absolute( fs.workingDirectory + '/screenshots/login_account_sign-up' ),
        failedComparisonsRoot: fs.absolute( fs.workingDirectory + '/failures/login_account_sign-up' ),
        addLabelToFailedImage: false,
    } );

    casper.on( 'remote.message', function ( msg ) {
        this.echo( msg );
    } )

    casper.on( 'error', function ( err ) {
        this.die( "PhantomJS has errored: " + err );
    } );

    casper.on( 'resource.error', function ( err ) {
        casper.log( 'Resource load error: ' + err, 'warning' );
    } );

    /*
     The test scenario
     */

    casper.start( config.getServerUrl()+'example-login-signup.html' );

    casper.viewport( 1600, 1500 );

    // STATIC CAPTURES
    // ===============
    casper.then( function () {
        casper.mouse.click('#applicationLoginUsername');
        phantomcss.screenshot( '#applicationLoginUsername', 'loginaccountsignup_case28_3_1_step3');
    } );


    casper.then( function () {
        casper.mouse.move('#applicationLoginPassword');
        phantomcss.screenshot( '#applicationLoginPassword', 'loginaccountsignup_case28_3_2_step2');
    } );


    casper.then( function () {
        casper.mouse.click('#TA_login_forgetpassword');
        phantomcss.screenshot( '#TA_login_forgetpassword', 'loginaccountsignup_case28_3_3_step3');
    } );


    casper.then( function () {
        casper.sendKeys('#applicationLoginUsername', 'hello', {keepFocus: true});
        casper.sendKeys('#applicationLoginPassword', 'hello', {keepFocus: true});
        casper.mouse.move('#applicationLoginButton');
        phantomcss.screenshot( '#applicationLoginButton', 'loginaccountsignup_case28_3_4_step3');
    } );

   casper.then( function () {
        casper.mouse.move('#TA_login_signupbutton');
        phantomcss.screenshot( '#TA_login_signupbutton', 'loginaccountsignup_case28_3_5_step2');
    } );


    casper.then( function now_check_the_screenshots() {
        // compare screenshots
        phantomcss.compareAll();
    } );
    /*
     Casper runs tests
     */
    casper.run( function () {
        console.log( '\nTHE END.' );
        // phantomcss.getExitStatus() // pass or fail?
        casper.test.done();
    } );
} );
Beispiel #26
0
// Headless Script testing
// Reusable slimerjs/phantomjs script for running cljs.test tests

var p = require('webpage').create();
var fs = require('fs');
var sys = require('system');

var pagePath = fs.absolute("doo-index.html");

var scripts = "";

for (var i = 1; i < sys.args.length; i++) {
    scripts += '<script src="' + fs.absolute(sys.args[i]) + '"></script>';
}

var html = "<html><head><meta charset=\"UTF-8\">"
           + scripts
           + "</head><body></body></html>";

fs.write(pagePath, html, 'w');

function isSlimer() {
    return (typeof slimer !== 'undefined');
}

function exit(code) {
    if (isSlimer()) {
        slimer.exit(code);
    } else {
        phantom.exit(code);
    }
Beispiel #27
0
/**
 Created by grelin on 2016/5/9.
 Require and initialise PhantomCSS module
 Paths are relative to CasperJs directory
 **/

var fs = require( 'fs' );
var path = fs.absolute( fs.workingDirectory + '/phantomcss.js' );
var configPath = fs.absolute( fs.workingDirectory + '/config/config.js' );
var jQueryPath = fs.absolute( fs.workingDirectory + '/config/jquery.js' );
var phantomcss = require( path );
var config = require( configPath );
var jQuery = require( jQueryPath );

casper.test.begin( 'textfield  tests', function ( test ) {

    phantomcss.init( {
        rebase: casper.cli.get( "rebase" ),
        // SlimerJS needs explicit knowledge of this Casper, and lots of absolute paths
        casper: casper,
        libraryRoot: fs.absolute( fs.workingDirectory + '' ),
        screenshotRoot: fs.absolute( fs.workingDirectory + '/screenshots/textfield' ),
        failedComparisonsRoot: fs.absolute( fs.workingDirectory + '/failures/textfield' ),
        addLabelToFailedImage: false
    } );

    casper.on( 'remote.message', function ( msg ) {
        this.echo( msg );
    } );

    casper.on( 'error', function ( err ) {
Beispiel #28
0
server.listen(4000, function (request, response)
{
	var allowedContentTypes = [
		'application/json',
		'text/html',
		'text/plain'
	];

	var renderOptions = {
		pageSize: 'A4',
		orientation: 'portrait',
		margin: {left: '2.5cm', right: '2.5cm', top: '2.5cm', bottom: '1cm'},
		header: {height: '0.9cm', content: ''},
		footer: {height: '0.9cm', content: '<div style="text-align:center;"><small>%%pageNumber/%%totalPages</small></div>'}
	};

	var fileName = uuid.v4() + '.pdf';
	var filePath = fs.absolute('./temp_files/' + fileName);

	switch (request.method)
	{
		case 'GET':
			response.write('Skitsanos PDF Rendering API. POST Method only please');
			response.close();
			break;

		case 'POST':
			console.log('POST (' + request.headers['Content-Type'] + ')');
			console.log(JSON.stringify(request.headers));

			if (request.headers['Content-Type'] == undefined || request.headers['Content-Length'] == undefined)
			{
				console.log('ERR 500 - Content-Length or Content-Type is missing');
				response.statusCode = 500;
				response.write('Content-Length header is missing');
				response.close();
				break;
			}

			var contentType = request.headers['Content-Type'].indexOf(';') ? request.headers['Content-Type'].split(';')[0] : request.headers['Content-Type'];

			if (!allowedContentTypes.exists(contentType))
			{
				console.log('ERR 415 - Content-Type is incorrect: ' + contentType);
				response.statusCode = 415;
				response.write('Content-Type is not supported');
				response.close();
				break;
			}

			if (request.headers['Content-Type'].startsWith('application/json'))
			{
				console.log('\tgot application/json');

				try
				{
					var jsonConfig = JSON.parse(request.post);

					renderOptions.content = jsonConfig.content;
					renderOptions.orientation = jsonConfig.orientation != undefined ? jsonConfig.orientation : 'portrait';
					renderOptions.pageSize = jsonConfig.pageSize != undefined ? jsonConfig.pageSize : 'A4';
					renderOptions.margin = jsonConfig.margin != undefined ? jsonConfig.margin : {left: '2.5cm', right: '2.5cm', top: '2.5cm', bottom: '1cm'};
					renderOptions.header = jsonConfig.header != undefined ? jsonConfig.header : {height: '0.9cm', content: ''};
					renderOptions.footer = jsonConfig.footer != undefined ? jsonConfig.footer : {height: '0.9cm', content: '<div style="text-align:center;"><small>%%pageNumber/%%totalPages</small></div>'};
					console.log('\tparsed JSON object');

				} catch (e)
				{
					console.log(e);

					response.statusCode = 500;
					response.write(JSON.stringify(e));
					response.close();
				}
			}
			else
			{
				renderOptions.content = request.post;
			}

			//write temp html file on disk
			try
			{
				console.log('-- Writing HTML ...');
				fs.write(filePath + '.html', renderOptions.content, 'w');
				console.log('\t' + renderOptions.content.length + ' bytes in file');
			} catch (e)
			{
				console.log(e);

				response.statusCode = 500;
				response.write(JSON.stringify(e));
				response.close();
			}

			var page = new WebPage();
			page.paperSize = {
				format: renderOptions.pageSize,
				orientation: renderOptions.orientation,
				margin: renderOptions.margin,
				header: {
					height: renderOptions.header.height,
					contents: phantom.callback(function (pageNum, numPages)
					{
						if (renderOptions.header.content == '' || renderOptions.header.content == null || renderOptions.header.content == undefined)
						{
							return '';
						}
						else
						{
							var headerContent = renderOptions.header.content.replaceAll('%%pageNumber', pageNum);
							headerContent = headerContent.replaceAll('%%totalPages', numPages);
							return headerContent;
						}
					})
				},
				footer: {
					height: renderOptions.footer.height,
					contents: phantom.callback(function (pageNum, numPages)
					{
						if (renderOptions.footer.content == '' || renderOptions.footer.content == null || renderOptions.footer.content == undefined)
						{
							return '';
						}
						else
						{
							var footerContent = renderOptions.footer.content.replaceAll('%%pageNumber', pageNum);
							footerContent = footerContent.replaceAll('%%totalPages', numPages);
							return footerContent;
						}
					})
				}
			};

			//open temp html file and render it
			page.open('file://' + filePath + '.html', function (status)
			{
				console.log('Rendering HTML into PDF...');
				page.render(filePath);
				fs.remove(filePath + '.html');
				page.close();
				console.log('-- done: Page closed.');

				console.log('-- redirecting to http://pdfapi.skitsanos.com/get/' + fileName);
				response.writeHead(302, {'Location': 'http://pdfapi.skitsanos.com/get/' + fileName});
				response.close();
				console.log('OK')
			});
			break;
	}
});
Beispiel #29
0
 tests.forEach(function(test) {
     var testDir = fs.absolute(fs.dirname(test));
     if (fs.isDirectory(testDir) && fs.exists(fs.pathJoin(testDir, '.casper'))) {
         isCasperTest = true;
     }
 });
console.error = function () {
    require("system").stderr.write(Array.prototype.join.call(arguments, ' ') + '\n');
};

if (url === undefined) {
    console.error('Missing URL as argument');
    phantom.exit(1);
}

var whitelisted_urls = []
,   whitelisted_domains = ["www.w3.org"];

if (whitelist_source) {
    if (fs.exists(whitelist_source)) {
        var whitelist = require(fs.absolute(whitelist_source));
        whitelisted_domains.push.apply(whitelisted_domains, whitelist.domains);
        whitelisted_urls = whitelist.urls;
    } else {
        console.error("The whitelist file doesn't exist");
    }
}

var scheme = urllib.parse(url).protocol;
if (scheme !== 'http:' && scheme !== 'https:') {
    console.error('not allowed to load ' + url);
    phantom.exit(1);
}

var original_domain = urllib.parse(url).hostname;
var found = false;