shutterbug 0.0.2

Sign up to get free protection for your applications and to get access to all the features.
data/.gitignore ADDED
@@ -0,0 +1,18 @@
1
+ *.gem
2
+ *~
3
+ *.rbc
4
+ .bundle
5
+ .config
6
+ .yardoc
7
+ Gemfile.lock
8
+ InstalledFiles
9
+ _yardoc
10
+ coverage
11
+ doc/
12
+ lib/bundler/man
13
+ pkg
14
+ rdoc
15
+ spec/reports
16
+ test/tmp
17
+ test/version_tmp
18
+ tmp
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --color
2
+ --format progress
data/.ruby-gemset ADDED
@@ -0,0 +1 @@
1
+ shutterbug
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ ruby-1.9.3-p327
data/.travis.yml ADDED
@@ -0,0 +1,11 @@
1
+ language: ruby
2
+ rvm:
3
+ - "1.8.7"
4
+ - "1.9.2"
5
+ - "1.9.3"
6
+ - jruby-18mode # JRuby in 1.8 mode
7
+ - jruby-19mode # JRuby in 1.9 mode
8
+ - rbx-18mode
9
+ - rbx-19mode
10
+ # uncomment this line if your project needs to run something other than `rake`:
11
+ # script: bundle exec rspec spec
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in shutterbug.gemspec
4
+ gemspec
data/Guardfile ADDED
@@ -0,0 +1,9 @@
1
+ # A sample Guardfile
2
+ # More info at https://github.com/guard/guard#readme
3
+
4
+ guard :rspec do
5
+ watch(%r{^spec/.+_spec\.rb$})
6
+ watch(%r{^lib/(.+)\.rb$}) { |m| "spec/#{m[1]}_spec.rb" }
7
+ watch('spec/spec_helper.rb') { "spec" }
8
+ end
9
+
data/LICENSE.md ADDED
@@ -0,0 +1,127 @@
1
+ ## [shutterbug](https://github.com/concord-consortium/shutterbug) ##
2
+ is Copyright 2012 © by the Concord Consortium and is distributed under any of the following licenses:
3
+
4
+ * [Simplified BSD](http://www.opensource.org/licenses/BSD-2-Clause),
5
+ * [MIT](http://www.opensource.org/licenses/MIT), or
6
+ * [Apache 2.0](http://www.opensource.org/licenses/Apache-2.0).
7
+
8
+ ##MIT License##
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining
11
+ a copy of this software and associated documentation files (the
12
+ "Software"), to deal in the Software without restriction, including
13
+ without limitation the rights to use, copy, modify, merge, publish,
14
+ distribute, sublicense, and/or sell copies of the Software, and to
15
+ permit persons to whom the Software is furnished to do so, subject to
16
+ the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be
19
+ included in all copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28
+
29
+ In the original BSD license, both occurrences of the phrase "COPYRIGHT HOLDERS AND CONTRIBUTORS" in the disclaimer read "REGENTS AND CONTRIBUTORS".
30
+
31
+ ----
32
+
33
+ ## Simplified BSD License ##
34
+
35
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
36
+
37
+ Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
38
+ Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
39
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40
+
41
+ ----
42
+
43
+ ## Apache License ##
44
+
45
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
46
+
47
+ 1. Definitions.
48
+
49
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
50
+
51
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
52
+
53
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
54
+
55
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
56
+
57
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
58
+
59
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
60
+
61
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
62
+
63
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
64
+
65
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
66
+
67
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
68
+
69
+ 2. Grant of Copyright License.
70
+
71
+ Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License.
74
+
75
+ Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
76
+
77
+ 4. Redistribution.
78
+
79
+ You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
80
+
81
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
82
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
83
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
84
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
85
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
86
+
87
+ 5. Submission of Contributions.
88
+
89
+ Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
90
+
91
+ 6. Trademarks.
92
+
93
+ This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
94
+
95
+ 7. Disclaimer of Warranty.
96
+
97
+ Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
98
+
99
+ 8. Limitation of Liability.
100
+
101
+ In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
102
+
103
+ 9. Accepting Warranty or Additional Liability.
104
+
105
+ While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
106
+
107
+ END OF TERMS AND CONDITIONS
108
+
109
+ APPENDIX: How to apply the Apache License to your work
110
+
111
+ To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
112
+
113
+ Copyright [yyyy] [name of copyright owner]
114
+
115
+ Licensed under the Apache License, Version 2.0 (the "License");
116
+ you may not use this file except in compliance with the License.
117
+ You may obtain a copy of the License at
118
+
119
+ http://www.apache.org/licenses/LICENSE-2.0
120
+
121
+ Unless required by applicable law or agreed to in writing, software
122
+ distributed under the License is distributed on an "AS IS" BASIS,
123
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
124
+ See the License for the specific language governing permissions and
125
+ limitations under the License.
126
+
127
+
data/README.md ADDED
@@ -0,0 +1,58 @@
1
+ # Shutterbug
2
+
3
+ [![Build Status](https://travis-ci.org/concord-consortium/shutterbug.png?branch=master)](https://travis-ci.org/concord-consortium/shutterbug)
4
+ [![Code Climate](https://codeclimate.com/github/concord-consortium/shutterbug.png)](https://codeclimate.com/github/concord-consortium/shutterbug)
5
+
6
+ A rack utility that will create and save images (pngs) from parts of your html's documents current dom. These images become available as public png resources in the rack application. Currently shutterbug supports HTML, SVG and Canvas elements.
7
+
8
+
9
+ use Shutterbug::Rackapp
10
+
11
+
12
+ ## Installation
13
+
14
+ Add this line to your application's Gemfile:
15
+
16
+ gem 'shutterbug'
17
+
18
+ And then execute:
19
+
20
+ $ bundle
21
+
22
+ Or install it yourself as:
23
+
24
+ $ gem install shutterbug
25
+
26
+ ## License ##
27
+
28
+ * [Simplified BSD](http://www.opensource.org/licenses/BSD-2-Clause),
29
+ * [MIT](http://www.opensource.org/licenses/MIT), or
30
+ * [Apache 2.0](http://www.opensource.org/licenses/Apache-2.0).
31
+
32
+ See License.txt for more information.
33
+
34
+ ## Usage
35
+
36
+ After adding `use Shutterbug::Rackapp` to your config.ru file, you can convert pieces of your web-page into png images. Just follow these steps:
37
+
38
+ 1. include the following javascript in your pages: `<script src='http://<yourhost:port>/shutterbug/shutterbug.js' type='text/javascript'></script>`
39
+ 1. Elsewhere in your javascript call `getDomSnapshot($("#sourceDomID"),$("#imageOutputDomId"));` This will replace the contents of `$("#imageOutputDomId")` with an `<img src="http://<yourhost:port>/gete_png/sha1hash>` tag which will magically spring into existance.
40
+
41
+ ## TODO: ##
42
+
43
+ * Configuration of the rack paths.
44
+ * Fix web-font bugs in phantom js.
45
+ * Better abstraction phantomjs command line invocation. Use phantomjs.rb ?
46
+ * Use [sprockets](https://github.com/sstephenson/sprockets) for and coffee.erb for shutterbug.js
47
+ * Write Tests.
48
+ * Write Documentation.
49
+
50
+ ## Contributing
51
+
52
+ 1. Fork it
53
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
54
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
55
+ 4. Push to the branch (`git push origin my-new-feature`)
56
+ 5. Create new Pull Request
57
+
58
+ © 2013 The concord Consortium.
data/Rakefile ADDED
@@ -0,0 +1,7 @@
1
+ require "bundler/gem_tasks"
2
+ require 'rspec/core/rake_task'
3
+
4
+ RSpec::Core::RakeTask.new('spec')
5
+
6
+ # If you want to make this the default task
7
+ task :default => :spec
data/lib/shutterbug.rb ADDED
@@ -0,0 +1,5 @@
1
+ module Shutterbug
2
+ VERSION = "0.0.2"
3
+ autoload :Service, "shutterbug/service"
4
+ autoload :Rackapp, "shutterbug/rackapp"
5
+ end
@@ -0,0 +1,78 @@
1
+ # encoding: utf-8
2
+
3
+ module Shutterbug
4
+ class Rackapp
5
+ BASE_PATH = "/shutterbug"
6
+
7
+ CONVERT_PATH = "#{BASE_PATH}/make_snapshot"
8
+ CONVERT_REGEX = /#{CONVERT_PATH}/
9
+
10
+ PNG_PATH = "#{BASE_PATH}/get_png"
11
+ GET_PNG_REGEX = /#{PNG_PATH}\/([^\/]+)/
12
+
13
+ HTML_PATH = "#{BASE_PATH}/get_html"
14
+ GET_HTML_REGEX = /#{HTML_PATH}\/([^\/]+)/
15
+
16
+ JS_PATH = "#{BASE_PATH}/shutterbug.js"
17
+ JS_REGEX = /#{JS_PATH}$/
18
+
19
+ def initialize app
20
+ @app = app
21
+ @shutterbug = Service.new()
22
+ log "initialized"
23
+ end
24
+
25
+ def base_url(req)
26
+ req.POST()['base_url'] || req.referrer || "#{req.scheme}://#{req.host_with_port}"
27
+ end
28
+
29
+ def do_convert(req)
30
+ html = req.POST()['content'] || ""
31
+ width = req.POST()['width'] || 1000
32
+ height = req.POST()['height'] || 700
33
+ css = req.POST()['css'] || ""
34
+
35
+ signature = @shutterbug.convert(base_url(req), html, css, width, height)
36
+ response_url = "#{PNG_PATH}/#{signature}"
37
+ response_text = "<img src='#{response_url}' alt='#{signature}'>"
38
+ return good_response(response_text,'text/plain')
39
+ end
40
+
41
+ def call env
42
+ req = Rack::Request.new(env)
43
+ case req.path
44
+ when CONVERT_REGEX
45
+ do_convert(req)
46
+ when GET_PNG_REGEX
47
+ good_response(@shutterbug.get_png_file($1),'image/png')
48
+ when GET_HTML_REGEX
49
+ good_response(@shutterbug.get_html_file($1),'text/html')
50
+ when JS_PATH
51
+ good_response(@shutterbug.get_shutterbug_file, 'application/javascript')
52
+ else
53
+ skip(env)
54
+ end
55
+ end
56
+
57
+ private
58
+ def good_response(content, type, cache='no-cache')
59
+ headers = {}
60
+ headers['Content-Length'] = content.size.to_s
61
+ headers['Content-Type'] = type
62
+ headers['Cache-Control'] = 'no-cache'
63
+ # content must be enumerable.
64
+ content = [content] if content.kind_of? String
65
+ return [200, headers, content]
66
+ end
67
+
68
+ def log(string)
69
+ puts "★ shutterbug ➙ #{string}"
70
+ end
71
+
72
+ def skip(env)
73
+ # call the applicaiton default
74
+ @app.call env
75
+ end
76
+
77
+ end
78
+ end
@@ -0,0 +1,31 @@
1
+ /*global phantom */
2
+
3
+ var page = require('webpage').create(),
4
+ system = require('system'),
5
+ address, output, size;
6
+
7
+ if (system.args.length < 3 || system.args.length > 5) {
8
+ console.log('Usage: rasterize.js URL filename [paperwidth*paperheight|paperformat] [zoom]');
9
+ console.log(' paper (pdf output) examples: "5in*7.5in", "10cm*20cm", "A4", "Letter"');
10
+ phantom.exit(1);
11
+ } else {
12
+ address = system.args[1];
13
+ output = system.args[2];
14
+ page.viewportSize = { width: 1000, height: 700 };
15
+ if (system.args.length > 3) {
16
+ size = system.args[3].split('*');
17
+ page.viewportSize = { width: size[0], height: size[1] };
18
+ }
19
+
20
+ page.open(address, function (status) {
21
+ if (status !== 'success') {
22
+ console.log('Unable to load the address!');
23
+ phantom.exit();
24
+ } else {
25
+ window.setTimeout(function () {
26
+ page.render(output);
27
+ phantom.exit();
28
+ }, 200);
29
+ }
30
+ });
31
+ }
@@ -0,0 +1,105 @@
1
+ require 'stringio'
2
+ module Shutterbug
3
+ class Service
4
+ class RackFile
5
+ def initialize(file)
6
+ @stream_file = file
7
+ end
8
+
9
+ def open
10
+ @stream_file.open
11
+ @stream_file.rewind
12
+ end
13
+
14
+ def each(&blk)
15
+ @stream_file.each(&blk)
16
+ ensure
17
+ @stream_file.close
18
+ end
19
+
20
+ def size
21
+ @stream_file.size
22
+ end
23
+ end
24
+
25
+ class PngFile < RackFile; end
26
+ class HtmlFile < RackFile; end
27
+
28
+ class JSFile < RackFile
29
+ def initialize(_filename)
30
+ @javascript = File.read(_filename).gsub(/CONVERT_PATH/,Shutterbug::Rackapp::CONVERT_PATH)
31
+ end
32
+ def open
33
+ @stream_file = StringIO.new(@javascript)
34
+ end
35
+ end
36
+
37
+
38
+ PROGRAM = 'phantomjs'
39
+ RASTERIZE_JS = File.join(File.dirname(__FILE__),'rasterize.js')
40
+ SHUTTERBUG_JS = File.join(File.dirname(__FILE__),'shutterbug.js')
41
+
42
+ def document(html, css, url_base)
43
+ date = Time.now.strftime("%Y-%m-%d (%I:%M%p)")
44
+ """
45
+ <!DOCTYPE html>
46
+ <html>
47
+ <head>
48
+ <base href='#{url_base}'>
49
+ <meta content='text/html;charset=utf-8' http-equiv='Content-Type'>
50
+ <title>png from #{url_base} #{date}</title>
51
+ #{css}
52
+ </head>
53
+ <body>
54
+ #{html}
55
+ </body>
56
+ </html>
57
+ """
58
+ end
59
+
60
+ def initialize
61
+ @file_cache = {}
62
+ @js_file = JSFile.new(SHUTTERBUG_JS)
63
+ end
64
+
65
+ def convert(base_url, html, css="", width=1000, height=700)
66
+ html_content = document(html, css, base_url)
67
+ signature = Digest::SHA1.hexdigest(html_content)[0..10]
68
+ return signature if @file_cache[signature]
69
+
70
+ infile = Tempfile.new(['phantom_page','.html'])
71
+ infile_name = infile.path
72
+
73
+ outfile = Tempfile.new(['phantom_render','.png'])
74
+ outfile_name = outfile.path
75
+
76
+ begin
77
+ infile.write(html_content)
78
+ infile.rewind
79
+ %x[#{PROGRAM} #{RASTERIZE_JS} #{infile_name} #{outfile_name} #{width}*#{height}]
80
+ @file_cache[signature] = {'png' => PngFile.new(outfile), 'html' => HtmlFile.new(infile) }
81
+ ensure
82
+ infile.close
83
+ end
84
+ return signature
85
+ end
86
+
87
+ def get_png_file(sha)
88
+ file = @file_cache[sha]['png']
89
+ file.open
90
+ return file
91
+ end
92
+
93
+ def get_html_file(sha)
94
+ file = @file_cache[sha]['html']
95
+ file.open
96
+ return file
97
+ end
98
+
99
+ def get_shutterbug_file
100
+ file = @js_file
101
+ file.open
102
+ return file
103
+ end
104
+ end
105
+ end
@@ -0,0 +1,74 @@
1
+ /*global $ */
2
+ (function(){
3
+ var getBaseUrl = function() {
4
+ var base = window.location.protocol + "//" + window.location.host + "/";
5
+ var root_path = window.location.pathname.split("/").slice(1,-1).join("/");
6
+ return base + root_path;
7
+ };
8
+
9
+ var cloneDomItem =function(elem, elemTag) {
10
+ var width = elem.width();
11
+ var height = elem.height();
12
+ var returnElm = $(elemTag);
13
+
14
+ returnElm.addClass($(elem).attr("class"));
15
+ returnElm.attr("style", $(elem).attr("style"));
16
+ returnElm.css('background', $(elem).css("background"));
17
+ returnElm.attr('width', width);
18
+ returnElm.attr('height', height);
19
+ return returnElm;
20
+ };
21
+
22
+ var getDomSnapshot = function(element, imgDst, callback) {
23
+ var css = $('<div>').append($('link[rel="stylesheet"]').clone()).html();
24
+ var width = element.width();
25
+ var height = element.height();
26
+ var html_content;
27
+
28
+ var replacementImgs = element.find('canvas').map( function(count,elem) {
29
+ var dataUrl = elem.toDataURL('image/png');
30
+ var img = cloneDomItem($(elem),"<img>");
31
+ img.attr('src', dataUrl);
32
+ return img;
33
+ });
34
+
35
+ element = element.clone();
36
+ element.find('canvas').each(function(i,elm) {
37
+ var backgroundDiv = cloneDomItem($(elm),"<div>");
38
+ // we should also add a backing (background) dom element
39
+ // $('canvas.overlay').css('background')
40
+ $(elm).replaceWith(replacementImgs[i]);
41
+ backgroundDiv.insertBefore($(elm));
42
+ });
43
+
44
+ element.css({
45
+ 'top':0,
46
+ 'left':0,
47
+ 'margin':0,
48
+ 'width':width,
49
+ 'height':height
50
+ });
51
+
52
+ html_content = $('<div>').append(element).html();
53
+
54
+ $.ajax({
55
+ url: "CONVERT_PATH",
56
+ type: "POST",
57
+ data: {
58
+ 'content': html_content,
59
+ 'css': css,
60
+ 'width': width,
61
+ 'height': height,
62
+ 'base_url': getBaseUrl()
63
+ }
64
+ }).done(function(msg) {
65
+ if(imgDst) {
66
+ imgDst.html(msg);
67
+ }
68
+ if (callback) {
69
+ callback(msg);
70
+ }
71
+ });
72
+ };
73
+ window.getDomSnapshot = getDomSnapshot;
74
+ })();
@@ -0,0 +1,35 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'shutterbug'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "shutterbug"
8
+ spec.version = Shutterbug::VERSION
9
+ spec.authors = ["Noah Paessel"]
10
+ spec.email = ["knowuh@gmail.com"]
11
+
12
+ spec.description = %q{
13
+ A rack utility that will create and save images (pngs)
14
+ for a part of your web page's current dom. These images
15
+ become available as public '.png' resources in the rack application.
16
+ Currently shutterbug supports HTML, SVG and Canvas elements.
17
+ }
18
+
19
+ spec.summary = %q{ use Shutterbug::Rackapp }
20
+ spec.homepage = ""
21
+ spec.license = "MIT, Simplified BSD, Apache 2.0"
22
+
23
+ spec.files = `git ls-files`.split($/)
24
+ spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
25
+ spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
26
+ spec.require_paths = ["lib"]
27
+
28
+ spec.add_development_dependency "bundler", "~> 1.3"
29
+ spec.add_development_dependency "rake"
30
+ spec.add_development_dependency "rspec"
31
+ spec.add_development_dependency "guard-rspec"
32
+
33
+ spec.add_dependency "rack"
34
+
35
+ end
@@ -0,0 +1,83 @@
1
+ require 'rack'
2
+ RSpec::Matchers.define :be_happy_response do |filetype|
3
+ match do |actual|
4
+ actual[0] == 200 || actual[3] == filetype
5
+ end
6
+ end
7
+
8
+ describe Shutterbug::Rackapp do
9
+ let(:sha) { "542112e" }
10
+ let(:size) { 200 }
11
+ let(:rackfile){ mock :fackfile, :size => size }
12
+ let(:service) { mock :service }
13
+ let(:app) { mock :app }
14
+ let(:post_data) do
15
+ {
16
+ 'content' => "<div class='foo'>foo!</div>",
17
+ 'width' => 1000,
18
+ 'height' => 700,
19
+ 'css' => "",
20
+ 'base_url' => "http://localhost:8080/"
21
+ }
22
+ end
23
+ subject { Shutterbug::Rackapp.new(app) }
24
+
25
+ before(:each) do
26
+ Shutterbug::Service.stub!(:new => service)
27
+ end
28
+
29
+ describe "#do_convert" do
30
+ let(:req) { mock :req, :POST => post_data}
31
+ it "should return a valid image url" do
32
+ service.should_receive(:convert).and_return(sha)
33
+ (resp_code,headers,content) = subject.do_convert(req)
34
+ resp_code.should == 200
35
+ headers['Content-Type'].should == 'text/plain'
36
+ content[0].should match /^<img src='[^']+'[^>]+>$/
37
+ headers['Content-Length'].should == content[0].size.to_s
38
+ end
39
+ end
40
+
41
+ describe "rounting requests in #call" do
42
+ let(:path) { 'bogus' }
43
+ let(:req) { mock(:req, :path => path) }
44
+ before(:each) do
45
+ Rack::Request.stub!(:new).and_return(req)
46
+ end
47
+
48
+ describe "convert route" do
49
+ let(:path) { Shutterbug::Rackapp::CONVERT_PATH }
50
+ let(:image_response) { mock :image_response }
51
+ it "should route #do_convert" do
52
+ subject.should_receive(:do_convert, :with => req).and_return image_response
53
+ subject.call(mock).should == image_response
54
+ end
55
+ end
56
+
57
+ describe "get png route" do
58
+ let(:path) { "#{Shutterbug::Rackapp::PNG_PATH}/#{sha}" }
59
+ it "should route #do_get_png" do
60
+ service.should_receive(:get_png_file, :with => sha).and_return rackfile
61
+ subject.call(mock).should be_happy_response('image/png')
62
+ end
63
+ end
64
+
65
+ describe "get html route" do
66
+ let(:path) { "#{Shutterbug::Rackapp::HTML_PATH}/#{sha}" }
67
+ it "should route #do_get_html" do
68
+ service.should_receive(:get_html_file, :with => sha).and_return rackfile
69
+ subject.call(mock).should be_happy_response('text/html')
70
+ end
71
+ end
72
+
73
+ describe "get shutterbug javascipt route" do
74
+ let(:path) { "#{Shutterbug::Rackapp::JS_PATH}" }
75
+ it "should route #do_get_shutterbug" do
76
+ service.should_receive(:get_shutterbug_file).and_return rackfile
77
+ subject.call(mock).should be_happy_response('application/javascript')
78
+ end
79
+ end
80
+
81
+ end
82
+
83
+ end
@@ -0,0 +1,17 @@
1
+ # This file was generated by the `rspec --init` command. Conventionally, all
2
+ # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
3
+ # Require this file using `require "spec_helper"` to ensure that it is only
4
+ # loaded once.
5
+ #
6
+ # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
7
+ RSpec.configure do |config|
8
+ config.treat_symbols_as_metadata_keys_with_true_values = true
9
+ config.run_all_when_everything_filtered = true
10
+ config.filter_run :focus
11
+
12
+ # Run specs in random order to surface order dependencies. If you find an
13
+ # order dependency and want to debug it, you can fix the order by providing
14
+ # the seed, which is printed after each run.
15
+ # --seed 1234
16
+ config.order = 'random'
17
+ end
metadata ADDED
@@ -0,0 +1,155 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: shutterbug
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.2
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - Noah Paessel
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2013-06-21 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: bundler
16
+ requirement: !ruby/object:Gem::Requirement
17
+ none: false
18
+ requirements:
19
+ - - ~>
20
+ - !ruby/object:Gem::Version
21
+ version: '1.3'
22
+ type: :development
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ none: false
26
+ requirements:
27
+ - - ~>
28
+ - !ruby/object:Gem::Version
29
+ version: '1.3'
30
+ - !ruby/object:Gem::Dependency
31
+ name: rake
32
+ requirement: !ruby/object:Gem::Requirement
33
+ none: false
34
+ requirements:
35
+ - - ! '>='
36
+ - !ruby/object:Gem::Version
37
+ version: '0'
38
+ type: :development
39
+ prerelease: false
40
+ version_requirements: !ruby/object:Gem::Requirement
41
+ none: false
42
+ requirements:
43
+ - - ! '>='
44
+ - !ruby/object:Gem::Version
45
+ version: '0'
46
+ - !ruby/object:Gem::Dependency
47
+ name: rspec
48
+ requirement: !ruby/object:Gem::Requirement
49
+ none: false
50
+ requirements:
51
+ - - ! '>='
52
+ - !ruby/object:Gem::Version
53
+ version: '0'
54
+ type: :development
55
+ prerelease: false
56
+ version_requirements: !ruby/object:Gem::Requirement
57
+ none: false
58
+ requirements:
59
+ - - ! '>='
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ - !ruby/object:Gem::Dependency
63
+ name: guard-rspec
64
+ requirement: !ruby/object:Gem::Requirement
65
+ none: false
66
+ requirements:
67
+ - - ! '>='
68
+ - !ruby/object:Gem::Version
69
+ version: '0'
70
+ type: :development
71
+ prerelease: false
72
+ version_requirements: !ruby/object:Gem::Requirement
73
+ none: false
74
+ requirements:
75
+ - - ! '>='
76
+ - !ruby/object:Gem::Version
77
+ version: '0'
78
+ - !ruby/object:Gem::Dependency
79
+ name: rack
80
+ requirement: !ruby/object:Gem::Requirement
81
+ none: false
82
+ requirements:
83
+ - - ! '>='
84
+ - !ruby/object:Gem::Version
85
+ version: '0'
86
+ type: :runtime
87
+ prerelease: false
88
+ version_requirements: !ruby/object:Gem::Requirement
89
+ none: false
90
+ requirements:
91
+ - - ! '>='
92
+ - !ruby/object:Gem::Version
93
+ version: '0'
94
+ description: ! "\n A rack utility that will create and save images (pngs)\n for
95
+ a part of your web page's current dom. These images\n become available as public
96
+ '.png' resources in the rack application.\n Currently shutterbug supports HTML,
97
+ SVG and Canvas elements.\n "
98
+ email:
99
+ - knowuh@gmail.com
100
+ executables: []
101
+ extensions: []
102
+ extra_rdoc_files: []
103
+ files:
104
+ - .gitignore
105
+ - .rspec
106
+ - .ruby-gemset
107
+ - .ruby-version
108
+ - .travis.yml
109
+ - Gemfile
110
+ - Guardfile
111
+ - LICENSE.md
112
+ - README.md
113
+ - Rakefile
114
+ - lib/shutterbug.rb
115
+ - lib/shutterbug/rackapp.rb
116
+ - lib/shutterbug/rasterize.js
117
+ - lib/shutterbug/service.rb
118
+ - lib/shutterbug/shutterbug.js
119
+ - shutterbug.gemspec
120
+ - spec/shutterbug/rackapp_spec.rb
121
+ - spec/spec_helper.rb
122
+ homepage: ''
123
+ licenses:
124
+ - MIT, Simplified BSD, Apache 2.0
125
+ post_install_message:
126
+ rdoc_options: []
127
+ require_paths:
128
+ - lib
129
+ required_ruby_version: !ruby/object:Gem::Requirement
130
+ none: false
131
+ requirements:
132
+ - - ! '>='
133
+ - !ruby/object:Gem::Version
134
+ version: '0'
135
+ segments:
136
+ - 0
137
+ hash: -514430895198801673
138
+ required_rubygems_version: !ruby/object:Gem::Requirement
139
+ none: false
140
+ requirements:
141
+ - - ! '>='
142
+ - !ruby/object:Gem::Version
143
+ version: '0'
144
+ segments:
145
+ - 0
146
+ hash: -514430895198801673
147
+ requirements: []
148
+ rubyforge_project:
149
+ rubygems_version: 1.8.23
150
+ signing_key:
151
+ specification_version: 3
152
+ summary: use Shutterbug::Rackapp
153
+ test_files:
154
+ - spec/shutterbug/rackapp_spec.rb
155
+ - spec/spec_helper.rb