thumbshooter 0.1.2

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of thumbshooter might be problematic. Click here for more details.

data/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ Copyright (c) 2009 Julian Kornberger
2
+
3
+ This program is free software; you can redistribute it and/or
4
+ modify it under the terms of the GNU General Public License
5
+ as published by the Free Software Foundation; either version 2
6
+ of the License, or (at your option) any later version.
7
+
8
+ This program is distributed in the hope that it will be useful,
9
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
10
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
+ GNU General Public License for more details.
12
+
13
+ You should have received a copy of the GNU General Public License
14
+ along with this program; if not, write to the Free Software
15
+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
data/README.md ADDED
@@ -0,0 +1,35 @@
1
+ Thumbshooter
2
+ ============
3
+
4
+ Generates thumbshots of URLs by using webkit und python.
5
+
6
+
7
+ Requirements
8
+ ============
9
+
10
+ Please ensure python-qt4 and qt4-webkit is installed.
11
+
12
+ apt-get install libqt4-webkit python-qt4
13
+
14
+ You do also need a running x server. You can use a lightweight
15
+ x server by doing "apt-get install xvfb" and enabling it:
16
+
17
+ Thumbshooter.use_xvfb = true
18
+
19
+ Example
20
+ =======
21
+
22
+ shooter = Thumbshooter.new(
23
+ :screen => '800x600',
24
+ :resize => '200x150'
25
+ )
26
+
27
+ # generate thumbnail
28
+ img = shooter.create('http://github.com/')
29
+
30
+ # write thumbnail to file
31
+ File.open('thumbshot.png', 'w') {|f| f.write(img) }
32
+
33
+
34
+
35
+ Copyright (c) 2009 Julian Kornberger, released under the GNU license
data/Rakefile ADDED
@@ -0,0 +1,23 @@
1
+ require 'rake'
2
+ require 'rake/testtask'
3
+ require 'rake/rdoctask'
4
+
5
+ desc 'Default: run unit tests.'
6
+ task :default => :test
7
+
8
+ desc 'Test the thumbshot plugin.'
9
+ Rake::TestTask.new(:test) do |t|
10
+ t.libs << 'lib'
11
+ t.libs << 'test'
12
+ t.pattern = 'test/**/*_test.rb'
13
+ t.verbose = true
14
+ end
15
+
16
+ desc 'Generate documentation for the thumbshot plugin.'
17
+ Rake::RDocTask.new(:rdoc) do |rdoc|
18
+ rdoc.rdoc_dir = 'rdoc'
19
+ rdoc.title = 'Thumbshot'
20
+ rdoc.options << '--line-numbers' << '--inline-source'
21
+ rdoc.rdoc_files.include('README')
22
+ rdoc.rdoc_files.include('lib/**/*.rb')
23
+ end
data/init.rb ADDED
@@ -0,0 +1,14 @@
1
+ # load ImageMagick
2
+ unless defined?(Magick)
3
+ # load RubyGems
4
+ require 'rubygems'
5
+
6
+ # load RMagick
7
+ gem "rmagick"
8
+ require 'RMagick'
9
+ end
10
+
11
+ require "tempfile"
12
+
13
+ # load classes
14
+ require File.dirname(__FILE__) + '/lib/thumbshooter'
@@ -0,0 +1,85 @@
1
+ #
2
+ # Binding for webkit2png
3
+ #
4
+ class Thumbshooter
5
+
6
+ # use X window virtual framebuffer?
7
+ cattr_accessor :use_xvfb
8
+
9
+ WEBKIT2PNG = File.dirname(__FILE__) + '/webkit2png.py'
10
+
11
+ #
12
+ # screen: dimension of the view part (w * h) i.e. 800x800
13
+ # resize: resize thumbshot (w * h) i.e. 160x160
14
+ # format: png (any others?)
15
+ # timeout: timeout for the page to load
16
+ def initialize(options={})
17
+ @args = ''
18
+ for key,value in options
19
+ next if value.nil?
20
+ case key
21
+ when :screen
22
+ # 123x124 (width x height)
23
+ raise ArgumentError, "invalid value for #{key}: #{value}" unless value =~ /^\d+x\d+$/
24
+ @args << " --geometry=" + value.sub('x',' ')
25
+ when :timeout
26
+ @args << " --timeout=#{value}"
27
+ when :format
28
+ @args << " --#{key}=#{value}"
29
+ when :resize
30
+ raise ArgumentError, "invalid value for #{key}: #{value}" unless value =~ /^\d+x\d+$/
31
+ @resize = value
32
+ else
33
+ raise ArgumentError, "unknown option: #{key}"
34
+ end
35
+ end
36
+ end
37
+
38
+ # creates a thumbshot
39
+ # returns it if no output-path given
40
+ def create(url, output=nil)
41
+ args = @args
42
+ args << "--output=#{output}" if output
43
+
44
+ # execute webkit2png-script and save stdout
45
+ command = ''
46
+ command << 'xvfb-run --server-args="-screen 0, 640x480x24" ' if use_xvfb
47
+ command << "#{WEBKIT2PNG} '#{url}' #{args}"
48
+
49
+ img = `#{command}`
50
+ status = $?.to_i
51
+ if status != 0
52
+ raise "webkitpng failed with status #{status}: #{img}"
53
+ end
54
+
55
+ if @resize
56
+ width,height = @resize.split("x")
57
+ img = resize(img,width,height)
58
+ end
59
+
60
+ img
61
+ end
62
+
63
+ # creates a thumb from direct html using a temporary file
64
+ def create_by_html(html)
65
+ tmp_file = Tempfile.new('thumbshot')
66
+ tmp_file.write(html)
67
+ tmp_file.close
68
+
69
+ begin
70
+ create(tmp_file.path)
71
+ ensure
72
+ #tmp_file.close!
73
+ end
74
+ end
75
+
76
+ protected
77
+
78
+ # resizes the image using RMagick
79
+ def resize(image_data, width, height)
80
+ img = Magick::Image.from_blob(image_data)[0]
81
+ img.resize!(width.to_i,height.to_i)
82
+ img.to_blob
83
+ end
84
+
85
+ end
data/lib/webkit2png.py ADDED
@@ -0,0 +1,210 @@
1
+ #!/usr/bin/env python
2
+ #
3
+ # webkit2png.py
4
+ #
5
+ # Creates screenshots of webpages using by QtWebkit.
6
+ #
7
+ # Copyright (c) 2008 Roland Tapken <roland@dau-sicher.de>
8
+ #
9
+ # This program is free software; you can redistribute it and/or
10
+ # modify it under the terms of the GNU General Public License
11
+ # as published by the Free Software Foundation; either version 2
12
+ # of the License, or (at your option) any later version.
13
+ #
14
+ # This program is distributed in the hope that it will be useful,
15
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
16
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17
+ # GNU General Public License for more details.
18
+ #
19
+ # You should have received a copy of the GNU General Public License
20
+ # along with this program; if not, write to the Free Software
21
+ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
22
+
23
+ import sys
24
+ import signal
25
+ import os
26
+ import logging
27
+ import time
28
+
29
+ from optparse import OptionParser
30
+
31
+ from PyQt4.QtCore import *
32
+ from PyQt4.QtGui import *
33
+ from PyQt4.QtWebKit import QWebPage
34
+
35
+ # Class for Website-Rendering. Uses QWebPage, which
36
+ # requires a running QtGui to work.
37
+ class WebkitRenderer(QObject):
38
+
39
+ # Initializes the QWebPage object and registers some slots
40
+ def __init__(self):
41
+ logging.debug("Initializing class %s", self.__class__.__name__)
42
+ self._page = QWebPage()
43
+ self.connect(self._page, SIGNAL("loadFinished(bool)"), self.__on_load_finished)
44
+ self.connect(self._page, SIGNAL("loadStarted()"), self.__on_load_started)
45
+
46
+ # The way we will use this, it seems to be unesseccary to have Scrollbars enabled
47
+ self._page.mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff)
48
+ self._page.mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff)
49
+
50
+ # Helper for multithreaded communication through signals
51
+ self.__loading = False
52
+ self.__loading_result = False
53
+
54
+ # Loads "url" and renders it.
55
+ # Returns QImage-object on success.
56
+ def render(self, url, width=0, height=0, timeout=0):
57
+ logging.debug("render(%s, timeout=%d)", url, timeout)
58
+
59
+ # This is an event-based application. So we have to wait until
60
+ # "loadFinished(bool)" raised.
61
+ cancelAt = time.time() + timeout
62
+ self._page.mainFrame().load(QUrl(url))
63
+ while self.__loading:
64
+ if timeout > 0 and time.time() >= cancelAt:
65
+ raise RuntimeError("Request timed out")
66
+ QCoreApplication.processEvents()
67
+
68
+ logging.debug("Processing result")
69
+
70
+ if self.__loading_result == False:
71
+ raise RuntimeError("Failed to load %s" % url)
72
+
73
+ # Set initial viewport (the size of the "window")
74
+ size = self._page.mainFrame().contentsSize()
75
+ if width > 0:
76
+ size.setWidth(width)
77
+ if height > 0:
78
+ size.setHeight(height)
79
+ self._page.setViewportSize(size)
80
+
81
+ # Paint this frame into an image
82
+ image = QImage(self._page.viewportSize(), QImage.Format_ARGB32)
83
+ painter = QPainter(image)
84
+ self._page.mainFrame().render(painter)
85
+ painter.end()
86
+
87
+ return image
88
+
89
+
90
+ # Eventhandler for "loadStarted()" signal
91
+ def __on_load_started(self):
92
+ logging.debug("loading started")
93
+ self.__loading = True
94
+
95
+ # Eventhandler for "loadFinished(bool)" signal
96
+ def __on_load_finished(self, result):
97
+ logging.debug("loading finished with result %s", result)
98
+ self.__loading = False
99
+ self.__loading_result = result
100
+
101
+
102
+ if __name__ == '__main__':
103
+ # Parse command line arguments.
104
+ # Syntax:
105
+ # $0 [--xvfb|--display=DISPLAY] [--debug] [--output=FILENAME] <URL>
106
+ qtargs = [sys.argv[0]]
107
+
108
+ description = "Creates a screenshot of a website using QtWebkit." \
109
+ + "This program comes with ABSOLUTELY NO WARRANTY. " \
110
+ + "This is free software, and you are welcome to redistribute " \
111
+ + "it under the terms of the GNU General Public License v2."
112
+
113
+ parser = OptionParser(usage="usage: %prog [options] <URL>",
114
+ version="%prog 0.1, Copyright (c) 2008 Roland Tapken",
115
+ description=description)
116
+ parser.add_option("-x", "--xvfb", action="store_true", dest="xvfb",
117
+ help="Start an 'xvfb' instance.", default=False)
118
+ parser.add_option("-g", "--geometry", dest="geometry", nargs=2, default=(0, 0), type="int",
119
+ help="Geometry of the virtual browser window (0 means 'autodetect') [default: %default].", metavar="WIDTH HEIGHT")
120
+ parser.add_option("-o", "--output", dest="output",
121
+ help="Write output to FILE instead of STDOUT.", metavar="FILE")
122
+ parser.add_option("-f", "--format", dest="format", default="png",
123
+ help="Output image format [default: %default]", metavar="FORMAT")
124
+ parser.add_option("--scale", dest="scale", nargs=2, type="int",
125
+ help="Scale the image to this size", metavar="WIDTH HEIGHT")
126
+ parser.add_option("--aspect-ratio", dest="ratio", type="choice", choices=["ignore", "keep", "expand"],
127
+ help="One of 'ignore', 'keep' or 'expand' [default: %default]")
128
+ parser.add_option("-t", "--timeout", dest="timeout", default=0, type="int",
129
+ help="Time before the request will be canceled [default: %default]", metavar="SECONDS")
130
+ parser.add_option("-d", "--display", dest="display",
131
+ help="Connect to X server at DISPLAY.", metavar="DISPLAY")
132
+ parser.add_option("--debug", action="store_true", dest="debug",
133
+ help="Show debugging information.", default=False)
134
+
135
+ # Parse command line arguments and validate them (as far as we can)
136
+ (options,args) = parser.parse_args()
137
+ if len(args) != 1:
138
+ parser.error("incorrect number of arguments")
139
+ if options.display and options.xvfb:
140
+ parser.error("options -x and -d are mutually exclusive")
141
+ options.url = args[0]
142
+
143
+ # Enable output of debugging information
144
+ if options.debug:
145
+ logging.basicConfig(level=logging.DEBUG)
146
+
147
+ # Add display information for qt (you may also use the environment var DISPLAY)
148
+ if options.display:
149
+ qtargs.append("-display")
150
+ qtargs.append(options.display)
151
+
152
+ if options.xvfb:
153
+ # Start 'xvfb' instance by replacing the current process
154
+ newArgs = ["xvfb-run", "--server-args=-screen 0, 640x480x24", sys.argv[0]]
155
+ for i in range(1, len(sys.argv)):
156
+ if sys.argv[i] not in ["-x", "--xvfb"]:
157
+ newArgs.append(sys.argv[i])
158
+ logging.debug("Executing %s" % " ".join(newArgs))
159
+ os.execvp(newArgs[0], newArgs)
160
+ raise RuntimeError("Failed to execute '%s'" % newArgs[0])
161
+
162
+ # Prepare outout ("1" means STDOUT)
163
+ if options.output == None:
164
+ qfile = QFile()
165
+ qfile.open(1, QIODevice.WriteOnly)
166
+ options.output = qfile
167
+
168
+ # Initialize Qt-Application, but make this script
169
+ # abortable via CTRL-C
170
+ app = QApplication(qtargs)
171
+ signal.signal(signal.SIGINT, signal.SIG_DFL)
172
+
173
+ # Initialize WebkitRenderer object
174
+ renderer = WebkitRenderer()
175
+
176
+ # Technically, this is a QtGui application, because QWebPage requires it
177
+ # to be. But because we will have no user interaction, and rendering can
178
+ # not start before 'app.exec_()' is called, we have to trigger our "main"
179
+ # by a timer event.
180
+ def __on_exec():
181
+ # Render the page.
182
+ # If this method times out or loading failed, a
183
+ # RuntimeException is thrown
184
+ try:
185
+ image = renderer.render(options.url,
186
+ width=options.geometry[0],
187
+ height=options.geometry[1],
188
+ timeout=options.timeout)
189
+
190
+ if options.scale:
191
+ # Scale this image
192
+ if options.ratio == 'keep':
193
+ ratio = Qt.KeepAspectRatio
194
+ elif options.ratio == 'expand':
195
+ ratio = Qt.KeepAspectRatioByExpanding
196
+ else:
197
+ ratio = Qt.IgnoreAspectRatio
198
+ image = image.scaled(options.scale[0], options.scale[1], ratio)
199
+
200
+ image.save(options.output, options.format)
201
+ if isinstance(options.output, QFile):
202
+ options.output.close()
203
+ sys.exit(0)
204
+ except RuntimeError, e:
205
+ logging.error(e.msg)
206
+ sys.exit(1)
207
+
208
+ # Go to main loop (required)
209
+ QTimer().singleShot(0, __on_exec)
210
+ sys.exit(app.exec_())
data/rails/init.rb ADDED
@@ -0,0 +1 @@
1
+ require File.join(File.dirname(__FILE__), "..", "init")
metadata ADDED
@@ -0,0 +1,72 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: thumbshooter
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.2
5
+ platform: ruby
6
+ authors:
7
+ - Julian Kornberger
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+
12
+ date: 2009-10-07 00:00:00 +02:00
13
+ default_executable:
14
+ dependencies:
15
+ - !ruby/object:Gem::Dependency
16
+ name: rmagick
17
+ type: :runtime
18
+ version_requirement:
19
+ version_requirements: !ruby/object:Gem::Requirement
20
+ requirements:
21
+ - - ">="
22
+ - !ruby/object:Gem::Version
23
+ version: "2"
24
+ version:
25
+ description: Thumbshooter creates thumbshots of websites using webkit, qt4 and python.
26
+ email: kontakt@digineo.de
27
+ executables: []
28
+
29
+ extensions: []
30
+
31
+ extra_rdoc_files:
32
+ - README.md
33
+ - LICENSE
34
+ files:
35
+ - init.rb
36
+ - Rakefile
37
+ - LICENSE
38
+ - README.md
39
+ - lib/thumbshooter.rb
40
+ - lib/webkit2png.py
41
+ - rails/init.rb
42
+ has_rdoc: true
43
+ homepage: http://github.com/digineo/thumbshooter
44
+ licenses: []
45
+
46
+ post_install_message:
47
+ rdoc_options:
48
+ - --inline-source
49
+ - --charset=UTF-8
50
+ require_paths:
51
+ - lib
52
+ required_ruby_version: !ruby/object:Gem::Requirement
53
+ requirements:
54
+ - - ">="
55
+ - !ruby/object:Gem::Version
56
+ version: "0"
57
+ version:
58
+ required_rubygems_version: !ruby/object:Gem::Requirement
59
+ requirements:
60
+ - - ">="
61
+ - !ruby/object:Gem::Version
62
+ version: "0"
63
+ version:
64
+ requirements:
65
+ - :"rmagick libqt4-webkit python-qt4"
66
+ rubyforge_project:
67
+ rubygems_version: 1.3.5
68
+ signing_key:
69
+ specification_version: 3
70
+ summary: Generator for thumbshots of websites.
71
+ test_files: []
72
+