From 956a16b8479ba38888b965d615c8f099802d5fc0 Mon Sep 17 00:00:00 2001 From: Mikhail Grachev Date: Mon, 10 Aug 2015 18:40:49 +0300 Subject: [PATCH] Stop PhantomJS if a site unavailable --- lib/gastly/screenshot.rb | 6 +++++- lib/gastly/script.js | 43 ++++++++++++++++++++++------------------ lib/gastly/version.rb | 2 +- 3 files changed, 30 insertions(+), 21 deletions(-) diff --git a/lib/gastly/screenshot.rb b/lib/gastly/screenshot.rb index f1e29ed..2257d5e 100644 --- a/lib/gastly/screenshot.rb +++ b/lib/gastly/screenshot.rb @@ -5,6 +5,8 @@ module Gastly class Screenshot + FetchError = Class.new(StandardError) + SCRIPT_PATH = File.expand_path('../script.js', __FILE__) DEFAULT_TIMEOUT = 0 DEFAULT_BROWSER_WIDTH = 1440 @@ -53,7 +55,9 @@ def capture Phantomjs.proxy_host = proxy_host if proxy_host Phantomjs.proxy_port = proxy_port if proxy_port - Phantomjs.run(proxy_options, SCRIPT_PATH.to_s, *prepared_params) + output = Phantomjs.run(proxy_options, SCRIPT_PATH.to_s, *prepared_params) + + raise FetchError, output if output.present? Gastly::Image.new(tempfile) end diff --git a/lib/gastly/script.js b/lib/gastly/script.js index cedfe14..dc574a0 100644 --- a/lib/gastly/script.js +++ b/lib/gastly/script.js @@ -39,24 +39,29 @@ if (args.cookies !== undefined){ } } -page.open(args.url, function(){ - window.setTimeout(function(){ - page.viewportSize = { width: args.width, height: args.height }; - - if (args.selector !== undefined){ - var clipRect = page.evaluate(function(s){ - return document.querySelector(s).getBoundingClientRect(); - }, args.selector); - - page.clipRect = { - top: clipRect.top, - left: clipRect.left, - width: clipRect.width, - height: clipRect.height - }; - } - - page.render(args.output); +page.open(args.url, function(status){ + if(status !== 'success') { + console.log('Unable to load: ' + args.url); phantom.exit(); - }, args.timeout); + } else { + window.setTimeout(function(){ + page.viewportSize = { width: args.width, height: args.height }; + + if (args.selector !== undefined){ + var clipRect = page.evaluate(function(s){ + return document.querySelector(s).getBoundingClientRect(); + }, args.selector); + + page.clipRect = { + top: clipRect.top, + left: clipRect.left, + width: clipRect.width, + height: clipRect.height + }; + } + + page.render(args.output); + phantom.exit(); + }, args.timeout); + } }); \ No newline at end of file diff --git a/lib/gastly/version.rb b/lib/gastly/version.rb index 205fe30..1707c4d 100644 --- a/lib/gastly/version.rb +++ b/lib/gastly/version.rb @@ -1,3 +1,3 @@ module Gastly - VERSION = '0.2.0' + VERSION = '0.2.1' end \ No newline at end of file