-
Notifications
You must be signed in to change notification settings - Fork 104
/
imgkit.rb
223 lines (188 loc) · 5.79 KB
/
imgkit.rb
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
class IMGKit
KNOWN_FORMATS = [:jpg, :jpeg, :png]
class NoExecutableError < StandardError
def initialize
msg = "No wkhtmltoimage executable found at #{IMGKit.configuration.wkhtmltoimage}\n"
msg << ">> Install wkhtmltoimage by hand or try running `imgkit --install-wkhtmltoimage`"
super(msg)
end
end
class ImproperSourceError < StandardError
def initialize(msg)
super("Improper Source: #{msg}")
end
end
class CommandFailedError < RuntimeError
attr_reader :command, :stderr
def initialize(command, stderr)
@command = command
@stderr = stderr
super("Command failed: #{command}: #{stderr}")
end
end
class UnknownFormatError < StandardError
def initialize(format)
super("Unknown Format: #{format}")
end
end
attr_accessor :source, :stylesheets, :javascripts
attr_reader :options
def initialize(url_file_or_html, options = {})
@source = Source.new(url_file_or_html)
@stylesheets = []
@javascripts = []
@options = IMGKit.configuration.default_options.merge(options)
@options.merge! find_options_in_meta(url_file_or_html) unless source.url?
raise NoExecutableError.new unless File.exist?(IMGKit.configuration.wkhtmltoimage)
end
def command(output_file = nil)
args = [executable]
args += normalize_options(@options).to_a.flatten.compact
if @source.html?
args << '-' # Get HTML from stdin
else
args << @source.to_s
end
if output_file
args << output_file.to_s
else
args << '-' # Read IMG from stdout
end
args
end
def executable
default = IMGKit.configuration.wkhtmltoimage
return default if default !~ /^\// # its not a path, so nothing we can do
if File.exist?(default)
default
else
default.split('/').last
end
end
if Open3.respond_to? :capture3
def capture3(*opts)
Open3.capture3 *opts
end
else
# Lifted from ruby 1.9.2-p290 sources for ruby 1.8 compatibility
# and modified to work on 1.8
def capture3(*cmd, &block)
if Hash === cmd.last
opts = cmd.pop.dup
else
opts = {}
end
stdin_data = opts.delete(:stdin_data) || ''
binmode = opts.delete(:binmode)
Open3.popen3(*cmd) {|i, o, e|
if binmode
i.binmode
o.binmode
e.binmode
end
out_reader = Thread.new { o.read }
err_reader = Thread.new { e.read }
i.write stdin_data
i.close
[out_reader.value, err_reader.value]
}
end
end
def to_img(format = nil, path = nil)
append_stylesheets
append_javascripts
set_format(format)
opts = @source.html? ? {:stdin_data => @source.to_s} : {}
result, stderr = capture3(*(command(path) + [opts]))
result.force_encoding("ASCII-8BIT") if result.respond_to? :force_encoding
raise CommandFailedError.new(command.join(' '), stderr) if path.nil? and result.size == 0
result
end
def to_file(path)
format = File.extname(path).gsub(/^\./,'').to_sym
self.to_img(format, path)
File.new(path)
end
def method_missing(name, *args, &block)
if(m = name.to_s.match(/^to_(\w+)/))
self.send(:to_img, m[1].to_sym)
else
super
end
end
protected
def find_options_in_meta(body)
imgkit_meta_tags(body).inject({}) do |found, tag|
name = tag.attributes["name"].sub(/^#{IMGKit.configuration.meta_tag_prefix}/, '').to_sym
found.merge(name => tag.attributes["content"])
end
end
def imgkit_meta_tags(body)
require 'rexml/document'
xml_body = REXML::Document.new(body)
found = []
xml_body.elements.each("html/head/meta") do |tag|
found << tag if tag.attributes['name'].to_s =~ /^#{IMGKit.configuration.meta_tag_prefix}/
end
found
rescue # rexml random crash on invalid xml
[]
end
def style_tag_for(stylesheet)
"<style>#{stylesheet.respond_to?(:read) ? stylesheet.read : File.read(stylesheet)}</style>"
end
def script_tag_for(javascript)
if javascript.respond_to?(:read)
"<script>#{javascript.read}</script>"
else
"<script src=\"#{javascript}\" type=\"text/javascript\"></script>"
end
end
def append_stylesheets
raise ImproperSourceError.new('Stylesheets may only be added to an HTML source') if stylesheets.any? && [email protected]?
stylesheets.each do |stylesheet|
if @source.to_s.match(/<\/head>/)
@source.to_s.gsub!(/(<\/head>)/, style_tag_for(stylesheet)+'\1')
else
@source.to_s.insert(0, style_tag_for(stylesheet))
end
end
end
def append_javascripts
raise ImproperSourceError.new('Javascripts may only be added to an HTML source') if javascripts.any? && [email protected]?
javascripts.each do |javascript|
if @source.to_s.match(/<\/head>/)
@source.to_s.gsub!(/(<\/head>)/, script_tag_for(javascript)+'\1')
else
@source.to_s.insert(0, script_tag_for(javascript))
end
end
end
def normalize_options(options)
normalized_options = {}
options.each do |key, value|
next if !value
normalized_key = "--#{normalize_arg key}"
normalized_options[normalized_key] = normalize_value(value)
end
normalized_options
end
def normalize_arg(arg)
arg.to_s.downcase.gsub(/[^a-z0-9]/,'-')
end
def normalize_value(value)
case value
when TrueClass
nil
when Array
value
else
value.to_s
end
end
def set_format(format)
format = IMGKit.configuration.default_format unless format
@options.merge!(:format => format.to_s) unless @options[:format]
raise UnknownFormatError.new(format) unless KNOWN_FORMATS.include?(@options[:format].to_sym)
end
end