grabzit 2.0.2 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 8c1f8325faed3eb54783d7606af82d2843ce2812
4
+ data.tar.gz: 7aad48f65edf2c38d507bcba3c73153c09c99d81
5
+ SHA512:
6
+ metadata.gz: e9a91502e7fac4ce457d4d1d899b8f09171e83ae2bcd9d967c0d40a492b015a9cfea80c8f63ece046fa0ffce1c5c5b0255c2c93dc7adce8fcb771d94ee53c9fe
7
+ data.tar.gz: 020092c3a5afa7edc4daf22eee553533d75fd1c685aa24bbb133cb91c2ae0d455b995c5254a347f0fa5764645c53291ef7f42b626507bdad0ba7c9e174de482a
@@ -1,443 +1,513 @@
1
- # The public REST API for http://grabz.it
2
- # @example To include the GrabzIt module do the following
3
- # require 'grabzit'
4
- module GrabzIt
5
- require 'digest/md5'
6
- require 'net/http'
7
- require 'rexml/document'
8
- require 'cgi'
9
- require 'uri'
10
- require File.join(File.dirname(__FILE__), 'screenshotstatus')
11
- require File.join(File.dirname(__FILE__), 'cookie')
12
- require File.join(File.dirname(__FILE__), 'watermark')
13
-
14
- # This client provides access to the GrabzIt web services
15
- # This API allows you to take screenshot of websites for free and convert them into images, PDF's and tables.
16
- # @example Example usage
17
- # require 'grabzit'
18
- #
19
- # grabzItClient = GrabzIt::Client.new("YOUR APPLICATION KEY", "YOUR APPLICATION SECRET")
20
- # grabzItClient.set_image_options("http://www.google.com")
21
- # grabzItClient.save("http://www.mysite.com/grabzit/handler")
22
- # @version 2.0
23
- # @author GrabzIt
24
- # @see http://grabz.it/api/ruby/ GrabzIt Ruby API
25
- class Client
26
-
27
- WebServicesBaseURL = "http://grabz.it/services/"
28
- private_constant :WebServicesBaseURL
29
- TrueString = "True"
30
- private_constant :TrueString
31
-
32
- @@signaturePartOne;
33
- @@signaturePartTwo;
34
- @@request;
35
-
36
- # Create a new instance of the Client class in order to access the GrabzIt API.
37
- # @param applicationKey [String] your application key
38
- # @param applicationSecret [String] your application secret
39
- # @see http://grabz.it/register.aspx You can get an application key and secret by registering for free with GrabzIt
40
- def initialize(applicationKey, applicationSecret)
41
- @applicationKey = applicationKey
42
- @applicationSecret = applicationSecret
43
- end
44
-
45
- # Sets the parameters required to take a screenshot of a web page.
46
- # @param url [String] the URL that the screenshot should be made of
47
- # @param customId [String, nil] custom identifier that you can pass through to the screenshot webservice. This will be returned with the callback URL you have specified.
48
- # @param browserWidth [Integer, nil] the width of the browser in pixels
49
- # @param browserHeight [Integer, nil] the height of the browser in pixels
50
- # @param width [Integer, nil] the width of the resulting thumbnail in pixels
51
- # @param height [Integer, nil] the height of the resulting thumbnail in pixels
52
- # @param format [String, nil] the format the screenshot should be in: bmp8, bmp16, bmp24, bmp, gif, jpg, png
53
- # @param delay [Integer, nil] the number of milliseconds to wait before taking the screenshot
54
- # @param targetElement [String, nil] the id of the only HTML element in the web page to turn into a screenshot
55
- # @param requestMobileVersion [Boolean, false] request a mobile version of the target website if possible
56
- # @param customWaterMarkId [String, nil] add a custom watermark to the image
57
- # @return [void]
58
- def set_image_options(url, customId = nil, browserWidth = nil, browserHeight = nil, width = nil, height = nil, format = nil, delay = nil, targetElement = nil, requestMobileVersion = false, customWaterMarkId = nil)
59
- @@request = WebServicesBaseURL + "takepicture.ashx?key="+CGI.escape(nil_check(@applicationKey))+"&url="+CGI.escape(nil_check(url))+"&width="+nil_int_check(width)+"&height="+nil_int_check(height)+"&format="+CGI.escape(nil_check(format))+"&bwidth="+nil_int_check(browserWidth)+"&bheight="+nil_int_check(browserHeight)+"&customid="+CGI.escape(nil_check(customId))+"&delay="+nil_int_check(delay)+"&target="+CGI.escape(nil_check(targetElement))+"&customwatermarkid="+CGI.escape(nil_check(customWaterMarkId))+"&requestmobileversion="+b_to_str(requestMobileVersion)+"&callback="
60
- @@signaturePartOne = nil_check(@applicationSecret)+"|"+nil_check(url)+"|"
61
- @@signaturePartTwo = "|"+nil_check(format)+"|"+nil_int_check(height)+"|"+nil_int_check(width)+"|"+nil_int_check(browserHeight)+"|"+nil_int_check(browserWidth)+"|"+nil_check(customId)+"|"+nil_int_check(delay)+"|"+nil_check(targetElement)+"|"+nil_check(customWaterMarkId)+"|"+b_to_str(requestMobileVersion)
62
-
63
- return nil
64
- end
65
-
66
- # Sets the parameters required to extract one or more tables from a web page.
67
- # @param url [String] the URL that the should be used to extract tables
68
- # @param customId [String, nil] a custom identifier that you can pass through to the webservice. This will be returned with the callback URL you have specified.
69
- # @param tableNumberToInclude [Integer, 1] the index of the table to be converted, were all tables in a web page are ordered from the top of the web page to bottom
70
- # @param format [String, 'csv'] the format the table should be in: csv, xlsx
71
- # @param includeHeaderNames [Boolean, true] if true header names will be included in the table
72
- # @param includeAllTables [Boolean, true] if true all table on the web page will be extracted with each table appearing in a seperate spreadsheet sheet. Only available with the XLSX format.
73
- # @param targetElement [String, nil] the id of the only HTML element in the web page that should be used to extract tables from
74
- # @param requestMobileVersion [Boolean, false] request a mobile version of the target website if possible
75
- # @return [void]
76
- def set_table_options(url, customId = nil, tableNumberToInclude = 1, format = 'csv', includeHeaderNames = true, includeAllTables = false, targetElement = nil, requestMobileVersion = false)
77
- @@request = WebServicesBaseURL + "taketable.ashx?key=" + CGI.escape(nil_check(@applicationKey))+"&url="+CGI.escape(url)+"&includeAllTables="+b_to_str(includeAllTables)+"&includeHeaderNames="+b_to_str(includeHeaderNames)+"&format="+CGI.escape(nil_check(format))+"&tableToInclude="+nil_int_check(tableNumberToInclude)+"&customid="+CGI.escape(nil_check(customId))+"&target="+CGI.escape(nil_check(targetElement))+"&requestmobileversion="+b_to_str(requestMobileVersion)+"&callback="
78
- @@signaturePartOne = nil_check(@applicationSecret)+"|"+nil_check(url)+"|"
79
- @@signaturePartTwo = "|"+nil_check(customId)+"|"+nil_int_check(tableNumberToInclude)+"|"+b_to_str(includeAllTables)+"|"+b_to_str(includeHeaderNames)+"|"+nil_check(targetElement)+"|"+nil_check(format)+"|"+b_to_str(requestMobileVersion)
80
-
81
- return nil
82
- end
83
-
84
- # Sets the parameters required to convert a web page into a PDF.
85
- # @param url url [String] the URL that the should be converted into a pdf
86
- # @param customId [String, nil] a custom identifier that you can pass through to the webservice. This will be returned with the callback URL you have specified.
87
- # @param includeBackground [Boolean, true] if true the background of the web page should be included in the screenshot
88
- # @param pagesize [String, 'A4'] the page size of the PDF to be returned: 'A3', 'A4', 'A5', 'B3', 'B4', 'B5'.
89
- # @param orientation [String, 'Portrait'] the orientation of the PDF to be returned: 'Landscape' or 'Portrait'
90
- # @param includeLinks [Boolean, true] true if links should be included in the PDF
91
- # @param includeOutline [Boolean, false] True if the PDF outline should be included
92
- # @param title [String, nil] provide a title to the PDF document
93
- # @param coverURL [String, nil] the URL of a web page that should be used as a cover page for the PDF
94
- # @param marginTop [Integer, 10] the margin that should appear at the top of the PDF document page
95
- # @param marginLeft [Integer, 10] the margin that should appear at the left of the PDF document page
96
- # @param marginBottom [Integer, 10] the margin that should appear at the bottom of the PDF document page
97
- # @param marginRight [Integer, 10] the margin that should appear at the right of the PDF document
98
- # @param delay [Integer, nil] the number of milliseconds to wait before taking the screenshot
99
- # @param requestMobileVersion [Boolean, false] request a mobile version of the target website if possible
100
- # @param customWaterMarkId [String, nil] add a custom watermark to each page of the PDF document
101
- # @return [void]
102
- def set_pdf_options(url, customId = nil, includeBackground = true, pagesize = 'A4', orientation = 'Portrait', includeLinks = true, includeOutline = false, title = nil, coverURL = nil, marginTop = 10, marginLeft = 10, marginBottom = 10, marginRight = 10, delay = nil, requestMobileVersion = false, customWaterMarkId = nil)
103
- pagesize = nil_check(pagesize).upcase
104
- $orientation = nil_check(orientation).capitalize
105
-
106
- @@request = WebServicesBaseURL + "takepdf.ashx?key=" + CGI.escape(nil_check(@applicationKey))+"&url="+CGI.escape(nil_check(url))+"&background="+b_to_str(includeBackground)+"&pagesize="+pagesize+"&orientation="+orientation+"&customid="+CGI.escape(nil_check(customId))+"&customwatermarkid="+CGI.escape(nil_check(customWaterMarkId))+"&includelinks="+b_to_str(includeLinks)+"&includeoutline="+b_to_str(includeOutline)+"&title="+CGI.escape(nil_check(title))+"&coverurl="+CGI.escape(nil_check(coverURL))+"&mleft="+nil_int_check(marginLeft)+"&mright="+nil_int_check(marginRight)+"&mtop="+nil_int_check(marginTop)+"&mbottom="+nil_int_check(marginBottom)+"&delay="+nil_int_check(delay)+"&requestmobileversion="+b_to_str(requestMobileVersion)+"&callback="
107
-
108
- @@signaturePartOne = nil_check(@applicationSecret)+"|"+nil_check(url)+"|"
109
- @@signaturePartTwo = "|"+nil_check(customId)+"|"+b_to_str(includeBackground)+"|"+pagesize +"|"+orientation+"|"+nil_check(customWaterMarkId)+"|"+b_to_str(includeLinks)+"|"+b_to_str(includeOutline)+"|"+nil_check(title)+"|"+nil_check(coverURL)+"|"+nil_int_check(marginTop)+"|"+nil_int_check(marginLeft)+"|"+nil_int_check(marginBottom)+"|"+nil_int_check(marginRight)+"|"+nil_int_check(delay)+"|"+b_to_str(requestMobileVersion)
110
-
111
- return nil
112
- end
113
-
114
- # Calls the GrabzIt web service to take the screenshot
115
- #
116
- # The handler will be passed a URL with the following query string parameters:
117
- # - message (is any error message associated with the screenshot)
118
- # - customId (is a custom id you may have specified in the {#set_image_options}, {#set_table_options} or {#set_pdf_options} method)
119
- # - id (is the unique id of the screenshot which can be used to retrieve the screenshot with the {#get_result} method)
120
- # - filename (is the filename of the screenshot)
121
- # - format (is the format of the screenshot)
122
- # @note This is the recommended method of saving a screenshot
123
- # @param callBackURL [String, nil] the handler the GrabzIt web service should call after it has completed its work
124
- # @return [String] the unique identifier of the screenshot. This can be used to get the screenshot with the {#get_result} method
125
- # @raise [RuntimeError] if the GrabzIt service reports an error with the request it will be raised as a RuntimeError
126
- def save(callBackURL = nil)
127
- if @@signaturePartOne == nil && @@signaturePartTwo == nil && @@request == nil
128
- raise "No screenshot parameters have been set."
129
- end
130
-
131
- sig = Digest::MD5.hexdigest(@@signaturePartOne+nil_check(callBackURL)+@@signaturePartTwo)
132
- @@request += CGI.escape(nil_check(callBackURL))+"&sig="+sig
133
-
134
- return get_result_value(get(@@request), "ID")
135
- end
136
-
137
- # Calls the GrabzIt web service to take the screenshot and saves it to the target path provided
138
- # @note Warning, this is a SYNCHONOUS method and can take up to 5 minutes before a response
139
- # @param saveToFile [String] the file path that the screenshot should saved to.
140
- # @example Synchronously save the screenshot to test.jpg
141
- # save_to('images/test.jpg')
142
- # @raise [RuntimeError] if the screenshot cannot be saved a RuntimeError will be raised that will contain an explanation
143
- # @return [Boolean] returns the true if it is successful otherwise it throws an exception.
144
- def save_to(saveToFile)
145
- id = save()
146
-
147
- #Wait for it to be ready.
148
- while true do
149
- status = get_status(id)
150
-
151
- if !status.cached && !status.processing
152
- raise "The screenshot did not complete with the error: " + status.Message
153
- break;
154
- elsif status.cached
155
- result = get_result(id)
156
- if !result
157
- raise "The screenshot image could not be found on GrabzIt."
158
- break
159
- end
160
-
161
- screenshot = File.new(saveToFile, "wb")
162
- screenshot.write(result)
163
- screenshot.close
164
-
165
- break
166
- end
167
-
168
- sleep(1)
169
- end
170
-
171
- return true
172
- end
173
-
174
-
175
- # Get the current status of a GrabzIt screenshot
176
- # @param id [String] the id of the screenshot
177
- # @return [ScreenShotStatus] a object representing the status of the screenshot
178
- def get_status(id)
179
- result = get(WebServicesBaseURL + "getstatus.ashx?id=" + nil_check(id))
180
-
181
- doc = REXML::Document.new(result)
182
-
183
- processing = doc.root.elements["Processing"].text()
184
- cached = doc.root.elements["Cached"].text()
185
- expired = doc.root.elements["Expired"].text()
186
- message = doc.root.elements["Message"].text()
187
-
188
- return ScreenShotStatus.new((processing == TrueString), (cached == TrueString), (expired == TrueString), message)
189
- end
190
-
191
- # This method returns the screenshot itself. If nothing is returned then something has gone wrong or the screenshot is not ready yet
192
- # @param id [String] the id of the screenshot
193
- # @return [Object] returns the screenshot
194
- # @raise [RuntimeError] if the GrabzIt service reports an error with the request it will be raised as a RuntimeError
195
- def get_result(id)
196
- return get(WebServicesBaseURL + "getfile.ashx?id=" + nil_check(id))
197
- end
198
-
199
- # Get all the cookies that GrabzIt is using for a particular domain. This may include your user set cookies as well
200
- # @param domain [String] the domain to return cookies for
201
- # @return [Array<Cookie>] an array of cookies
202
- # @raise [RuntimeError] if the GrabzIt service reports an error with the request it will be raised as a RuntimeError
203
- def get_cookies(domain)
204
- sig = Digest::MD5.hexdigest(nil_check(@applicationSecret)+"|"+nil_check(domain))
205
-
206
- qs = "key=" +CGI.escape(nil_check(@applicationKey))+"&domain="+CGI.escape(nil_check(domain))+"&sig="+sig
207
-
208
- result = get(WebServicesBaseURL + "getcookies.ashx?" + qs)
209
-
210
- doc = REXML::Document.new(result)
211
-
212
- message = doc.root.elements["Message"].text()
213
-
214
- if message != nil
215
- raise message
216
- end
217
-
218
- cookies = Array.new
219
-
220
- xml_cookies = doc.elements.to_a("//WebResult/Cookies/Cookie")
221
- xml_cookies.each do |cookie|
222
- expires = nil
223
- if cookie.elements["Expires"] != nil
224
- expires = cookie.elements["Expires"].text
225
- end
226
- grabzItCookie = GrabzIt::Cookie.new(cookie.elements["Name"].text, cookie.elements["Domain"].text, cookie.elements["Value"].text, cookie.elements["Path"].text, (cookie.elements["HttpOnly"].text == TrueString), expires, cookie.elements["Type"].text)
227
- cookies << grabzItCookie
228
- end
229
-
230
- return cookies
231
- end
232
-
233
- # Sets a new custom cookie on GrabzIt, if the custom cookie has the same name and domain as a global cookie the global
234
- # cookie is overridden
235
- # @note This can be useful if a websites functionality is controlled by cookies
236
- # @param name [String] the name of the cookie to set
237
- # @param domain [String] the domain of the website to set the cookie for
238
- # @param value [String, ''] the value of the cookie
239
- # @param path [String, '/'] the website path the cookie relates to
240
- # @param httponly [Boolean, false] is the cookie only used on HTTP
241
- # @param expires [String, ''] when the cookie expires. Pass a nil value if it does not expire
242
- # @return [Boolean] returns true if the cookie was successfully set
243
- # @raise [RuntimeError] if the GrabzIt service reports an error with the request it will be raised as a RuntimeError
244
- def set_cookie(name, domain, value = "", path = "/", httponly = false, expires = "")
245
- sig = Digest::MD5.hexdigest(nil_check(@applicationSecret)+"|"+nil_check(name)+"|"+nil_check(domain)+"|"+nil_check(value)+"|"+nil_check(path)+"|"+b_to_str(httponly)+"|"+nil_check(expires)+"|0")
246
-
247
- qs = "key=" +CGI.escape(nil_check(@applicationKey))+"&domain="+CGI.escape(nil_check(domain))+"&name="+CGI.escape(nil_check(name))+"&value="+CGI.escape(nil_check(value))+"&path="+CGI.escape(nil_check(path))+"&httponly="+b_to_str(httponly)+"&expires="+nil_check(expires)+"&sig="+sig
248
-
249
- return (get_result_value(get(WebServicesBaseURL + "setcookie.ashx?" + qs), "Result") == TrueString)
250
- end
251
-
252
- # Delete a custom cookie or block a global cookie from being used
253
- # @param name [String] the name of the cookie to delete
254
- # @param domain [String] the website the cookie belongs to
255
- # @return [Boolean] returns true if the cookie was successfully set
256
- # @raise [RuntimeError] if the GrabzIt service reports an error with the request it will be raised as a RuntimeError
257
- def delete_cookie(name, domain)
258
- sig = Digest::MD5.hexdigest(nil_check(@applicationSecret)+"|"+nil_check(name)+"|"+nil_check(domain)+"|1")
259
-
260
- qs = "key=" + CGI.escape(nil_check(@applicationKey))+"&domain="+CGI.escape(nil_check(domain))+"&name="+CGI.escape(nil_check(name))+"&delete=1&sig="+sig
261
-
262
- return (get_result_value(get(WebServicesBaseURL + "setcookie.ashx?" + qs), "Result") == TrueString)
263
- end
264
-
265
- # Get your uploaded custom watermarks
266
- # @param identifier [String, nil] the identifier of a particular custom watermark you want to view
267
- # @return [Array<WaterMark>] an array of uploaded watermarks
268
- def get_watermarks(identifier = nil)
269
- sig = Digest::MD5.hexdigest(nil_check(@applicationSecret)+"|"+nil_check(identifier))
270
-
271
- qs = "key=" +CGI.escape(nil_check(@applicationKey))+"&identifier="+CGI.escape(nil_check(identifier))+"&sig="+sig
272
-
273
- result = get(WebServicesBaseURL + "getwatermarks.ashx?" + qs)
274
-
275
- doc = REXML::Document.new(result)
276
-
277
- watermarks = Array.new
278
-
279
- xml_watemarks = doc.elements.to_a("//WebResult/WaterMarks/WaterMark")
280
- xml_watemarks.each do |watemark|
281
- grabzItWaterMark = GrabzIt::WaterMark.new(watemark.elements["Identifier"].text, watemark.elements["XPosition"].text.to_i, watemark.elements["YPosition"].text.to_i, watemark.elements["Format"].text)
282
- watermarks << grabzItWaterMark
283
- end
284
-
285
- return watermarks
286
- end
287
-
288
- # Add a new custom watermark
289
- # @param identifier [String] the identifier you want to give the custom watermark. It is important that this identifier is unique.
290
- # @param path [String] the absolute path of the watermark on your server. For instance C:/watermark/1.png
291
- # @param xpos [Integer] the horizontal position you want the screenshot to appear at: Left = 0, Center = 1, Right = 2
292
- # @param ypos [Integer] the vertical position you want the screenshot to appear at: Top = 0, Middle = 1, Bottom = 2
293
- # @return [Boolean] returns true if the watermark was successfully set
294
- # @raise [RuntimeError] if the GrabzIt service reports an error with the request it will be raised as a RuntimeError
295
- def add_watermark(identifier, path, xpos, ypos)
296
- if !File.file?(path)
297
- raise "File: " + path + " does not exist"
298
- end
299
- sig = Digest::MD5.hexdigest(nil_check(@applicationSecret)+"|"+nil_check(identifier)+"|"+nil_int_check(xpos)+"|"+nil_int_check(ypos));
300
-
301
- boundary = '--------------------------'+Time.now.to_f.to_s
302
-
303
- url = WebServicesBaseURL + "addwatermark.ashx"
304
- uri = URI.parse(url)
305
-
306
- file = File.open(path, "rb")
307
- data = file.read
308
-
309
- post_body = Array.new
310
- post_body << "\r\n--"+boundary+"\r\n"
311
- post_body << "Content-Disposition: form-data; name=\"watermark\"; filename=\""+File.basename(path)+"\"\r\nContent-Type: image/jpeg\r\n\r\n"
312
- post_body << data
313
- post_body << "\r\n--"+boundary+"\r\n"
314
-
315
- post_body << "Content-Disposition: form-data; name=\"key\"\r\n\r\n"
316
- post_body << CGI.escape(nil_check(@applicationKey))
317
- post_body << "\r\n--"+boundary+"\r\n"
318
-
319
- post_body << "Content-Disposition: form-data; name=\"identifier\"\r\n\r\n"
320
- post_body << CGI.escape(nil_check(identifier))
321
- post_body << "\r\n--"+boundary+"\r\n"
322
-
323
- post_body << "Content-Disposition: form-data; name=\"xpos\"\r\n\r\n"
324
- post_body << nil_check(xpos)
325
- post_body << "\r\n--"+boundary+"\r\n"
326
-
327
- post_body << "Content-Disposition: form-data; name=\"ypos\"\r\n\r\n"
328
- post_body << nil_check(ypos)
329
- post_body << "\r\n--"+boundary+"\r\n"
330
-
331
- post_body << "Content-Disposition: form-data; name=\"sig\"\r\n\r\n"
332
- post_body << sig
333
- post_body << "\r\n--"+boundary+"--\r\n"
334
-
335
- request = Net::HTTP::Post.new(url)
336
- request.content_type = "multipart/form-data, boundary="+boundary
337
- request.body = post_body.join
338
-
339
- response = Net::HTTP.new(uri.host, uri.port).start {|http| http.request(request) }
340
-
341
- return (get_result_value(response.body(), "Result") == TrueString)
342
- end
343
-
344
- # Delete a custom watermark
345
- # @param identifier [String] the identifier of the custom watermark you want to delete
346
- # @return [Boolean] returns true if the watermark was successfully deleted
347
- # @raise [RuntimeError] if the GrabzIt service reports an error with the request it will be raised as a RuntimeError
348
- def delete_watermark(identifier)
349
- sig = Digest::MD5.hexdigest(nil_check(@applicationSecret)+"|"+nil_check(identifier))
350
-
351
- qs = "key=" +CGI.escape(nil_check(@applicationKey))+"&identifier="+CGI.escape(nil_check(identifier))+"&sig="+sig
352
-
353
- return (get_result_value(get(WebServicesBaseURL + "deletewatermark.ashx?" + qs), "Result") == TrueString)
354
- end
355
-
356
- # This method calls the GrabzIt web service to take the screenshot.
357
- # @param url [String] the URL that the screenshot should be made of
358
- # @param callback [String, nil] the handler the GrabzIt web service should call after it has completed its work
359
- # @param customId [String, nil] custom identifier that you can pass through to the screenshot webservice. This will be returned with the callback URL you have specified.
360
- # @param browserWidth [Integer, nil] the width of the browser in pixels
361
- # @param browserHeight [Integer, nil] the height of the browser in pixels
362
- # @param width [Integer, nil] the width of the resulting thumbnail in pixels
363
- # @param height [Integer, nil] the height of the resulting thumbnail in pixels
364
- # @param format [String, nil] the format the screenshot should be in: bmp8, bmp16, bmp24, bmp, gif, jpg, png
365
- # @param delay [Integer, nil] the number of milliseconds to wait before taking the screenshot
366
- # @param targetElement [String, nil] the id of the only HTML element in the web page to turn into a screenshot
367
- # @return [String] returns the unique identifier of the screenshot. This can be used to get the screenshot with the get_result method
368
- # @raise [RuntimeError] if the GrabzIt service reports an error with the request it will be raised as a RuntimeError
369
- # @deprecated Use {#set_image_options} and {#save} instead.
370
- def take_picture(url, callback = nil, customId = nil, browserWidth = nil, browserHeight = nil, width = nil, height = nil, format = nil, delay = nil, targetElement = nil)
371
- set_image_options(url, customId, browserWidth, browserHeight, width, height, format, delay, targetElement)
372
- return save(callback)
373
- end
374
-
375
- # This method takes the screenshot and then saves the result to a file. WARNING this method is synchronous
376
- # @param url [String] the URL that the screenshot should be made of
377
- # @param saveToFile [String] the file path that the screenshot should saved to
378
- # @param browserWidth [Integer, nil] the width of the browser in pixels
379
- # @param browserHeight [Integer, nil] the height of the browser in pixels
380
- # @param width [Integer, nil] the width of the resulting thumbnail in pixels
381
- # @param height [Integer, nil] the height of the resulting thumbnail in pixels
382
- # @param format [String, nil] the format the screenshot should be in: bmp8, bmp16, bmp24, bmp, gif, jpg, png
383
- # @param delay [Integer, nil] the number of milliseconds to wait before taking the screenshot
384
- # @param targetElement [String, nil] the id of the only HTML element in the web page to turn into a screenshot
385
- # @example Synchronously save the screenshot to test.jpg
386
- # save_picture('images/test.jpg')
387
- # @return [Boolean] returns the true if it is successfull otherwise it throws an exception
388
- # @raise [RuntimeError] if the screenshot cannot be saved a RuntimeError will be raised that will contain an explanation
389
- # @deprecated Use {#set_image_options} and {#save_to} instead.
390
- def save_picture(url, saveToFile, browserWidth = nil, browserHeight = nil, width = nil, height = nil, format = nil, delay = nil, targetElement = nil)
391
- set_image_options(url, nil, browserWidth, browserHeight, width, height, format, delay, targetElement)
392
- return save_to(saveToFile)
393
- end
394
-
395
- # This method returns the image itself. If nothing is returned then something has gone wrong or the image is not ready yet.
396
- # @param id [String] the id of the screenshot
397
- # @return [Object] returns the screenshot
398
- # @deprecated Use {#get_result} instead.
399
- def get_picture(id)
400
- return get_result(id)
401
- end
402
-
403
- private
404
- def get(url)
405
- Net::HTTP.get(URI.parse(url))
406
- end
407
-
408
- private
409
- def b_to_str(bValue)
410
- if bValue
411
- return 1.to_s
412
- end
413
- return 0.to_s
414
- end
415
-
416
- private
417
- def nil_check(param)
418
- if param == nil
419
- return ""
420
- end
421
- return param
422
- end
423
-
424
- private
425
- def nil_int_check(param)
426
- return param.to_i.to_s
427
- end
428
-
429
- private
430
- def get_result_value(result, field)
431
- doc = REXML::Document.new(result)
432
-
433
- message = doc.root.elements["Message"].text()
434
- value = doc.root.elements[field].text()
435
-
436
- if message != nil
437
- raise message
438
- end
439
-
440
- return value
441
- end
442
- end
1
+ # The public REST API for http://grabz.it
2
+ # @example To include the GrabzIt module do the following
3
+ # require 'grabzit'
4
+ module GrabzIt
5
+ require 'digest/md5'
6
+ require 'net/http'
7
+ require 'rexml/document'
8
+ require 'cgi'
9
+ require 'uri'
10
+ require File.join(File.dirname(__FILE__), 'screenshotstatus')
11
+ require File.join(File.dirname(__FILE__), 'cookie')
12
+ require File.join(File.dirname(__FILE__), 'watermark')
13
+ require File.join(File.dirname(__FILE__), 'exception')
14
+
15
+ # This client provides access to the GrabzIt web services
16
+ # This API allows you to take screenshot of websites for free and convert them into images, PDF's and tables.
17
+ # @example Example usage
18
+ # require 'grabzit'
19
+ #
20
+ # grabzItClient = GrabzIt::Client.new("YOUR APPLICATION KEY", "YOUR APPLICATION SECRET")
21
+ # grabzItClient.set_image_options("http://www.google.com")
22
+ # grabzItClient.save("http://www.mysite.com/grabzit/handler")
23
+ # @version 2.1
24
+ # @author GrabzIt
25
+ # @see http://grabz.it/api/ruby/ GrabzIt Ruby API
26
+ class Client
27
+
28
+ WebServicesBaseURL = "http://grabz.it/services/"
29
+ private_constant :WebServicesBaseURL
30
+ TrueString = "True"
31
+ private_constant :TrueString
32
+
33
+ @@signaturePartOne;
34
+ @@signaturePartTwo;
35
+ @@request;
36
+
37
+ # Create a new instance of the Client class in order to access the GrabzIt API.
38
+ #
39
+ # @param applicationKey [String] your application key
40
+ # @param applicationSecret [String] your application secret
41
+ # @see http://grabz.it/register.aspx You can get an application key and secret by registering for free with GrabzIt
42
+ def initialize(applicationKey, applicationSecret)
43
+ @applicationKey = applicationKey
44
+ @applicationSecret = applicationSecret
45
+ end
46
+
47
+ # Sets the parameters required to take a screenshot of a web page.
48
+ #
49
+ # @param url [String] the URL that the screenshot should be made of
50
+ # @param customId [String, nil] custom identifier that you can pass through to the screenshot webservice. This will be returned with the callback URL you have specified.
51
+ # @param browserWidth [Integer, nil] the width of the browser in pixels
52
+ # @param browserHeight [Integer, nil] the height of the browser in pixels
53
+ # @param width [Integer, nil] the width of the resulting thumbnail in pixels
54
+ # @param height [Integer, nil] the height of the resulting thumbnail in pixels
55
+ # @param format [String, nil] the format the screenshot should be in: bmp8, bmp16, bmp24, bmp, gif, jpg, png
56
+ # @param delay [Integer, nil] the number of milliseconds to wait before taking the screenshot
57
+ # @param targetElement [String, nil] the id of the only HTML element in the web page to turn into a screenshot
58
+ # @param requestAs [Integer, 0] request the screenshot in different forms: Standard Browser = 0, Mobile Browser = 1, Search Engine = 2 and Fallback Browser = 3
59
+ # @param customWaterMarkId [String, nil] add a custom watermark to the image
60
+ # @param quality [Integer, -1] the quality of the image where 0 is poor and 100 excellent
61
+ # @param country [String, nil] request the screenshot from different countries: Default = "", UK = "UK", US = "US"
62
+ # @return [void]
63
+ def set_image_options(url, customId = nil, browserWidth = nil, browserHeight = nil, width = nil, height = nil, format = nil, delay = nil, targetElement = nil, requestAs = 0, customWaterMarkId = nil, quality = -1, country = nil)
64
+ @@request = WebServicesBaseURL + "takepicture.ashx?key="+CGI.escape(nil_check(@applicationKey))+"&url="+CGI.escape(nil_check(url))+"&width="+nil_int_check(width)+"&height="+nil_int_check(height)+"&format="+CGI.escape(nil_check(format))+"&bwidth="+nil_int_check(browserWidth)+"&bheight="+nil_int_check(browserHeight)+"&customid="+CGI.escape(nil_check(customId))+"&delay="+nil_int_check(delay)+"&target="+CGI.escape(nil_check(targetElement))+"&customwatermarkid="+CGI.escape(nil_check(customWaterMarkId))+"&requestmobileversion="+nil_int_check(requestAs)+"&country="+CGI.escape(nil_check(country))+"&quality="+nil_int_check(quality)+"&callback="
65
+ @@signaturePartOne = nil_check(@applicationSecret)+"|"+nil_check(url)+"|"
66
+ @@signaturePartTwo = "|"+nil_check(format)+"|"+nil_int_check(height)+"|"+nil_int_check(width)+"|"+nil_int_check(browserHeight)+"|"+nil_int_check(browserWidth)+"|"+nil_check(customId)+"|"+nil_int_check(delay)+"|"+nil_check(targetElement)+"|"+nil_check(customWaterMarkId)+"|"+nil_int_check(requestAs)+"|"+nil_check(country)+"|"+nil_int_check(quality)
67
+
68
+ return nil
69
+ end
70
+
71
+ # Sets the parameters required to extract one or more tables from a web page.
72
+ #
73
+ # @param url [String] the URL that the should be used to extract tables
74
+ # @param customId [String, nil] a custom identifier that you can pass through to the webservice. This will be returned with the callback URL you have specified.
75
+ # @param tableNumberToInclude [Integer, 1] the index of the table to be converted, were all tables in a web page are ordered from the top of the web page to bottom
76
+ # @param format [String, 'csv'] the format the table should be in: csv, xlsx
77
+ # @param includeHeaderNames [Boolean, true] if true header names will be included in the table
78
+ # @param includeAllTables [Boolean, true] if true all table on the web page will be extracted with each table appearing in a seperate spreadsheet sheet. Only available with the XLSX format.
79
+ # @param targetElement [String, nil] the id of the only HTML element in the web page that should be used to extract tables from
80
+ # @param requestAs [Integer, 0] request the screenshot in different forms: Standard Browser = 0, Mobile Browser = 1, Search Engine = 2 and Fallback Browser = 3
81
+ # @param country [String, nil] request the screenshot from different countries: Default = "", UK = "UK", US = "US"
82
+ # @return [void]
83
+ def set_table_options(url, customId = nil, tableNumberToInclude = 1, format = 'csv', includeHeaderNames = true, includeAllTables = false, targetElement = nil, requestAs = 0, country = nil)
84
+ @@request = WebServicesBaseURL + "taketable.ashx?key=" + CGI.escape(nil_check(@applicationKey))+"&url="+CGI.escape(url)+"&includeAllTables="+b_to_str(includeAllTables)+"&includeHeaderNames="+b_to_str(includeHeaderNames)+"&format="+CGI.escape(nil_check(format))+"&tableToInclude="+nil_int_check(tableNumberToInclude)+"&customid="+CGI.escape(nil_check(customId))+"&target="+CGI.escape(nil_check(targetElement))+"&requestmobileversion="+nil_int_check(requestAs)+"&country="+CGI.escape(nil_check(country))+"&callback="
85
+ @@signaturePartOne = nil_check(@applicationSecret)+"|"+nil_check(url)+"|"
86
+ @@signaturePartTwo = "|"+nil_check(customId)+"|"+nil_int_check(tableNumberToInclude)+"|"+b_to_str(includeAllTables)+"|"+b_to_str(includeHeaderNames)+"|"+nil_check(targetElement)+"|"+nil_check(format)+"|"+nil_int_check(requestAs)+"|"+nil_check(country)
87
+
88
+ return nil
89
+ end
90
+
91
+ # Sets the parameters required to convert a web page into a PDF.
92
+ #
93
+ # @param url url [String] the URL that the should be converted into a pdf
94
+ # @param customId [String, nil] a custom identifier that you can pass through to the webservice. This will be returned with the callback URL you have specified.
95
+ # @param includeBackground [Boolean, true] if true the background of the web page should be included in the screenshot
96
+ # @param pagesize [String, 'A4'] the page size of the PDF to be returned: 'A3', 'A4', 'A5', 'B3', 'B4', 'B5', 'Letter'.
97
+ # @param orientation [String, 'Portrait'] the orientation of the PDF to be returned: 'Landscape' or 'Portrait'
98
+ # @param includeLinks [Boolean, true] true if links should be included in the PDF
99
+ # @param includeOutline [Boolean, false] True if the PDF outline should be included
100
+ # @param title [String, nil] provide a title to the PDF document
101
+ # @param coverURL [String, nil] the URL of a web page that should be used as a cover page for the PDF
102
+ # @param marginTop [Integer, 10] the margin that should appear at the top of the PDF document page
103
+ # @param marginLeft [Integer, 10] the margin that should appear at the left of the PDF document page
104
+ # @param marginBottom [Integer, 10] the margin that should appear at the bottom of the PDF document page
105
+ # @param marginRight [Integer, 10] the margin that should appear at the right of the PDF document
106
+ # @param delay [Integer, nil] the number of milliseconds to wait before taking the screenshot
107
+ # @param requestAs [Integer, 0] request the screenshot in different forms: Standard Browser = 0, Mobile Browser = 1, Search Engine = 2 and Fallback Browser = 3
108
+ # @param customWaterMarkId [String, nil] add a custom watermark to each page of the PDF document
109
+ # @param quality [Integer, -1] the quality of the PDF where 0 is poor and 100 excellent
110
+ # @param country [String, nil] request the screenshot from different countries: Default = "", UK = "UK", US = "US"
111
+ # @return [void]
112
+ def set_pdf_options(url, customId = nil, includeBackground = true, pagesize = 'A4', orientation = 'Portrait', includeLinks = true, includeOutline = false, title = nil, coverURL = nil, marginTop = 10, marginLeft = 10, marginBottom = 10, marginRight = 10, delay = nil, requestAs = 0, customWaterMarkId = nil, quality = -1, country = nil)
113
+ pagesize = nil_check(pagesize).upcase
114
+ $orientation = nil_check(orientation).capitalize
115
+
116
+ @@request = WebServicesBaseURL + "takepdf.ashx?key=" + CGI.escape(nil_check(@applicationKey))+"&url="+CGI.escape(nil_check(url))+"&background="+b_to_str(includeBackground)+"&pagesize="+pagesize+"&orientation="+orientation+"&customid="+CGI.escape(nil_check(customId))+"&customwatermarkid="+CGI.escape(nil_check(customWaterMarkId))+"&includelinks="+b_to_str(includeLinks)+"&includeoutline="+b_to_str(includeOutline)+"&title="+CGI.escape(nil_check(title))+"&coverurl="+CGI.escape(nil_check(coverURL))+"&mleft="+nil_int_check(marginLeft)+"&mright="+nil_int_check(marginRight)+"&mtop="+nil_int_check(marginTop)+"&mbottom="+nil_int_check(marginBottom)+"&delay="+nil_int_check(delay)+"&requestmobileversion="+nil_int_check(requestAs)+"&country="+CGI.escape(nil_check(country))+"&quality="+nil_int_check(quality)+"&callback="
117
+
118
+ @@signaturePartOne = nil_check(@applicationSecret)+"|"+nil_check(url)+"|"
119
+ @@signaturePartTwo = "|"+nil_check(customId)+"|"+b_to_str(includeBackground)+"|"+pagesize +"|"+orientation+"|"+nil_check(customWaterMarkId)+"|"+b_to_str(includeLinks)+"|"+b_to_str(includeOutline)+"|"+nil_check(title)+"|"+nil_check(coverURL)+"|"+nil_int_check(marginTop)+"|"+nil_int_check(marginLeft)+"|"+nil_int_check(marginBottom)+"|"+nil_int_check(marginRight)+"|"+nil_int_check(delay)+"|"+nil_int_check(requestAs)+"|"+nil_check(country)+"|"+nil_int_check(quality)
120
+
121
+ return nil
122
+ end
123
+
124
+ # Calls the GrabzIt web service to take the screenshot
125
+ #
126
+ # The handler will be passed a URL with the following query string parameters:
127
+ # - message (is any error message associated with the screenshot)
128
+ # - customId (is a custom id you may have specified in the {#set_image_options}, {#set_table_options} or {#set_pdf_options} method)
129
+ # - id (is the unique id of the screenshot which can be used to retrieve the screenshot with the {#get_result} method)
130
+ # - filename (is the filename of the screenshot)
131
+ # - format (is the format of the screenshot)
132
+ # @note This is the recommended method of saving a screenshot
133
+ # @param callBackURL [String, nil] the handler the GrabzIt web service should call after it has completed its work
134
+ # @return [String] the unique identifier of the screenshot. This can be used to get the screenshot with the {#get_result} method
135
+ # @raise [RuntimeError] if the GrabzIt service reports an error with the request it will be raised as a RuntimeError
136
+ def save(callBackURL = nil)
137
+ if @@signaturePartOne == nil && @@signaturePartTwo == nil && @@request == nil
138
+ raise GrabzItException.new("No screenshot parameters have been set.", GrabzItException::PARAMETER_MISSING_PARAMETERS)
139
+ end
140
+
141
+ sig = Digest::MD5.hexdigest(@@signaturePartOne+nil_check(callBackURL)+@@signaturePartTwo)
142
+ @@request += CGI.escape(nil_check(callBackURL))+"&sig="+sig
143
+
144
+ return get_result_value(get(@@request), "ID")
145
+ end
146
+
147
+ # Calls the GrabzIt web service to take the screenshot and saves it to the target path provided
148
+ #
149
+ # @note Warning, this is a SYNCHONOUS method and can take up to 5 minutes before a response
150
+ # @param saveToFile [String] the file path that the screenshot should saved to.
151
+ # @example Synchronously save the screenshot to test.jpg
152
+ # save_to('images/test.jpg')
153
+ # @raise [RuntimeError] if the screenshot cannot be saved a RuntimeError will be raised that will contain an explanation
154
+ # @return [Boolean] returns the true if it is successful otherwise it throws an exception.
155
+ def save_to(saveToFile)
156
+ id = save()
157
+
158
+ if id == nil || id == ""
159
+ return false
160
+ end
161
+
162
+ #Wait for it to be ready.
163
+ while true do
164
+ status = get_status(id)
165
+
166
+ if !status.cached && !status.processing
167
+ raise GrabzItException.new("The screenshot did not complete with the error: " + status.Message, GrabzItException::RENDERING_ERROR)
168
+ break
169
+ elsif status.cached
170
+ result = get_result(id)
171
+ if !result
172
+ raise GrabzItException.new("The screenshot could not be found on GrabzIt.", GrabzItException::RENDERING_MISSING_SCREENSHOT)
173
+ break
174
+ end
175
+
176
+ screenshot = File.new(saveToFile, "wb")
177
+ screenshot.write(result)
178
+ screenshot.close
179
+
180
+ break
181
+ end
182
+
183
+ sleep(3)
184
+ end
185
+
186
+ return true
187
+ end
188
+
189
+ # Get the current status of a GrabzIt screenshot
190
+ #
191
+ # @param id [String] the id of the screenshot
192
+ # @return [ScreenShotStatus] a object representing the status of the screenshot
193
+ def get_status(id)
194
+
195
+ if id == nil || id == ""
196
+ return nil
197
+ end
198
+
199
+ result = get(WebServicesBaseURL + "getstatus.ashx?id=" + nil_check(id))
200
+
201
+ doc = REXML::Document.new(result)
202
+
203
+ processing = doc.root.elements["Processing"].text()
204
+ cached = doc.root.elements["Cached"].text()
205
+ expired = doc.root.elements["Expired"].text()
206
+ message = doc.root.elements["Message"].text()
207
+
208
+ return ScreenShotStatus.new((processing == TrueString), (cached == TrueString), (expired == TrueString), message)
209
+ end
210
+
211
+ # This method returns the screenshot itself. If nothing is returned then something has gone wrong or the screenshot is not ready yet
212
+ #
213
+ # @param id [String] the id of the screenshot
214
+ # @return [Object] returns the screenshot
215
+ # @raise [RuntimeError] if the GrabzIt service reports an error with the request it will be raised as a RuntimeError
216
+ def get_result(id)
217
+ return get(WebServicesBaseURL + "getfile.ashx?id=" + nil_check(id))
218
+ end
219
+
220
+ # Get all the cookies that GrabzIt is using for a particular domain. This may include your user set cookies as well
221
+ #
222
+ # @param domain [String] the domain to return cookies for
223
+ # @return [Array<Cookie>] an array of cookies
224
+ # @raise [RuntimeError] if the GrabzIt service reports an error with the request it will be raised as a RuntimeError
225
+ def get_cookies(domain)
226
+ sig = Digest::MD5.hexdigest(nil_check(@applicationSecret)+"|"+nil_check(domain))
227
+
228
+ qs = "key=" +CGI.escape(nil_check(@applicationKey))+"&domain="+CGI.escape(nil_check(domain))+"&sig="+sig
229
+
230
+ result = get(WebServicesBaseURL + "getcookies.ashx?" + qs)
231
+
232
+ doc = REXML::Document.new(result)
233
+
234
+ check_for_exception(doc)
235
+
236
+ cookies = Array.new
237
+
238
+ xml_cookies = doc.elements.to_a("//WebResult/Cookies/Cookie")
239
+ xml_cookies.each do |cookie|
240
+ expires = nil
241
+ if cookie.elements["Expires"] != nil
242
+ expires = cookie.elements["Expires"].text
243
+ end
244
+ grabzItCookie = GrabzIt::Cookie.new(cookie.elements["Name"].text, cookie.elements["Domain"].text, cookie.elements["Value"].text, cookie.elements["Path"].text, (cookie.elements["HttpOnly"].text == TrueString), expires, cookie.elements["Type"].text)
245
+ cookies << grabzItCookie
246
+ end
247
+
248
+ return cookies
249
+ end
250
+
251
+ # Sets a new custom cookie on GrabzIt, if the custom cookie has the same name and domain as a global cookie the global
252
+ #
253
+ # cookie is overridden
254
+ # @note This can be useful if a websites functionality is controlled by cookies
255
+ # @param name [String] the name of the cookie to set
256
+ # @param domain [String] the domain of the website to set the cookie for
257
+ # @param value [String, ''] the value of the cookie
258
+ # @param path [String, '/'] the website path the cookie relates to
259
+ # @param httponly [Boolean, false] is the cookie only used on HTTP
260
+ # @param expires [String, ''] when the cookie expires. Pass a nil value if it does not expire
261
+ # @return [Boolean] returns true if the cookie was successfully set
262
+ # @raise [RuntimeError] if the GrabzIt service reports an error with the request it will be raised as a RuntimeError
263
+ def set_cookie(name, domain, value = "", path = "/", httponly = false, expires = "")
264
+ sig = Digest::MD5.hexdigest(nil_check(@applicationSecret)+"|"+nil_check(name)+"|"+nil_check(domain)+"|"+nil_check(value)+"|"+nil_check(path)+"|"+b_to_str(httponly)+"|"+nil_check(expires)+"|0")
265
+
266
+ qs = "key=" +CGI.escape(nil_check(@applicationKey))+"&domain="+CGI.escape(nil_check(domain))+"&name="+CGI.escape(nil_check(name))+"&value="+CGI.escape(nil_check(value))+"&path="+CGI.escape(nil_check(path))+"&httponly="+b_to_str(httponly)+"&expires="+CGI.escape(nil_check(expires))+"&sig="+sig
267
+
268
+ return (get_result_value(get(WebServicesBaseURL + "setcookie.ashx?" + qs), "Result") == TrueString)
269
+ end
270
+
271
+ # Delete a custom cookie or block a global cookie from being used
272
+ #
273
+ # @param name [String] the name of the cookie to delete
274
+ # @param domain [String] the website the cookie belongs to
275
+ # @return [Boolean] returns true if the cookie was successfully set
276
+ # @raise [RuntimeError] if the GrabzIt service reports an error with the request it will be raised as a RuntimeError
277
+ def delete_cookie(name, domain)
278
+ sig = Digest::MD5.hexdigest(nil_check(@applicationSecret)+"|"+nil_check(name)+"|"+nil_check(domain)+"|1")
279
+
280
+ qs = "key=" + CGI.escape(nil_check(@applicationKey))+"&domain="+CGI.escape(nil_check(domain))+"&name="+CGI.escape(nil_check(name))+"&delete=1&sig="+sig
281
+
282
+ return (get_result_value(get(WebServicesBaseURL + "setcookie.ashx?" + qs), "Result") == TrueString)
283
+ end
284
+
285
+ # Get your uploaded custom watermark
286
+ #
287
+ # @param identifier [String, nil] the identifier of a particular custom watermark you want to view
288
+ # @return [WaterMark] the watermark with the specified identifier
289
+ def get_watermark(identifier)
290
+ watermarks = get_watermarks(identifier)
291
+ if watermarks.length == 1
292
+ return watermarks[0];
293
+ end
294
+
295
+ return nil
296
+ end
297
+
298
+ # Get your uploaded custom watermarks
299
+ #
300
+ # @return [Array<WaterMark>] an array of uploaded watermarks
301
+ def get_watermarks()
302
+ return get_watermarks(nil)
303
+ end
304
+
305
+ # Add a new custom watermark
306
+ #
307
+ # @param identifier [String] the identifier you want to give the custom watermark. It is important that this identifier is unique.
308
+ # @param path [String] the absolute path of the watermark on your server. For instance C:/watermark/1.png
309
+ # @param xpos [Integer] the horizontal position you want the screenshot to appear at: Left = 0, Center = 1, Right = 2
310
+ # @param ypos [Integer] the vertical position you want the screenshot to appear at: Top = 0, Middle = 1, Bottom = 2
311
+ # @return [Boolean] returns true if the watermark was successfully set
312
+ # @raise [RuntimeError] if the GrabzIt service reports an error with the request it will be raised as a RuntimeError
313
+ def add_watermark(identifier, path, xpos, ypos)
314
+ if !File.file?(path)
315
+ raise "File: " + path + " does not exist"
316
+ end
317
+ sig = Digest::MD5.hexdigest(nil_check(@applicationSecret)+"|"+nil_check(identifier)+"|"+nil_int_check(xpos)+"|"+nil_int_check(ypos));
318
+
319
+ boundary = '--------------------------'+Time.now.to_f.to_s
320
+
321
+ url = WebServicesBaseURL + "addwatermark.ashx"
322
+ uri = URI.parse(url)
323
+
324
+ file = File.open(path, "rb")
325
+ data = file.read
326
+
327
+ post_body = Array.new
328
+ post_body << "\r\n--"+boundary+"\r\n"
329
+ post_body << "Content-Disposition: form-data; name=\"watermark\"; filename=\""+File.basename(path)+"\"\r\nContent-Type: image/jpeg\r\n\r\n"
330
+ post_body << data
331
+ post_body << "\r\n--"+boundary+"\r\n"
332
+
333
+ post_body << "Content-Disposition: form-data; name=\"key\"\r\n\r\n"
334
+ post_body << CGI.escape(nil_check(@applicationKey))
335
+ post_body << "\r\n--"+boundary+"\r\n"
336
+
337
+ post_body << "Content-Disposition: form-data; name=\"identifier\"\r\n\r\n"
338
+ post_body << CGI.escape(nil_check(identifier))
339
+ post_body << "\r\n--"+boundary+"\r\n"
340
+
341
+ post_body << "Content-Disposition: form-data; name=\"xpos\"\r\n\r\n"
342
+ post_body << nil_check(xpos)
343
+ post_body << "\r\n--"+boundary+"\r\n"
344
+
345
+ post_body << "Content-Disposition: form-data; name=\"ypos\"\r\n\r\n"
346
+ post_body << nil_check(ypos)
347
+ post_body << "\r\n--"+boundary+"\r\n"
348
+
349
+ post_body << "Content-Disposition: form-data; name=\"sig\"\r\n\r\n"
350
+ post_body << sig
351
+ post_body << "\r\n--"+boundary+"--\r\n"
352
+
353
+ request = Net::HTTP::Post.new(url)
354
+ request.content_type = "multipart/form-data, boundary="+boundary
355
+ request.body = post_body.join
356
+
357
+ response = Net::HTTP.new(uri.host, uri.port).start {|http| http.request(request) }
358
+ response_check(response)
359
+
360
+ return (get_result_value(response.body(), "Result") == TrueString)
361
+ end
362
+
363
+ # Delete a custom watermark
364
+ #
365
+ # @param identifier [String] the identifier of the custom watermark you want to delete
366
+ # @return [Boolean] returns true if the watermark was successfully deleted
367
+ # @raise [RuntimeError] if the GrabzIt service reports an error with the request it will be raised as a RuntimeError
368
+ def delete_watermark(identifier)
369
+ sig = Digest::MD5.hexdigest(nil_check(@applicationSecret)+"|"+nil_check(identifier))
370
+
371
+ qs = "key=" +CGI.escape(nil_check(@applicationKey))+"&identifier="+CGI.escape(nil_check(identifier))+"&sig="+sig
372
+
373
+ return (get_result_value(get(WebServicesBaseURL + "deletewatermark.ashx?" + qs), "Result") == TrueString)
374
+ end
375
+
376
+ # This method calls the GrabzIt web service to take the screenshot.
377
+ #
378
+ # @param url [String] the URL that the screenshot should be made of
379
+ # @param callback [String, nil] the handler the GrabzIt web service should call after it has completed its work
380
+ # @param customId [String, nil] custom identifier that you can pass through to the screenshot webservice. This will be returned with the callback URL you have specified.
381
+ # @param browserWidth [Integer, nil] the width of the browser in pixels
382
+ # @param browserHeight [Integer, nil] the height of the browser in pixels
383
+ # @param width [Integer, nil] the width of the resulting thumbnail in pixels
384
+ # @param height [Integer, nil] the height of the resulting thumbnail in pixels
385
+ # @param format [String, nil] the format the screenshot should be in: bmp8, bmp16, bmp24, bmp, gif, jpg, png
386
+ # @param delay [Integer, nil] the number of milliseconds to wait before taking the screenshot
387
+ # @param targetElement [String, nil] the id of the only HTML element in the web page to turn into a screenshot
388
+ # @return [String] returns the unique identifier of the screenshot. This can be used to get the screenshot with the get_result method
389
+ # @raise [RuntimeError] if the GrabzIt service reports an error with the request it will be raised as a RuntimeError
390
+ # @deprecated Use {#set_image_options} and {#save} instead.
391
+ def take_picture(url, callback = nil, customId = nil, browserWidth = nil, browserHeight = nil, width = nil, height = nil, format = nil, delay = nil, targetElement = nil)
392
+ set_image_options(url, customId, browserWidth, browserHeight, width, height, format, delay, targetElement)
393
+ return save(callback)
394
+ end
395
+
396
+ # This method takes the screenshot and then saves the result to a file. WARNING this method is synchronous
397
+ #
398
+ # @param url [String] the URL that the screenshot should be made of
399
+ # @param saveToFile [String] the file path that the screenshot should saved to
400
+ # @param browserWidth [Integer, nil] the width of the browser in pixels
401
+ # @param browserHeight [Integer, nil] the height of the browser in pixels
402
+ # @param width [Integer, nil] the width of the resulting thumbnail in pixels
403
+ # @param height [Integer, nil] the height of the resulting thumbnail in pixels
404
+ # @param format [String, nil] the format the screenshot should be in: bmp8, bmp16, bmp24, bmp, gif, jpg, png
405
+ # @param delay [Integer, nil] the number of milliseconds to wait before taking the screenshot
406
+ # @param targetElement [String, nil] the id of the only HTML element in the web page to turn into a screenshot
407
+ # @example Synchronously save the screenshot to test.jpg
408
+ # save_picture('images/test.jpg')
409
+ # @return [Boolean] returns the true if it is successfull otherwise it throws an exception
410
+ # @raise [RuntimeError] if the screenshot cannot be saved a RuntimeError will be raised that will contain an explanation
411
+ # @deprecated Use {#set_image_options} and {#save_to} instead.
412
+ def save_picture(url, saveToFile, browserWidth = nil, browserHeight = nil, width = nil, height = nil, format = nil, delay = nil, targetElement = nil)
413
+ set_image_options(url, nil, browserWidth, browserHeight, width, height, format, delay, targetElement)
414
+ return save_to(saveToFile)
415
+ end
416
+
417
+ # This method returns the image itself. If nothing is returned then something has gone wrong or the image is not ready yet.
418
+ #
419
+ # @param id [String] the id of the screenshot
420
+ # @return [Object] returns the screenshot
421
+ # @deprecated Use {#get_result} instead.
422
+ def get_picture(id)
423
+ return get_result(id)
424
+ end
425
+
426
+ private
427
+ def get_watermarks(identifier = nil)
428
+ sig = Digest::MD5.hexdigest(nil_check(@applicationSecret)+"|"+nil_check(identifier))
429
+
430
+ qs = "key=" +CGI.escape(nil_check(@applicationKey))+"&identifier="+CGI.escape(nil_check(identifier))+"&sig="+sig
431
+
432
+ result = get(WebServicesBaseURL + "getwatermarks.ashx?" + qs)
433
+
434
+ doc = REXML::Document.new(result)
435
+
436
+ check_for_exception(doc)
437
+
438
+ watermarks = Array.new
439
+
440
+ xml_watemarks = doc.elements.to_a("//WebResult/WaterMarks/WaterMark")
441
+ xml_watemarks.each do |watemark|
442
+ grabzItWaterMark = GrabzIt::WaterMark.new(watemark.elements["Identifier"].text, watemark.elements["XPosition"].text.to_i, watemark.elements["YPosition"].text.to_i, watemark.elements["Format"].text)
443
+ watermarks << grabzItWaterMark
444
+ end
445
+
446
+ return watermarks
447
+ end
448
+
449
+ private
450
+ def get(url)
451
+ uri = URI.parse(url)
452
+ response = Net::HTTP.start(uri.host, uri.port) { |http| http.get(uri.request_uri) }
453
+ response_check(response)
454
+ return response.body
455
+ end
456
+
457
+ private
458
+ def response_check(response)
459
+ statusCode = response.code.to_i
460
+ if statusCode == 403
461
+ raise GrabzItException.new(response.body, GrabzItException::NETWORK_DDOS_ATTACK)
462
+ elsif statusCode >= 400
463
+ raise GrabzItException.new("A network error occured when connecting to the GrabzIt servers.", GrabzItException::NETWORK_GENERAL_ERROR)
464
+ end
465
+ end
466
+
467
+ private
468
+ def b_to_str(bValue)
469
+ if bValue
470
+ return 1.to_s
471
+ end
472
+ return 0.to_s
473
+ end
474
+
475
+ private
476
+ def nil_check(param)
477
+ if param == nil
478
+ return ""
479
+ end
480
+ return param
481
+ end
482
+
483
+ private
484
+ def nil_int_check(param)
485
+ return param.to_i.to_s
486
+ end
487
+
488
+ private
489
+ def check_for_exception(doc)
490
+ if (doc == nil)
491
+ return
492
+ end
493
+
494
+ message = doc.root.elements["Message"].text()
495
+ code = doc.root.elements["Code"].text()
496
+
497
+ if message != nil
498
+ raise GrabzItException.new(message, code)
499
+ end
500
+ end
501
+
502
+ private
503
+ def get_result_value(result, field)
504
+ doc = REXML::Document.new(result)
505
+
506
+ value = doc.root.elements[field].text()
507
+
508
+ check_for_exception(doc)
509
+
510
+ return value
511
+ end
512
+ end
443
513
  end