diff --git a/vendor/plugins/attachment_fu/.gitignore b/vendor/plugins/attachment_fu/.gitignore deleted file mode 100644 index e7d0533..0000000 --- a/vendor/plugins/attachment_fu/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -test/amazon_s3.yml -test/debug.log diff --git a/vendor/plugins/attachment_fu/CHANGELOG b/vendor/plugins/attachment_fu/CHANGELOG index 33f5d7e..83a0f3a 100644 --- a/vendor/plugins/attachment_fu/CHANGELOG +++ b/vendor/plugins/attachment_fu/CHANGELOG @@ -1,3 +1,52 @@ +* Aug 22, 2013 * +* Added cache-control header option and Ruby 1.9 fix for S3 from tricycle + +* Aug 21, 2013 * +* Added S3 :encrypted_storage option support from cschulte22 + +* Jul 5, 2013 +* Pull in changes from lchimonji10 to reformat README to RDoc format + +* Apr 10, 2013 * +* Ruby 2 compatibility fix +* Removed some lingering occurrences of RAILS_ROOT and RAILS_ENV +* clean up of gemspec file +* no longer package unnecessary files like the test files + +* Mar 12, 2013 * +* Pull in changes from https://github.com/aalong/attachment_fu to use Ruby 1.9.2 Tempfile naming strategy to fix conflicts with Sprockets (see https://github.com/aalong/attachment_fu/commit/938ec3b8597fbf82b1de8c98de12c4688463450a) + +* Feb 19, 2013 * +* Pull in changes from https://github.com/itkin/attachment_fu fork to fix mini magick + +* Nov 15, 2012 * +* Removed 'crop:' option as already included when prefixing geometry with a 'c'. Add note to docs. +* Added option to sharpen resized images ':sharpen_on_resize' + +* Oct 26, 2012 * +* Merged with https://github.com/tdd/attachment_fu fork to include GEM support for use in Rails 3.2, and bumped version to 3.2.x to indicate Rails 3.2 support. + +* Oct 25, 2012 * +* Fix to support Ruby 1.9.3 +* Image cropping support (append 'crop:' to desired file size when resizing) + +* Mar 15, 2010 * +* Added a symbol syntax for parent-type-based size spec: calls the corresponding method on the current asset instance to + get a Hash of required thumbnails. Lets us dynamically specify what would otherwise be hard-coded, which is useful + when the set of thumbnails for a given parent type varies depending on the usage context. + +* Aug 6, 2009 * +* JPEG quality control finalized across processors (although CoreImage applies it in a rather fuzzy-logic way), with tests. + +* Aug 4, 2009 * +* Supports the :aspect/'!' geometry flag in all processors + (thanks to http://www.deepcalm.com/writing/cropped-thumbnails-in-attachment_fu-using-imagescience) +* JPEG quality control on thumbnailing/resizing (still buggy on Rmagick/MiniMagick though). +* Moves from GIF to PNG regardless of the source file extension's case (used to require lowercase) +* Auto-orients image (if EXIF suggests it) prior to processing with RMagickProcessor +* Fixes non-image upload tests (both regular files and Merb files) +* Fixes obsolete failures on RMagick tests (aspect_ratio tested but not initialized anymore due to new callback architecture + * Apr 17 2008 * * amazon_s3.yml is now passed through ERB before being passed to AWS::S3 [François Beausoleil] diff --git a/vendor/plugins/attachment_fu/Gemfile b/vendor/plugins/attachment_fu/Gemfile new file mode 100644 index 0000000..ad69a95 --- /dev/null +++ b/vendor/plugins/attachment_fu/Gemfile @@ -0,0 +1,13 @@ +source 'http://rubygems.org' + + +group :test, :development do + gem 'rails', '~> 3.2' + gem 'sqlite3' + gem 'pothoven-attachment_fu', :path => '.' + gem 'rmagick' + gem 'core_image' + gem 'mini_magick' + gem 'aws-s3', :require => 'aws/s3' + gem 'test-unit' +end diff --git a/vendor/plugins/attachment_fu/Gemfile.lock b/vendor/plugins/attachment_fu/Gemfile.lock new file mode 100644 index 0000000..48fbf26 --- /dev/null +++ b/vendor/plugins/attachment_fu/Gemfile.lock @@ -0,0 +1,109 @@ +PATH + remote: . + specs: + pothoven-attachment_fu (3.2.10) + +GEM + remote: http://rubygems.org/ + specs: + actionmailer (3.2.14) + actionpack (= 3.2.14) + mail (~> 2.5.4) + actionpack (3.2.14) + activemodel (= 3.2.14) + activesupport (= 3.2.14) + builder (~> 3.0.0) + erubis (~> 2.7.0) + journey (~> 1.0.4) + rack (~> 1.4.5) + rack-cache (~> 1.2) + rack-test (~> 0.6.1) + sprockets (~> 2.2.1) + activemodel (3.2.14) + activesupport (= 3.2.14) + builder (~> 3.0.0) + activerecord (3.2.14) + activemodel (= 3.2.14) + activesupport (= 3.2.14) + arel (~> 3.0.2) + tzinfo (~> 0.3.29) + activeresource (3.2.14) + activemodel (= 3.2.14) + activesupport (= 3.2.14) + activesupport (3.2.14) + i18n (~> 0.6, >= 0.6.4) + multi_json (~> 1.0) + arel (3.0.2) + aws-s3 (0.6.3) + builder + mime-types + xml-simple + builder (3.0.4) + core_image (0.0.3.5) + erubis (2.7.0) + hike (1.2.3) + i18n (0.6.5) + journey (1.0.4) + json (1.8.0) + mail (2.5.4) + mime-types (~> 1.16) + treetop (~> 1.4.8) + mime-types (1.24) + mini_magick (3.6.0) + subexec (~> 0.2.1) + multi_json (1.7.9) + polyglot (0.3.3) + rack (1.4.5) + rack-cache (1.2) + rack (>= 0.4) + rack-ssl (1.3.3) + rack + rack-test (0.6.2) + rack (>= 1.0) + rails (3.2.14) + actionmailer (= 3.2.14) + actionpack (= 3.2.14) + activerecord (= 3.2.14) + activeresource (= 3.2.14) + activesupport (= 3.2.14) + bundler (~> 1.0) + railties (= 3.2.14) + railties (3.2.14) + actionpack (= 3.2.14) + activesupport (= 3.2.14) + rack-ssl (~> 1.3.2) + rake (>= 0.8.7) + rdoc (~> 3.4) + thor (>= 0.14.6, < 2.0) + rake (10.1.0) + rdoc (3.12.2) + json (~> 1.4) + rmagick (2.13.2) + sprockets (2.2.2) + hike (~> 1.2) + multi_json (~> 1.0) + rack (~> 1.0) + tilt (~> 1.1, != 1.3.0) + sqlite3 (1.3.8) + subexec (0.2.3) + test-unit (2.5.5) + thor (0.18.1) + tilt (1.4.1) + treetop (1.4.15) + polyglot + polyglot (>= 0.3.1) + tzinfo (0.3.37) + xml-simple (1.1.2) + +PLATFORMS + ruby + +DEPENDENCIES + aws-s3 + core_image + mini_magick + pothoven-attachment_fu! + rails (~> 3.2) + rmagick + sqlite3 + test-unit diff --git a/vendor/plugins/attachment_fu/LICENSE b/vendor/plugins/attachment_fu/LICENSE new file mode 100644 index 0000000..b2d8f02 --- /dev/null +++ b/vendor/plugins/attachment_fu/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2009 rick olson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/plugins/attachment_fu/README b/vendor/plugins/attachment_fu/README index 8db7ba2..baa78c2 100644 --- a/vendor/plugins/attachment_fu/README +++ b/vendor/plugins/attachment_fu/README @@ -9,12 +9,13 @@ attachment_fu functionality attachment_fu facilitates file uploads in Ruby on Rails. There are a few storage options for the actual file data, but the plugin always at a minimum stores metadata for each file in the database. -There are three storage options for files uploaded through attachment_fu: +There are four storage options for files uploaded through attachment_fu: File system Database file Amazon S3 + Rackspace (Mosso) Cloud Files -Each method of storage many options associated with it that will be covered in the following section. Something to note, however, is that the Amazon S3 storage requires you to modify config/amazon_s3.yml and the Database file storage requires an extra table. +Each method of storage many options associated with it that will be covered in the following section. Something to note, however, is that the Amazon S3 storage requires you to modify config/amazon_s3.yml, the Rackspace Cloud Files storage requires you to modify config/rackspace_cloudfiles.yml, and the Database file storage requires an extra table. attachment_fu models @@ -41,13 +42,18 @@ has_attachment(options = {}) # This option need only be included if you want thumbnailing. :thumbnail_class # Set which model class to use for thumbnails. # This current attachment class is used by default. - :path_prefix # path to store the uploaded files. - # Uses public/#{table_name} by default for the filesystem, and just #{table_name} for the S3 backend. + :path_prefix # Path to store the uploaded files in. + # Uses public/#{table_name} by default for the filesystem, and just #{table_name} for the S3 and Cloud Files backend. # Setting this sets the :storage to :file_system. + :partition # Whether to partiton files in directories like /0000/0001/image.jpg. Default is true. Only applicable to the :file_system backend. :storage # Specifies the storage system to use.. - # Defaults to :db_file. Options are :file_system, :db_file, and :s3. + # Defaults to :db_file. Options are :file_system, :db_file, :s3, and :cloud_files. + :cloudfront # If using S3 for storage, this option allows for serving the files via Amazon CloudFront. + # Defaults to false. :processor # Sets the image processor to use for resizing of the attached image. # Options include ImageScience, Rmagick, and MiniMagick. Default is whatever is installed. + :uuid_primary_key # If your model's primary key is a 128-bit UUID in hexadecimal format, then set this to true. + :association_options # attachment_fu automatically defines associations with thumbnails with has_many and belongs_to. If there are any additional options that you want to pass to these methods, then specify them here. Examples: @@ -60,10 +66,12 @@ has_attachment(options = {}) has_attachment :thumbnails => { :thumb => [50, 50], :geometry => 'x50' } has_attachment :storage => :file_system, :path_prefix => 'public/files' has_attachment :storage => :file_system, :path_prefix => 'public/files', - :content_type => :image, :resize_to => [50,50] + :content_type => :image, :resize_to => [50,50], :partition => false has_attachment :storage => :file_system, :path_prefix => 'public/files', :thumbnails => { :thumb => [50, 50], :geometry => 'x50' } has_attachment :storage => :s3 + has_attachment :store => :s3, :cloudfront => true + has_attachment :storage => :cloud_files validates_as_attachment This method prevents files outside of the valid range (:min_size to :max_size, or the :size range) from being saved. It does not however, halt the upload of such files. They will be uploaded into memory regardless of size before validation. @@ -119,7 +127,7 @@ There are two parts of the upload form that differ from typical usage. Example: <%= form.file_field :uploaded_data %> -Displaying uploaded images is made easy by the public_filename method of the ActiveRecord attachment objects using file system and s3 storage. +Displaying uploaded images is made easy by the public_filename method of the ActiveRecord attachment objects using file system, s3, and Cloud Files storage. public_filename(thumbnail = nil) Returns the public path to the file. If a thumbnail prefix is specified it will return the public file path to the corresponding thumbnail. @@ -160,3 +168,26 @@ Example in controller: render :action => :new end end + +attachement_fu scripting +==================================== + +You may wish to import a large number of images or attachments. +The following example shows how to upload a file from a script. + +#!/usr/bin/env ./script/runner + +# required to use ActionController::TestUploadedFile +require 'action_controller' +require 'action_controller/test_process.rb' + +path = "./public/images/x.jpg" + +# mimetype is a string like "image/jpeg". One way to get the mimetype for a given file on a UNIX system +# mimetype = `file -ib #{path}`.gsub(/\n/,"") + +mimetype = "image/jpeg" + +# This will "upload" the file at path and create the new model. +@attachable = AttachmentMetadataModel.new(:uploaded_data => ActionController::TestUploadedFile.new(path, mimetype)) +@attachable.save diff --git a/vendor/plugins/attachment_fu/README.rdoc b/vendor/plugins/attachment_fu/README.rdoc new file mode 100644 index 0000000..35578ee --- /dev/null +++ b/vendor/plugins/attachment_fu/README.rdoc @@ -0,0 +1,352 @@ += attachment-fu + +attachment_fu is a plugin by Rick Olson (aka technoweenie +http://techno-weenie.net) and is the successor to acts_as_attachment. To get a +basic run-through of its capabilities, check out {Mike Clark's +tutorial}[http://clarkware.com/cgi/blosxom/2007/02/24#FileUploadFu]. + += attachment_fu functionality + +attachment_fu facilitates file uploads in Ruby on Rails. There are a few +storage options for the actual file data, but the plugin always at a minimum +stores metadata for each file in the database. + +There are four storage options for files uploaded through attachment_fu: + +* File system +* Database file +* Amazon S3 +* Rackspace (Mosso) Cloud Files + +Each method of storage many options associated with it that will be covered in +the following section. Something to note, however, is that the Amazon S3 storage +requires you to modify +config/amazon_s3.yml+, the Rackspace Cloud Files storage +requires you to modify +config/rackspace_cloudfiles.yml+, and the Database file +storage requires an extra table. + += attachment_fu models + +For all three of these storage options a table of metadata is required. This +table will contain information about the file (hence the 'meta') and its +location. This table has no restrictions on naming, unlike the extra table +required for database storage, which must have a table name of +db_files+ (and +by convention a model of +DbFile+). + +Two methods are available to models: +has_attachment+ and ++validates_as_attachment+. + +== has_attachment(options = {}) + +This method accepts the options in a hash: + +[:content_type] + Allowed content types. + + By default, all content types are allowed. Use +:image+ to allow all + standard image types. + +[:min_size] + Minimum file size. + + By default, set to +1.byte+. + +[:max_size] + Maximum file size. + + By default, set to +1.megabyte+. + +[:size] + Minimum and maximum file size. + + By default, set to +1..1.megabyte+. Overrides +:min_size+ and + +:max_size+. + +[:resize_to] + Used by RMagick. + + Tells RMagick how to resize images. Pass either an array specifying + width and height or a geometry string. Prefixing the geometry string + with a 'c' will crop the image to the specified size. + +[:sharpen_on_resize] + Used by RMagick. + + If set to true, images are sharpened after being resized. + +[:thumbnails] + A set of thumbnails to generate. + + This accepts a hash of filename suffixes and RMagick resizing options. This + option need only be included if you want thumbnailing. + + If you have a polymorphic parent relationship, you can provide + parent-type-specific thumbnail settings by using a pair with the type string + as key and a Hash of thumbnail definitions, or a method symbol, as value. + The method symbol will call the named method in order to get a + dynamically-built Hash of thumbnail definitions, which gives you full + flexibility. AttachmentFu automatically detects your first polymorphic + +belongs_to+ relationship. + +[:thumbnail_class] + Which model class to use for thumbnails. + + By default, the current attachment class is used. + +[:jpeg_quality] + JPEG quality settings for thumbnail resizes. + + Arguments can be in multiple formats: + + * Integer from 0 (basically crap) to 100 (basically lossless, fat files). + + * When relying on tdd-image_science, you can also use one of its +JPEG_xxx+ + constants for predefined ratios/settings. + + * You can also use a Hash, with keys being either thumbnail symbols (I + repeat: _symbols_) or surface boundaries. A surface boundary is a string + starting with either '<' or '>=', followed by a number of pixels. This + lets you specify per-thumbnail or per-general-thumbnail-"size" JPEG + qualities. (which can be useful when you have a _lot_ of thumbnail + options). Surface example: {'<2000' => 90, '>=2000' => 75}. + + Defaults vary depending on the processor (ImageScience: 100%, + Rmagick/MiniMagick/Gd2: 75%, CoreImage: auto-adjust). Note that only + tdd-image_science (available from GitHub) currently supports explicit JPEG + quality; the default image_science currently forces 100%. + +[:path_prefix] + Path to store the uploaded files in. Uses public/#{table_name} + by default for the filesystem, and just #{table_name} for the + S3 and Cloud Files backend. Setting this sets the +:storage+ to + +:file_system+. + +[:partition] + Whether to partiton files in directories like +/0000/0001/image.jpg+. + Default is true. Only applicable to the +:file_system+ backend. + +[:storage] + Specifies the storage system to use. Defaults to +:db_file+. Options are + +:file_system+, +:db_file+, +:s3+, and +:cloud_files+. + +[:cloudfront] + If using S3 for storage, this option allows for serving the files via Amazon + CloudFront. Defaults to false. + +[:processor] + Sets the image processor to use for resizing of the attached image. Options + include ImageScience, Rmagick, MiniMagick, Gd2 and CoreImage. Default is + whatever is installed. + +[:uuid_primary_key] + If your model's primary key is a 128-bit UUID in hexadecimal format, then + set this to true. + +[:association_options] + attachment_fu automatically defines associations with thumbnails with + +has_many+ and +belongs_to+. If there are any additional options that you + want to pass to these methods, then specify them here. + +Examples: + + has_attachment(content_type: 'application/pdf') + has_attachment( + content_type: ['application/pdf', 'application/msword', 'text/plain'] + ) + has_attachment(content_type: ['application/pdf', :image], resize_to: 'x50') + has_attachment(content_type: :image, resize_to: [50,50]) + has_attachment(max_size: 1.kilobyte) + has_attachment(size: 1.megabyte..2.megabytes) + has_attachment(storage: :cloud_files) + has_attachment(storage: :file_system, path_prefix: 'public/files') + has_attachment( + storage: :file_system, + path_prefix: 'public/files', + content_type: :image, + resize_to: [50, 50], + partition: false + ) + has_attachment( + storage: :file_system, + path_prefix: 'public/files', + thumbnails: {thumb: [50, 50], geometry: 'x50'} + ) + has_attachment(storage: :s3) + has_attachment(store: :s3, cloudfront: true) + has_attachment(thumbnails: {thumb: [50, 50], geometry: 'x50'}) + + # Let's say we have a polymorphic belongs_to, e.g. called 'imageable', where + # imageable_type (or whatever the :foreign_type option was set to) can be, + # among other things, 'Product', 'User' or 'Editorial', each of which should + # have extra thumbnails: + + has_attachment(thumbnails: { + editorials: {fullsize: '150x100>'}, + geometry: 'x50', + products: {large_thumb: '169x169!', zoomed: '500x500>'}, + thumb: [50, 50], + users: {avatar: '64x64!'} + }) + + # JPEG qualities… + + has_attachment(jpeg_quality: 75) + has_attachment(jpeg_quality: 80 | ImageScience::JPEG_PROGRESSIVE) + has_attachment( + thumbnails: {thumb: [50, 50], geometry: 'x50'}, + jpeg_quality: {'<2000' => 90, '>=2000' => 75} + ) + has_attachment( + thumbnails: {thumb: [50, 50], geometry: 'x50'}, + jpeg_quality: {nil => 75, thumb: 90, geometry: 90} + ) + +== validates_as_attachment + +This method prevents files outside of the valid range (+:min_size+ to ++:max_size+, or the +:size+ range) from being saved. It does not however, halt +the upload of such files. They will be uploaded into memory regardless of size +before validation. + +To perform this validation, simply add +validates_as_attachment+ to your model. + += attachment_fu migrations + +Fields for attachment_fu metadata tables… + +In general: + + size, :integer # file size in bytes + content_type, :string # mime type, ex: application/mp3 + filename, :string # sanitized filename + +That reference images: + + height, :integer # in pixels + width, :integer # in pixels + +That reference images that will be thumbnailed: + + parent_id, :integer # id of parent image (on the same table, a + # self-referencing foreign-key). Only populated if + # the current object is a thumbnail. + thumbnail, :string # The type of thumbnail this attachment record + # describes. Only populated if the current object is + # a thumbnail. Example: + # + # (In Model 'Avatar') + # has_attachment( + # :content_type => :image, + # :storage => :file_system, + # :max_size => 500.kilobytes, + # :resize_to => '320x200>', + # :thumbnails => { + # :small => '10x10>', + # :thumb => '100x100>' + # } + # ) + # + # (Elsewhere) + # @user.avatar.thumbnails.first.thumbnail # => 'small' + # + db_file_id, :integer # ID of the file in the database (foreign key) that + # reference files stored in the database (:db_file). + +Field for attachment_fu +db_files+ table: + + data, :binary # binary file data, for use in database file storage + += attachment_fu views + +There are two main views tasks that will be directly affected by attachment_fu: +upload forms and displaying uploaded images. + +There are two parts of the upload form that differ from typical usage. + +1. Include multipart: true in the html options of the +form_for+ + tag. Example: + + <%= + form_for( + :attachment_metadata, + url: {action: "create"}, + html: {multipart: true} + ) do |form| + %> + +2. Use the +file_field+ helper with +:uploaded_data+ as the field name. Example: + + <%= form.file_field(:uploaded_data) %> + +Displaying uploaded images is made easy by the +public_filename+ method of the +ActiveRecord attachment objects using file system, s3, and Cloud Files storage. + +== public_filename(thumbnail = nil) + +Returns the public path to the file. If a thumbnail prefix is specified it will +return the public file path to the corresponding thumbnail. Examples: + + attachment_obj.public_filename #=> /attachments/2/file.jpg + attachment_obj.public_filename(:thumb) #=> /attachments/2/file_thumb.jpg + attachment_obj.public_filename(:small) #=> /attachments/2/file_small.jpg + +When serving files from database storage, doing more than simply downloading the +file is beyond the scope of this document. + += attachment_fu controllers + +There are two considerations to take into account when using attachment_fu in +controllers. + +The first is when the files have no publicly accessible path and need to be +downloaded through an action. Example: + + def readme + send_file( + '/path/to/readme.txt', + type: 'plain/text', + disposition: 'inline' + ) + end + +See the possible values for +send_file+ for reference. + +The second is when saving the file when submitted from a form. Example: + +In a view: + + <%= form.file_field(:attachable, :uploaded_data) %> + +In a controller: + + def create + @attachable_file = AttachmentMetadataModel.new(params[:attachable]) + if @attachable_file.save + flash[:notice] = 'Attachment was successfully created.' + redirect_to(attachable_url(@attachable_file)) + else + redirect_to(action: 'new') + end + end + += attachment_fu scripting + +You may wish to import a large number of images or attachments. The following +example shows how to upload a file from a script. + + #!/usr/bin/env ./script/runner + + # required to use ActionController::TestUploadedFile + require 'action_controller' + require 'action_controller/test_process.rb' + + path = "./public/images/x.jpg" + + # `mimetype` is a string like "image/jpeg". One way to get the mimetype for + # a given file on a UNIX system: mimetype = `file -ib #{path}`.gsub(/\n/,"") + mimetype = "image/jpeg" + + # This will "upload" the file at path and create the new model. + @attachable = AttachmentMetadataModel.new( + uploaded_data: ActionController::TestUploadedFile.new(path, mimetype) + ) + @attachable.save diff --git a/vendor/plugins/attachment_fu/Rakefile b/vendor/plugins/attachment_fu/Rakefile index faa7ad1..f90a073 100644 --- a/vendor/plugins/attachment_fu/Rakefile +++ b/vendor/plugins/attachment_fu/Rakefile @@ -1,6 +1,6 @@ require 'rake' require 'rake/testtask' -require 'rake/rdoctask' +require 'rdoc/task' desc 'Default: run unit tests.' task :default => :test @@ -16,6 +16,7 @@ desc 'Generate documentation for the attachment_fu plugin.' Rake::RDocTask.new(:rdoc) do |rdoc| rdoc.rdoc_dir = 'rdoc' rdoc.title = 'ActsAsAttachment' - rdoc.rdoc_files.include('README') + rdoc.options << '--line-numbers --inline-source' + rdoc.rdoc_files.include('README.rdoc') rdoc.rdoc_files.include('lib/**/*.rb') end diff --git a/vendor/plugins/attachment_fu/amazon_s3.yml.tpl b/vendor/plugins/attachment_fu/amazon_s3.yml.tpl index 81cb807..5c585e7 100644 --- a/vendor/plugins/attachment_fu/amazon_s3.yml.tpl +++ b/vendor/plugins/attachment_fu/amazon_s3.yml.tpl @@ -2,13 +2,16 @@ development: bucket_name: appname_development access_key_id: secret_access_key: + distribution_domain: XXXX.cloudfront.net test: bucket_name: appname_test access_key_id: secret_access_key: + distribution_domain: XXXX.cloudfront.net production: bucket_name: appname access_key_id: secret_access_key: + distribution_domain: XXXX.cloudfront.net diff --git a/vendor/plugins/attachment_fu/attachment_fu.gemspec b/vendor/plugins/attachment_fu/attachment_fu.gemspec new file mode 100644 index 0000000..9cbcfd0 --- /dev/null +++ b/vendor/plugins/attachment_fu/attachment_fu.gemspec @@ -0,0 +1,23 @@ +# -*- encoding: utf-8 -*- + +Gem::Specification.new do |s| + s.name = %q{pothoven-attachment_fu} + s.authors = ["Rick Olson", "Steven Pothoven"] + s.summary = %q{attachment_fu as a gem} + s.description = %q{This is a fork of Rick Olson's attachment_fu adding Ruby 1.9 and Rails 3.2 support as well as some other enhancements.} + s.email = %q{steven@pothoven.net} + s.homepage = %q{http://github.com/pothoven/attachment_fu} + s.version = "3.2.10" + s.date = %q{2013-08-22} + + s.files = Dir.glob("{lib,vendor}/**/*") + %w( CHANGELOG LICENSE README.rdoc amazon_s3.yml.tpl rackspace_cloudfiles.yml.tpl ) + s.extra_rdoc_files = ["README.rdoc"] + s.rdoc_options = ["--inline-source", "--charset=UTF-8"] + s.require_paths = ["lib"] + s.rubyforge_project = "nowarning" + s.rubygems_version = %q{1.3.5} + + if s.respond_to? :specification_version then + s.specification_version = 2 + end +end diff --git a/vendor/plugins/attachment_fu/config/database.yml b/vendor/plugins/attachment_fu/config/database.yml new file mode 100644 index 0000000..2cfeb7a --- /dev/null +++ b/vendor/plugins/attachment_fu/config/database.yml @@ -0,0 +1,3 @@ +test: + adapter: sqlite3 + database: ":memory:" diff --git a/vendor/plugins/attachment_fu/config/environment.rb b/vendor/plugins/attachment_fu/config/environment.rb new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/vendor/plugins/attachment_fu/config/environment.rb diff --git a/vendor/plugins/attachment_fu/init.rb b/vendor/plugins/attachment_fu/init.rb index dadcb07..c377063 100644 --- a/vendor/plugins/attachment_fu/init.rb +++ b/vendor/plugins/attachment_fu/init.rb @@ -1,13 +1,3 @@ -require 'tempfile' - -Tempfile.class_eval do - # overwrite so tempfiles use the extension of the basename. important for rmagick and image science - def make_tmpname(basename, n) - ext = nil - sprintf("%s%d-%d%s", basename.to_s.gsub(/\.\w+$/) { |s| ext = s; '' }, $$, n, ext) - end -end - require 'geometry' ActiveRecord::Base.send(:extend, Technoweenie::AttachmentFu::ActMethods) Technoweenie::AttachmentFu.tempfile_path = ATTACHMENT_FU_TEMPFILE_PATH if Object.const_defined?(:ATTACHMENT_FU_TEMPFILE_PATH) diff --git a/vendor/plugins/attachment_fu/install.rb b/vendor/plugins/attachment_fu/install.rb index 2938164..1b75ff8 100644 --- a/vendor/plugins/attachment_fu/install.rb +++ b/vendor/plugins/attachment_fu/install.rb @@ -2,4 +2,6 @@ require 'fileutils' s3_config = File.dirname(__FILE__) + '/../../../config/amazon_s3.yml' FileUtils.cp File.dirname(__FILE__) + '/amazon_s3.yml.tpl', s3_config unless File.exist?(s3_config) -puts IO.read(File.join(File.dirname(__FILE__), 'README')) \ No newline at end of file +cloudfiles_config = File.dirname(__FILE__) + '/../../../config/rackspace_cloudfiles.yml' +FileUtils.cp File.dirname(__FILE__) + '/rackspace_cloudfiles.yml.tpl', cloudfiles_config unless File.exist?(cloudfiles_config) +puts IO.read(File.join(File.dirname(__FILE__), 'README.rdoc')) diff --git a/vendor/plugins/attachment_fu/lib/geometry.rb b/vendor/plugins/attachment_fu/lib/geometry.rb index 2d6e381..1f1c2fa 100644 --- a/vendor/plugins/attachment_fu/lib/geometry.rb +++ b/vendor/plugins/attachment_fu/lib/geometry.rb @@ -1,9 +1,9 @@ # This Geometry class was yanked from RMagick. However, it lets ImageMagick handle the actual change_geometry. -# Use #new_dimensions_for to get new dimensons +# Use #new_dimensions_for to get new dimensions # Used so I can use spiffy RMagick geometry strings with ImageScience class Geometry - # ! and @ are removed until support for them is added - FLAGS = ['', '%', '<', '>']#, '!', '@'] + # @ is removed until support for them is added + FLAGS = ['', '%', '<', '>', '!']#, '@'] RFLAGS = { '%' => :percent, '!' => :aspect, '<' => :>, @@ -25,7 +25,7 @@ class Geometry end # Construct an object from a geometry string - RE = /\A(\d*)(?:x(\d+))?([-+]\d+)?([-+]\d+)?([%!<>@]?)\Z/ + RE = /\A(\d*)(?:x(\d+)?)?([-+]\d+)?([-+]\d+)?([%!<>@]?)\Z/ def self.from_s(str) raise(ArgumentError, "no geometry string specified") unless str @@ -59,6 +59,9 @@ class Geometry scale_y = @height.zero? ? @width : @height new_width = scale_x.to_f * (orig_width.to_f / 100.0) new_height = scale_y.to_f * (orig_height.to_f / 100.0) + when :aspect + new_width = @width unless @width.nil? + new_height = @height unless @height.nil? when :<, :>, nil scale_factor = if new_width.zero? || new_height.zero? @@ -76,7 +79,7 @@ class Geometry new_height = orig_height if @flag && orig_height.send(@flag, new_height) end - [new_width, new_height].collect! { |v| v.round } + [new_width, new_height].collect! { |v| [v.round, 1].max } end end @@ -90,4 +93,4 @@ class Array geometry = Geometry.from_s(geometry) if geometry.is_a?(String) geometry.new_dimensions_for first, last end -end \ No newline at end of file +end diff --git a/vendor/plugins/attachment_fu/lib/pothoven-attachment_fu.rb b/vendor/plugins/attachment_fu/lib/pothoven-attachment_fu.rb new file mode 100644 index 0000000..adb1e62 --- /dev/null +++ b/vendor/plugins/attachment_fu/lib/pothoven-attachment_fu.rb @@ -0,0 +1,12 @@ +class Engine < Rails::Engine + # Mimic old vendored plugin behavior, attachment_fu/lib is autoloaded. + config.autoload_paths << File.expand_path("..", __FILE__) + + initializer "attachment_fu" do + require 'geometry' + + ActiveRecord::Base.send(:extend, Technoweenie::AttachmentFu::ActMethods) + Technoweenie::AttachmentFu.tempfile_path = ATTACHMENT_FU_TEMPFILE_PATH if Object.const_defined?(:ATTACHMENT_FU_TEMPFILE_PATH) + FileUtils.mkdir_p Technoweenie::AttachmentFu.tempfile_path + end +end diff --git a/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu.rb b/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu.rb index 77fab8a..d9a8492 100644 --- a/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu.rb +++ b/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu.rb @@ -2,7 +2,37 @@ module Technoweenie # :nodoc: module AttachmentFu # :nodoc: @@default_processors = %w(ImageScience Rmagick MiniMagick Gd2 CoreImage) @@tempfile_path = File.join(Rails.root, 'tmp', 'attachment_fu') - @@content_types = ['image/jpeg', 'image/pjpeg', 'image/gif', 'image/png', 'image/x-png', 'image/jpg'] + @@content_types = [ + 'image/jpeg', + 'image/pjpeg', + 'image/jpg', + 'image/gif', + 'image/png', + 'image/x-png', + 'image/jpg', + 'image/x-ms-bmp', + 'image/bmp', + 'image/x-bmp', + 'image/x-bitmap', + 'image/x-xbitmap', + 'image/x-win-bitmap', + 'image/x-windows-bmp', + 'image/ms-bmp', + 'application/bmp', + 'application/x-bmp', + 'application/x-win-bitmap', + 'application/preview', + 'image/jp_', + 'application/jpg', + 'application/x-jpg', + 'image/pipeg', + 'image/vnd.swiftview-jpeg', + 'image/x-xbitmap', + 'application/png', + 'application/x-png', + 'image/gi_', + 'image/x-citrix-pjpeg' + ] mattr_reader :content_types, :tempfile_path, :default_processors mattr_writer :tempfile_path @@ -15,12 +45,32 @@ module Technoweenie # :nodoc: # * :min_size - Minimum size allowed. 1 byte is the default. # * :max_size - Maximum size allowed. 1.megabyte is the default. # * :size - Range of sizes allowed. (1..1.megabyte) is the default. This overrides the :min_size and :max_size options. - # * :resize_to - Used by RMagick to resize images. Pass either an array of width/height, or a geometry string. - # * :thumbnails - Specifies a set of thumbnails to generate. This accepts a hash of filename suffixes and RMagick resizing options. + # * :resize_to - Used by RMagick to resize images. Pass either an array of width/height, or a geometry string. Prefix geometry string with 'c' to crop image, ex. 'c100x100' + # * :sharpen_on_resize - When using RMagick, setting to true will sharpen images after resizing. + # * :jpeg_quality - Used to provide explicit JPEG quality for thumbnail/resize saves. Can have multiple formats: + # * Integer from 0 (basically crap) to 100 (basically lossless, fat files). + # * When relying on ImageScience, you can also use one of its +JPEG_xxx+ constants for predefined ratios/settings. + # * You can also use a Hash, with keys being either thumbnail symbols (I repeat: _symbols_) or surface boundaries. + # A surface boundary is a string starting with either '<' or '>=', followed by a number of pixels. This lets you + # specify per-thumbnail or per-general-thumbnail-"size" JPEG qualities. (which can be useful when you have a + # _lot_ of thumbnail options). Surface example: +{ '<2000' => 90, '>=2000' => 75 }+. + # Defaults vary depending on the processor (ImageScience: 100%, Rmagick/MiniMagick/Gd2: 75%, + # CoreImage: auto-adjust). Note that only tdd-image_science (available from GitHub) currently supports explicit JPEG quality; + # the default image_science currently forces 100%. + # * :thumbnails - Specifies a set of thumbnails to generate. This accepts a hash of filename suffixes and + # RMagick resizing options. If you have a polymorphic parent relationship, you can provide parent-type-specific + # thumbnail settings by using a pair with the type string as key and a Hash of thumbnail definitions as value. + # AttachmentFu automatically detects your first polymorphic +belongs_to+ relationship. # * :thumbnail_class - Set what class to use for thumbnails. This attachment class is used by default. # * :path_prefix - path to store the uploaded files. Uses public/#{table_name} by default for the filesystem, and just #{table_name} # for the S3 backend. Setting this sets the :storage to :file_system. + # * :storage - Use :file_system to specify the attachment data is stored with the file system. Defaults to :db_system. + # * :cloundfront - Set to true if you are using S3 storage and want to serve the files through CloudFront. You will need to + # set a distribution domain in the amazon_s3.yml config file. Defaults to false + # * :bucket_key - Use this to specify a different bucket key other than :bucket_name in the amazon_s3.yml file. This allows you to use + # different buckets for different models. An example setting would be :image_bucket and the you would need to define the name of the corresponding + # bucket in the amazon_s3.yml file. # * :keep_profile By default image EXIF data will be stripped to minimize image size. For small thumbnails this proivides important savings. Picture quality is not affected. Set to false if you want to keep the image profile as is. ImageScience will allways keep EXIF data. # @@ -46,7 +96,9 @@ module Technoweenie # :nodoc: options[:thumbnails] ||= {} options[:thumbnail_class] ||= self options[:s3_access] ||= :public_read - options[:content_type] = [options[:content_type]].flatten.collect! { |t| t == :image ? Technoweenie::AttachmentFu.content_types : t }.flatten unless options[:content_type].nil? + options[:cloudfront] ||= false + options[:content_type] = [options[:content_type]].flatten.collect! { |t| t == :image ? ::Technoweenie::AttachmentFu.content_types : t }.flatten unless options[:content_type].nil? + options[:cache_control] ||= "max-age=315360000" # 10 years unless options[:thumbnails].is_a?(Hash) raise ArgumentError, ":thumbnails option should be a hash: e.g. :thumbnails => { :foo => '50x50' }" @@ -65,25 +117,33 @@ module Technoweenie # :nodoc: attachment_options[:storage] ||= parent_options[:storage] attachment_options[:path_prefix] ||= attachment_options[:file_system_path] if attachment_options[:path_prefix].nil? - attachment_options[:path_prefix] = attachment_options[:storage] == :s3 ? table_name : File.join("public", table_name) + attachment_options[:path_prefix] = case attachment_options[:storage] + when :s3 then table_name + when :cloud_files then table_name + else File.join("public", table_name) + end end attachment_options[:path_prefix] = attachment_options[:path_prefix][1..-1] if options[:path_prefix].first == '/' - with_options :foreign_key => 'parent_id' do |m| + association_options = { :foreign_key => 'parent_id' } + if attachment_options[:association_options] + association_options.merge!(attachment_options[:association_options]) + end + with_options(association_options) do |m| m.has_many :thumbnails, :class_name => "::#{attachment_options[:thumbnail_class]}" m.belongs_to :parent, :class_name => "::#{base_class}" unless options[:thumbnails].empty? end - storage_mod = Technoweenie::AttachmentFu::Backends.const_get("#{options[:storage].to_s.classify}Backend") + storage_mod = ::Technoweenie::AttachmentFu::Backends.const_get("#{options[:storage].to_s.classify}Backend") include storage_mod unless included_modules.include?(storage_mod) case attachment_options[:processor] when :none, nil - processors = Technoweenie::AttachmentFu.default_processors.dup + processors = ::Technoweenie::AttachmentFu.default_processors.dup begin if processors.any? - attachment_options[:processor] = "#{processors.first}Processor" - processor_mod = Technoweenie::AttachmentFu::Processors.const_get(attachment_options[:processor]) + attachment_options[:processor] = processors.first + processor_mod = ::Technoweenie::AttachmentFu::Processors.const_get("#{attachment_options[:processor].to_s.classify}Processor") include processor_mod unless included_modules.include?(processor_mod) end rescue Object, Exception @@ -94,7 +154,7 @@ module Technoweenie # :nodoc: end else begin - processor_mod = Technoweenie::AttachmentFu::Processors.const_get("#{attachment_options[:processor].to_s.classify}Processor") + processor_mod = ::Technoweenie::AttachmentFu::Processors.const_get("#{attachment_options[:processor].to_s.classify}Processor") include processor_mod unless included_modules.include?(processor_mod) rescue Object, Exception raise unless load_related_exception?($!) @@ -118,7 +178,7 @@ module Technoweenie # :nodoc: end module ClassMethods - delegate :content_types, :to => Technoweenie::AttachmentFu + delegate :content_types, :to => ::Technoweenie::AttachmentFu # Performs common validations for attachment models. def validates_as_attachment @@ -135,12 +195,12 @@ module Technoweenie # :nodoc: base.class_attribute :attachment_options base.before_destroy :destroy_thumbnails base.before_validation :set_size_from_temp_path - base.after_save :after_process_attachment base.after_destroy :destroy_file base.after_validation :process_attachment - if defined?(::ActiveSupport::Callbacks) - base.define_callbacks :after_resize, :after_attachment_saved, :before_thumbnail_saved - end + base.after_save :after_process_attachment + #if defined?(::ActiveSupport::Callbacks) + # base.define_callbacks :after_resize, :after_attachment_saved, :before_thumbnail_saved + #end end unless defined?(::ActiveSupport::Callbacks) @@ -192,7 +252,7 @@ module Technoweenie # :nodoc: # Copies the given file path to a new tempfile, returning the closed tempfile. def copy_to_temp_file(file, temp_base_name) - returning Tempfile.new(temp_base_name, Technoweenie::AttachmentFu.tempfile_path) do |tmp| + Tempfile.new(temp_base_name, ::Technoweenie::AttachmentFu.tempfile_path).tap do |tmp| tmp.close FileUtils.cp file, tmp.path end @@ -200,12 +260,19 @@ module Technoweenie # :nodoc: # Writes the given data to a new tempfile, returning the closed tempfile. def write_to_temp_file(data, temp_base_name) - returning Tempfile.new(temp_base_name, Technoweenie::AttachmentFu.tempfile_path) do |tmp| + Tempfile.new(temp_base_name, ::Technoweenie::AttachmentFu.tempfile_path).tap do |tmp| tmp.binmode tmp.write data tmp.close end end + + def polymorphic_relation_type_column + return @@_polymorphic_relation_type_column if defined?(@@_polymorphic_relation_type_column) + # Checked against ActiveRecord 1.15.6 through Edge @ 2009-08-05. + ref = reflections.values.detect { |r| r.macro == :belongs_to && r.options[:polymorphic] } + @@_polymorphic_relation_type_column = ref && ref.options[:foreign_type] + end end module InstanceMethods @@ -220,11 +287,7 @@ module Technoweenie # :nodoc: # Returns true/false if an attachment is thumbnailable. A thumbnailable attachment has an image content type and the parent_id attribute. def thumbnailable? - image? && !is_thumbnail? - end - - def is_thumbnail? - (thumbnail_class == self.class) && !(respond_to?(:parent_id) && parent_id.nil?) + image? && respond_to?(:parent_id) && parent_id.nil? end # Returns the class used to create new thumbnails for this attachment. @@ -234,26 +297,33 @@ module Technoweenie # :nodoc: # Gets the thumbnail name for a filename. 'foo.jpg' becomes 'foo_thumbnail.jpg' def thumbnail_name_for(thumbnail = nil) - return filename if thumbnail.blank? + if thumbnail.blank? + if filename.nil? + return '' + else + return filename + end + end + ext = nil basename = filename.gsub /\.\w+$/ do |s| ext = s; '' end # ImageScience doesn't create gif thumbnails, only pngs - ext.sub!(/gif$/, 'png') if attachment_options[:processor] == "ImageScience" + ext.sub!(/gif$/i, 'png') if attachment_options[:processor] == "ImageScience" "#{basename}_#{thumbnail}#{ext}" end # Creates or updates the thumbnail for the current attachment. def create_or_update_thumbnail(temp_file, file_name_suffix, *size) thumbnailable? || raise(ThumbnailError.new("Can't create a thumbnail if the content type is not an image or there is no parent_id column")) - returning find_or_initialize_thumbnail(file_name_suffix) do |thumb| - thumb.attributes = { + find_or_initialize_thumbnail(file_name_suffix).tap do |thumb| + thumb.temp_paths.unshift temp_file + thumb.send(:assign_attributes, { :content_type => content_type, :filename => thumbnail_name_for(file_name_suffix), - :temp_path => temp_file, :thumbnail_resize_options => size - } + }, :without_protection => true) callback_with_args :before_thumbnail_saved, thumb thumb.save! end @@ -276,7 +346,7 @@ module Technoweenie # :nodoc: # Returns true if the attachment data will be written to the storage system on the next save def save_attachment? - File.file?(temp_path.to_s) + File.file?(temp_path.class == String ? temp_path : temp_path.to_filename) end # nil placeholder in case this field is used in a form. @@ -294,14 +364,21 @@ module Technoweenie # :nodoc: # # TODO: Allow it to work with Merb tempfiles too. def uploaded_data=(file_data) - return nil if file_data.nil? || file_data.size == 0 - self.content_type = file_data.content_type - self.filename = file_data.original_filename if respond_to?(:filename) + if file_data.respond_to?(:content_type) + return nil if file_data.size == 0 + self.content_type = file_data.content_type + self.filename = file_data.original_filename if respond_to?(:filename) + else + return nil if file_data.blank? || file_data['size'] == 0 + self.content_type = file_data['content_type'] + self.filename = file_data['filename'] + file_data = file_data['tempfile'] + end if file_data.is_a?(StringIO) file_data.rewind - self.temp_data = file_data.read + set_temp_data file_data.read else - self.temp_path = file_data + file_data.respond_to?(:tempfile) ? self.temp_paths.unshift( file_data.tempfile.path ) : self.temp_paths.unshift( file_data.path ) end end @@ -320,22 +397,14 @@ module Technoweenie # :nodoc: [] : [copy_to_temp_file(full_filename)]) end - # Adds a new temp_path to the array. This should take a string or a Tempfile. This class makes no - # attempt to remove the files, so Tempfiles should be used. Tempfiles remove themselves when they go out of scope. - # You can also use string paths for temporary files, such as those used for uploaded files in a web server. - def temp_path=(value) - temp_paths.unshift value - temp_path - end - # Gets the data from the latest temp file. This will read the file into memory. def temp_data save_attachment? ? File.read(temp_path) : nil end # Writes the given data to a Tempfile and adds it to the collection of temp files. - def temp_data=(data) - self.temp_path = write_to_temp_file data unless data.nil? + def set_temp_data(data) + temp_paths.unshift write_to_temp_file data unless data.nil? end # Copies the given file to a randomly named Tempfile. @@ -364,17 +433,20 @@ module Technoweenie # :nodoc: protected # Generates a unique filename for a Tempfile. def random_tempfile_filename - "#{rand Time.now.to_i}#{filename || 'attachment'}" + base_filename = filename ? filename.gsub(/\.\w+$/, '') : 'attachment' + ext = filename.slice(/\.\w+$/) + ["#{rand Time.now.to_i}#{base_filename}", ext || ''] end def sanitize_filename(filename) - returning filename.strip do |name| + return unless filename + filename.strip.tap do |name| # NOTE: File.basename doesn't work right with Windows paths on Unix # get only the filename, not the whole path name.gsub! /^.*(\\|\/)/, '' # Finally, replace all non alphanumeric, underscore or periods with underscore - name.gsub! /[^\w\.\-]/, '_' + name.gsub! /[^A-Za-z0-9\.\-]/, '_' end end @@ -387,13 +459,17 @@ module Technoweenie # :nodoc: def attachment_attributes_valid? [:size, :content_type].each do |attr_name| enum = attachment_options[attr_name] - errors.add attr_name, ActiveRecord::Errors.default_error_messages[:inclusion] unless enum.nil? || enum.include?(send(attr_name)) + if Object.const_defined?(:I18n) # Rails >= 2.2 + errors.add attr_name, I18n.translate("activerecord.errors.messages.inclusion", attr_name => enum) unless enum.nil? || enum.include?(send(attr_name)) + else + errors.add attr_name, ActiveRecord::Errors.default_error_messages[:inclusion] unless enum.nil? || enum.include?(send(attr_name)) + end end end # Initializes a new thumbnail with the given suffix. def find_or_initialize_thumbnail(file_name_suffix) - thumbnail_class.columns.map(&:name).include?('parent_id') ? + respond_to?(:parent_id) ? thumbnail_class.find_or_initialize_by_thumbnail_and_parent_id(file_name_suffix.to_s, id) : thumbnail_class.find_or_initialize_by_thumbnail(file_name_suffix.to_s) end @@ -406,29 +482,51 @@ module Technoweenie # :nodoc: # Cleans up after processing. Thumbnails are created, the attachment is stored to the backend, and the temp_paths are cleared. def after_process_attachment if @saved_attachment - if respond_to?(:process_attachment_with_processing) && thumbnailable? && !attachment_options[:thumbnails].blank? + if respond_to?(:process_attachment_with_processing, true) && thumbnailable? && !attachment_options[:thumbnails].blank? && parent_id.nil? temp_file = temp_path || create_temp_file - attachment_options[:thumbnails].each { |suffix, size| create_or_update_thumbnail(temp_file, suffix, *size) } + attachment_options[:thumbnails].each { |suffix, size| + if size.is_a?(Symbol) + parent_type = polymorphic_parent_type + next unless parent_type && [parent_type, parent_type.tableize].include?(suffix.to_s) && respond_to?(size) + size = send(size) + end + if size.is_a?(Hash) + parent_type = polymorphic_parent_type + next unless parent_type && [parent_type, parent_type.tableize].include?(suffix.to_s) + size.each { |ppt_suffix, ppt_size| + create_or_update_thumbnail(temp_file, ppt_suffix, *ppt_size) + } + else + create_or_update_thumbnail(temp_file, suffix, *size) + end + } end save_to_storage @temp_paths.clear @saved_attachment = nil - callback :after_attachment_saved + #callback :after_attachment_saved + callback_with_args :after_attachment_saved, nil end end # Resizes the given processed img object with either the attachment resize options or the thumbnail resize options. def resize_image_or_thumbnail!(img) - if !is_thumbnail? && attachment_options[:resize_to] # parent image + if (!respond_to?(:parent_id) || parent_id.nil?) && attachment_options[:resize_to] # parent image resize_image(img, attachment_options[:resize_to]) elsif thumbnail_resize_options # thumbnail resize_image(img, thumbnail_resize_options) end end + if defined?(Rails) && Rails::VERSION::MAJOR >= 3 + def callback_with_args(method, arg = self) + if respond_to?(method) + send(method, arg) + end + end # Yanked from ActiveRecord::Callbacks, modified so I can pass args to the callbacks besides self. # Only accept blocks, however - if ActiveSupport.const_defined?(:Callbacks) + elsif ActiveSupport.const_defined?(:Callbacks) # Rails 2.1 and beyond! def callback_with_args(method, arg = self) notify(method) @@ -464,6 +562,27 @@ module Technoweenie # :nodoc: def destroy_thumbnails self.thumbnails.each { |thumbnail| thumbnail.destroy } if thumbnailable? end + + def polymorphic_parent_type + rel_name = self.class.polymorphic_relation_type_column + rel_name && send(rel_name) + end + + def get_jpeg_quality(require_0_to_100 = true) + quality = attachment_options[:jpeg_quality] + if quality.is_a?(Hash) + sbl_quality = thumbnail && quality[thumbnail.to_sym] + sbl_quality = nil if sbl_quality && require_0_to_100 && !sbl_quality.to_i.between?(0, 100) + surface = (width || 1) * (height || 1) + size_quality = quality.detect { |k, v| + next unless k.is_a?(String) && k =~ /^(<|>=)(\d+)$/ + op, threshold = $1, $2.to_i + surface.send(op, threshold) + } + quality = sbl_quality || size_quality && size_quality[1] + end + return quality && (!require_0_to_100 || quality.to_i.between?(0, 100)) ? quality : nil + end end end end diff --git a/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/backends/cloud_file_backend.rb b/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/backends/cloud_file_backend.rb new file mode 100644 index 0000000..a779195 --- /dev/null +++ b/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/backends/cloud_file_backend.rb @@ -0,0 +1,211 @@ +module Technoweenie # :nodoc: + module AttachmentFu # :nodoc: + module Backends + # = CloudFiles Storage Backend + # + # Enables use of {Rackspace Cloud Files}[http://www.mosso.com/cloudfiles.jsp] as a storage mechanism + # + # Based heavily on the Amazon S3 backend. + # + # == Requirements + # + # Requires the {Cloud Files Gem}[http://www.mosso.com/cloudfiles.jsp] by Rackspace + # + # == Configuration + # + # Configuration is done via Rails.root.to_s/config/rackspace_cloudfiles.yml and is loaded according to the #{Rails.env}. + # The minimum connection options that you must specify are a container name, your Mosso login name and your Mosso API key. + # You can sign up for Cloud Files and get access keys by visiting https://www.mosso.com/buy.htm + # + # Example configuration (Rails.root.to_s/config/rackspace_cloudfiles.yml) + # + # development: + # container_name: appname_development + # username: + # api_key: + # + # test: + # container_name: appname_test + # username: + # api_key: + # + # production: + # container_name: appname + # username: + # apik_key: + # + # You can change the location of the config path by passing a full path to the :cloudfiles_config_path option. + # + # has_attachment :storage => :cloud_files, :cloudfiles_config_path => (Rails.root.to_s + '/config/mosso.yml') + # + # === Required configuration parameters + # + # * :username - The username for your Rackspace Cloud (Mosso) account. Provided by Rackspace. + # * :secret_access_key - The api key for your Rackspace Cloud account. Provided by Rackspace. + # * :container_name - The name of a container in your Cloud Files account. + # + # If any of these required arguments is missing, a AuthenticationException will be raised from CloudFiles::Connection. + # + # == Usage + # + # To specify Cloud Files as the storage mechanism for a model, set the acts_as_attachment :storage option to :cloud_files/tt>. + # + # class Photo < ActiveRecord::Base + # has_attachment :storage => :cloud_files + # end + # + # === Customizing the path + # + # By default, files are prefixed using a pseudo hierarchy in the form of :table_name/:id, which results + # in Cloud Files object names (and urls) that look like: http://:server/:container_name/:table_name/:id/:filename with :table_name + # representing the customizable portion of the path. You can customize this prefix using the :path_prefix + # option: + # + # class Photo < ActiveRecord::Base + # has_attachment :storage => :cloud_files, :path_prefix => 'my/custom/path' + # end + # + # Which would result in public URLs like http(s)://:server/:container_name/my/custom/path/:id/:filename. + # + # === Permissions + # + # File permisisons are determined by the permissions of the container. At present, the options are public (and distributed + # by the Limelight CDN), and private (only available to your login) + # + # === Other options + # + # Of course, all the usual configuration options apply, such as content_type and thumbnails: + # + # class Photo < ActiveRecord::Base + # has_attachment :storage => :cloud_files, :content_type => ['application/pdf', :image], :resize_to => 'x50' + # has_attachment :storage => :cloud_files, :thumbnails => { :thumb => [50, 50], :geometry => 'x50' } + # end + # + # === Accessing Cloud Files URLs + # + # You can get an object's public URL using the cloudfiles_url accessor. For example, assuming that for your postcard app + # you had a container name like 'postcard_world_development', and an attachment model called Photo: + # + # @postcard.cloudfiles_url # => http://cdn.cloudfiles.mosso.com/c45182/uploaded_files/20/london.jpg + # + # The resulting url is in the form: http://:server/:container_name/:table_name/:id/:file. + # The optional thumbnail argument will output the thumbnail's filename (if any). + # + # Additionally, you can get an object's base path relative to the container root using + # base_path: + # + # @photo.file_base_path # => uploaded_files/20 + # + # And the full path (including the filename) using full_filename: + # + # @photo.full_filename # => uploaded_files/20/london.jpg + # + # Niether base_path or full_filename include the container name as part of the path. + # You can retrieve the container name using the container_name method. + module CloudFileBackend + class RequiredLibraryNotFoundError < StandardError; end + class ConfigFileNotFoundError < StandardError; end + + def self.included(base) #:nodoc: + mattr_reader :container_name, :cloudfiles_config + + begin + require 'cloudfiles' + rescue LoadError + raise RequiredLibraryNotFoundError.new('CloudFiles could not be loaded') + end + + begin + @@cloudfiles_config_path = base.attachment_options[:cloudfiles_config_path] || (Rails.root.to_s + '/config/rackspace_cloudfiles.yml') + @@cloudfiles_config = @@cloudfiles_config = YAML.load(ERB.new(File.read(@@cloudfiles_config_path)).result)[Rails.env].symbolize_keys + rescue + #raise ConfigFileNotFoundError.new('File %s not found' % @@cloudfiles_config_path) + end + + @@container_name = @@cloudfiles_config[:container_name] + @@cf = CloudFiles::Connection.new(@@cloudfiles_config[:username], @@cloudfiles_config[:api_key]) + @@container = @@cf.container(@@container_name) + + base.before_update :rename_file + end + + # Overwrites the base filename writer in order to store the old filename + def filename=(value) + @old_filename = filename unless filename.nil? || @old_filename + write_attribute :filename, sanitize_filename(value) + end + + # The attachment ID used in the full path of a file + def attachment_path_id + ((respond_to?(:parent_id) && parent_id) || id).to_s + end + + # The pseudo hierarchy containing the file relative to the container name + # Example: :table_name/:id + def base_path + File.join(attachment_options[:path_prefix], attachment_path_id) + end + + # The full path to the file relative to the container name + # Example: :table_name/:id/:filename + def full_filename(thumbnail = nil) + File.join(base_path, thumbnail_name_for(thumbnail)) + end + + # All public objects are accessible via a GET request to the Cloud Files servers. You can generate a + # url for an object using the cloudfiles_url method. + # + # @photo.cloudfiles_url + # + # The resulting url is in the CDN URL for the object + # + # The optional thumbnail argument will output the thumbnail's filename (if any). + # + # If you are trying to get the URL for a nonpublic container, nil will be returned. + def cloudfiles_url(thumbnail = nil) + if @@container.public? + File.join(@@container.cdn_url, full_filename(thumbnail)) + else + nil + end + end + alias :public_filename :cloudfiles_url + + def create_temp_file + write_to_temp_file current_data + end + + def current_data + @@container.get_object(full_filename).data + end + + protected + # Called in the after_destroy callback + def destroy_file + @@container.delete_object(full_filename) + end + + def rename_file + # Cloud Files doesn't rename right now, so we'll just nuke. + return unless @old_filename && @old_filename != filename + + old_full_filename = File.join(base_path, @old_filename) + @@container.delete_object(old_full_filename) + + @old_filename = nil + true + end + + def save_to_storage + if save_attachment? + @object = @@container.create_object(full_filename) + @object.write((temp_path ? File.open(temp_path) : temp_data)) + end + + @old_filename = nil + true + end + end + end + end +end diff --git a/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/backends/file_system_backend.rb b/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/backends/file_system_backend.rb index e314c8d..985fae1 100644 --- a/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/backends/file_system_backend.rb +++ b/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/backends/file_system_backend.rb @@ -1,3 +1,6 @@ +require 'fileutils' +require 'digest/sha2' + module Technoweenie # :nodoc: module AttachmentFu # :nodoc: module Backends @@ -6,12 +9,12 @@ module Technoweenie # :nodoc: def self.included(base) #:nodoc: base.before_update :rename_file end - + # Gets the full path to the filename in this format: # # # This assumes a model name like MyModel - # # public/#{table_name} is the default filesystem path - # Rails.root/public/my_models/5/blah.jpg + # # public/#{table_name} is the default filesystem path + # #{Rails.root}/public/my_models/5/blah.jpg # # Overwrite this method in your model to customize the filename. # The optional thumbnail argument will output the thumbnail's filename. @@ -19,29 +22,56 @@ module Technoweenie # :nodoc: file_system_path = (thumbnail ? thumbnail_class : self).attachment_options[:path_prefix].to_s File.join(Rails.root, file_system_path, *partitioned_path(thumbnail_name_for(thumbnail))) end - + # Used as the base path that #public_filename strips off full_filename to create the public path def base_path @base_path ||= File.join(Rails.root, 'public') end - + # The attachment ID used in the full path of a file def attachment_path_id - (is_thumbnail? && respond_to?(:parent_id)) ? parent_id : id + ((respond_to?(:parent_id) && parent_id) || id) || 0 end - - # overrwrite this to do your own app-specific partitioning. - # you can thank Jamis Buck for this: http://www.37signals.com/svn/archives2/id_partitioning.php + + # Partitions the given path into an array of path components. + # + # For example, given an *args of ["foo", "bar"], it will return + # ["0000", "0001", "foo", "bar"] (assuming that that id returns 1). + # + # If the id is not an integer, then path partitioning will be performed by + # hashing the string value of the id with SHA-512, and splitting the result + # into 4 components. If the id a 128-bit UUID (as set by :uuid_primary_key => true) + # then it will be split into 2 components. + # + # To turn this off entirely, set :partition => false. def partitioned_path(*args) - ("%08d" % attachment_path_id).scan(/..../) + args + if respond_to?(:attachment_options) && attachment_options[:partition] == false + args + elsif attachment_options[:uuid_primary_key] + # Primary key is a 128-bit UUID in hex format. Split it into 2 components. + path_id = attachment_path_id.to_s + component1 = path_id[0..15] || "-" + component2 = path_id[16..-1] || "-" + [component1, component2] + args + else + path_id = attachment_path_id + if path_id.is_a?(Integer) + # Primary key is an integer. Split it after padding it with 0. + ("%08d" % path_id).scan(/..../) + args + else + # Primary key is a String. Hash it, then split it into 4 components. + hash = Digest::SHA512.hexdigest(path_id.to_s) + [hash[0..31], hash[32..63], hash[64..95], hash[96..127]] + args + end + end end - + # Gets the public path to the file # The optional thumbnail argument will output the thumbnail's filename. def public_filename(thumbnail = nil) full_filename(thumbnail).gsub %r(^#{Regexp.escape(base_path)}), '' end - + def filename=(value) @old_filename = full_filename unless filename.nil? || @old_filename write_attribute :filename, sanitize_filename(value) @@ -74,19 +104,19 @@ module Technoweenie # :nodoc: @old_filename = nil true end - + # Saves the file to the file system def save_to_storage if save_attachment? # TODO: This overwrites the file if it exists, maybe have an allow_overwrite option? FileUtils.mkdir_p(File.dirname(full_filename)) - File.cp(temp_path, full_filename) - File.chmod(attachment_options[:chmod] || 0644, full_filename) + FileUtils.cp(temp_path, full_filename) + FileUtils.chmod(attachment_options[:chmod] || 0644, full_filename) end @old_filename = nil true end - + def current_data File.file?(full_filename) ? File.read(full_filename) : nil end diff --git a/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/backends/s3_backend.rb b/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/backends/s3_backend.rb index effd886..6532dd0 100644 --- a/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/backends/s3_backend.rb +++ b/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/backends/s3_backend.rb @@ -12,31 +12,37 @@ module Technoweenie # :nodoc: # # == Configuration # - # Configuration is done via Rails.root/config/amazon_s3.yml and is loaded according to the RAILS_ENV. + # Configuration is done via #{Rails.root}/config/amazon_s3.yml and is loaded according to the #{Rails.env}. # The minimum connection options that you must specify are a bucket name, your access key id and your secret access key. # If you don't already have your access keys, all you need to sign up for the S3 service is an account at Amazon. # You can sign up for S3 and get access keys by visiting http://aws.amazon.com/s3. # - # Example configuration (Rails.root/config/amazon_s3.yml) - # + # If you wish to use Amazon CloudFront to serve the files, you can also specify a distibution domain for the bucket. + # To read more about CloudFront, visit http://aws.amazon.com/cloudfront + # + # Example configuration (#{Rails.root}/config/amazon_s3.yml) + # # development: # bucket_name: appname_development # access_key_id: # secret_access_key: - # + # distribution_domain: XXXX.cloudfront.net + # # test: # bucket_name: appname_test # access_key_id: # secret_access_key: - # + # distribution_domain: XXXX.cloudfront.net + # # production: # bucket_name: appname # access_key_id: # secret_access_key: + # distribution_domain: XXXX.cloudfront.net # # You can change the location of the config path by passing a full path to the :s3_config_path option. # - # has_attachment :storage => :s3, :s3_config_path => (Rails.root + '/config/s3.yml') + # has_attachment :storage => :s3, :s3_config_path => (#{Rails.root} + '/config/s3.yml') # # === Required configuration parameters # @@ -59,6 +65,8 @@ module Technoweenie # :nodoc: # * :server - The server to make requests to. Defaults to s3.amazonaws.com. # * :port - The port to the requests should be made on. Defaults to 80 or 443 if :use_ssl is set. # * :use_ssl - If set to true, :port will be implicitly set to 443, unless specified otherwise. Defaults to false. + # * :distribution_domain - The CloudFront distribution domain for the bucket. This can either be the assigned + # distribution domain (ie. XXX.cloudfront.net) or a chosen domain using a CNAME. See CloudFront for more details. # # == Usage # @@ -81,10 +89,43 @@ module Technoweenie # :nodoc: # # Which would result in URLs like http(s)://:server/:bucket_name/my/custom/path/:id/:filename. # + # === Using different bucket names on different models + # + # By default the bucket name that the file will be stored to is the one specified by the + # :bucket_name key in the amazon_s3.yml file. You can use the :bucket_key option + # to overide this behavior on a per model basis. For instance if you want a bucket that will hold + # only Photos you can do this: + # + # class Photo < ActiveRecord::Base + # has_attachment :storage => :s3, :bucket_key => :photo_bucket_name + # end + # + # And then your amazon_s3.yml file needs to look like this. + # + # development: + # bucket_name: appname_development + # access_key_id: + # secret_access_key: + # + # test: + # bucket_name: appname_test + # access_key_id: + # secret_access_key: + # + # production: + # bucket_name: appname + # photo_bucket_name: appname_photos + # access_key_id: + # secret_access_key: + # + # If the bucket_key you specify is not there in a certain environment then attachment_fu will + # default to the bucket_name key. This way you only have to create special buckets + # this can be helpful if you only need special buckets in certain environments. + # # === Permissions # # By default, files are stored on S3 with public access permissions. You can customize this using - # the :s3_access option to has_attachment. Available values are + # the :s3_access option to has_attachment. Available values are # :private, :public_read_write, and :authenticated_read. # # === Other options @@ -117,13 +158,23 @@ module Technoweenie # :nodoc: # # Niether base_path or full_filename include the bucket name as part of the path. # You can retrieve the bucket name using the bucket_name method. + # + # === Accessing CloudFront URLs + # + # You can get an object's CloudFront URL using the cloudfront_url accessor. Using the example from above: + # @postcard.cloudfront_url # => http://XXXX.cloudfront.net/photos/1/mexico.jpg + # + # The resulting url is in the form: http://:distribution_domain/:table_name/:id/:file + # + # If you set :cloudfront to true in your model, the public_filename will be the CloudFront + # URL, not the S3 URL. module S3Backend class RequiredLibraryNotFoundError < StandardError; end class ConfigFileNotFoundError < StandardError; end def self.included(base) #:nodoc: mattr_reader :bucket_name, :s3_config - + begin require 'aws/s3' include AWS::S3 @@ -132,13 +183,20 @@ module Technoweenie # :nodoc: end begin - @@s3_config_path = base.attachment_options[:s3_config_path] || (Rails.root + '/config/amazon_s3.yml') - @@s3_config = @@s3_config = YAML.load(ERB.new(File.read(@@s3_config_path)).result)[RAILS_ENV].symbolize_keys + @@s3_config_path = base.attachment_options[:s3_config_path] || File.join(Rails.root, 'config', 'amazon_s3.yml') + @@s3_config = @@s3_config = YAML.load(ERB.new(File.read(@@s3_config_path)).result)[Rails.env].symbolize_keys #rescue # raise ConfigFileNotFoundError.new('File %s not found' % @@s3_config_path) end - @@bucket_name = s3_config[:bucket_name] + bucket_key = base.attachment_options[:bucket_key] + + if bucket_key and s3_config[bucket_key.to_sym] + eval_string = "def bucket_name()\n \"#{s3_config[bucket_key.to_sym]}\"\nend" + else + eval_string = "def bucket_name()\n \"#{s3_config[:bucket_name]}\"\nend" + end + base.class_eval(eval_string, __FILE__, __LINE__) Base.establish_connection!(s3_config.slice(:access_key_id, :secret_access_key, :server, :port, :use_ssl, :persistent, :proxy)) @@ -150,27 +208,35 @@ module Technoweenie # :nodoc: def self.protocol @protocol ||= s3_config[:use_ssl] ? 'https://' : 'http://' end - + def self.hostname @hostname ||= s3_config[:server] || AWS::S3::DEFAULT_HOST end - + def self.port_string @port_string ||= (s3_config[:port].nil? || s3_config[:port] == (s3_config[:use_ssl] ? 443 : 80)) ? '' : ":#{s3_config[:port]}" end + def self.distribution_domain + @distribution_domain = s3_config[:distribution_domain] + end + module ClassMethods def s3_protocol Technoweenie::AttachmentFu::Backends::S3Backend.protocol end - + def s3_hostname Technoweenie::AttachmentFu::Backends::S3Backend.hostname end - + def s3_port_string Technoweenie::AttachmentFu::Backends::S3Backend.port_string end + + def cloudfront_distribution_domain + Technoweenie::AttachmentFu::Backends::S3Backend.distribution_domain + end end # Overwrites the base filename writer in order to store the old filename @@ -196,22 +262,42 @@ module Technoweenie # :nodoc: File.join(base_path, thumbnail_name_for(thumbnail)) end - # All public objects are accessible via a GET request to the S3 servers. You can generate a + # All public objects are accessible via a GET request to the S3 servers. You can generate a # url for an object using the s3_url method. # # @photo.s3_url # # The resulting url is in the form: http(s)://:server/:bucket_name/:table_name/:id/:file where # the :server variable defaults to AWS::S3 URL::DEFAULT_HOST (s3.amazonaws.com) and can be - # set using the configuration parameters in Rails.root/config/amazon_s3.yml. + # set using the configuration parameters in #{Rails.root}/config/amazon_s3.yml. # # The optional thumbnail argument will output the thumbnail's filename (if any). def s3_url(thumbnail = nil) File.join(s3_protocol + s3_hostname + s3_port_string, bucket_name, full_filename(thumbnail)) end - alias :public_filename :s3_url - # All private objects are accessible via an authenticated GET request to the S3 servers. You can generate an + # All public objects are accessible via a GET request to CloudFront. You can generate a + # url for an object using the cloudfront_url method. + # + # @photo.cloudfront_url + # + # The resulting url is in the form: http://:distribution_domain/:table_name/:id/:file using + # the :distribution_domain variable set in the configuration parameters in #{Rails.root}/config/amazon_s3.yml. + # + # The optional thumbnail argument will output the thumbnail's filename (if any). + def cloudfront_url(thumbnail = nil) + s3_protocol + cloudfront_distribution_domain + "/" + full_filename(thumbnail) + end + + def public_filename(*args) + if attachment_options[:cloudfront] + cloudfront_url(*args) + else + s3_url(*args) + end + end + + # All private objects are accessible via an authenticated GET request to the S3 servers. You can generate an # authenticated url for an object like this: # # @photo.authenticated_s3_url @@ -223,7 +309,7 @@ module Technoweenie # :nodoc: # # # Absolute expiration date (October 13th, 2025) # @photo.authenticated_s3_url(:expires => Time.mktime(2025,10,13).to_i) - # + # # # Expiration in five hours from now # @photo.authenticated_s3_url(:expires_in => 5.hours) # @@ -236,8 +322,9 @@ module Technoweenie # :nodoc: # # @photo.authenticated_s3_url('thumbnail', :expires_in => 5.hours, :use_ssl => true) def authenticated_s3_url(*args) - thumbnail = args.first.is_a?(String) ? args.first : nil - options = args.last.is_a?(Hash) ? args.last : {} + options = args.extract_options! + options[:expires_in] = options[:expires_in].to_i if options[:expires_in] + thumbnail = args.shift S3Object.url_for(full_filename(thumbnail), bucket_name, options) end @@ -246,21 +333,29 @@ module Technoweenie # :nodoc: end def current_data - S3Object.value full_filename, bucket_name + if attachment_options[:encrypted_storage] && self.respond_to?(:encryption_key) && self.encryption_key != nil + EncryptedData.decrypt_data(S3Object.value(full_filename, bucket_name), self.encryption_key) + else + S3Object.value full_filename, bucket_name + end end def s3_protocol Technoweenie::AttachmentFu::Backends::S3Backend.protocol end - + def s3_hostname Technoweenie::AttachmentFu::Backends::S3Backend.hostname end - + def s3_port_string Technoweenie::AttachmentFu::Backends::S3Backend.port_string end + def cloudfront_distribution_domain + Technoweenie::AttachmentFu::Backends::S3Backend.distribution_domain + end + protected # Called in the after_destroy callback def destroy_file @@ -269,7 +364,7 @@ module Technoweenie # :nodoc: def rename_file return unless @old_filename && @old_filename != filename - + old_full_filename = File.join(base_path, @old_filename) S3Object.rename( @@ -285,13 +380,27 @@ module Technoweenie # :nodoc: def save_to_storage if save_attachment? - S3Object.store( - full_filename, - (temp_path ? File.open(temp_path) : temp_data), - bucket_name, - :content_type => content_type, - :access => attachment_options[:s3_access] - ) + if attachment_options[:encrypted_storage] + S3Object.store( + full_filename, + (temp_path ? File.open(temp_path) : temp_data), + bucket_name, + :content_type => content_type, + :cache_control => attachment_options[:cache_control], + :access => attachment_options[:s3_access], + 'x-amz-server-side-encryption' => 'AES256', + 'Content-Disposition' => "attachment; filename=\"#{filename}\"" + ) + else + S3Object.store( + full_filename, + (temp_path ? File.open(temp_path) : temp_data), + bucket_name, + :content_type => content_type, + :cache_control => attachment_options[:cache_control], + :access => attachment_options[:s3_access] + ) + end end @old_filename = nil diff --git a/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/core_image_processor.rb b/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/core_image_processor.rb index 8120b69..d78e8d0 100644 --- a/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/core_image_processor.rb +++ b/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/core_image_processor.rb @@ -44,7 +44,17 @@ module Technoweenie # :nodoc: processor.render do |result| self.width = result.extent.size.width if respond_to?(:width) self.height = result.extent.size.height if respond_to?(:height) - result.save self.temp_path, OSX::NSJPEGFileType + out_file = random_tempfile_filename + temp_paths.unshift Tempfile.new(out_file, Technoweenie::AttachmentFu.tempfile_path).path + properties = nil + # We don't check the source image since we're forcing the output to JPEG, apparently… + # Beware: apparently CoreImage only takes the percentage as a HINT, using a different actual quality… + quality = get_jpeg_quality + properties = { OSX::NSImageCompressionFactor => quality / 100.0 } if quality + result.save(self.temp_path, OSX::NSJPEGFileType, properties) + # + # puts "#{self.temp_path} @ #{quality.inspect} -> #{%x(identify -format '%Q' "#{self.temp_path}")}" + # self.size = File.size(self.temp_path) end end diff --git a/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/gd2_processor.rb b/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/gd2_processor.rb index d120b25..ea00713 100644 --- a/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/gd2_processor.rb +++ b/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/gd2_processor.rb @@ -44,8 +44,13 @@ module Technoweenie # :nodoc: w, h = [img.width, img.height] / size.to_s img.resize!(w, h, false) end - self.temp_path = random_tempfile_filename - self.size = img.export(self.temp_path) + self.width = img.width if respond_to?(:width) + self.height = img.height if respond_to?(:height) + out_file = random_tempfile_filename + temp_paths.unshift out_file + jpeg = out_file =~ /\.jpe?g\z/i + quality = jpeg && get_jpeg_quality + self.size = img.export(self.temp_path, quality ? { :quality => quality } : {}) end end diff --git a/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/image_science_processor.rb b/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/image_science_processor.rb index 6f27833..44da9dd 100644 --- a/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/image_science_processor.rb +++ b/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/image_science_processor.rb @@ -32,13 +32,21 @@ module Technoweenie # :nodoc: # pngs for thumbnails. It has something to do with trying to save gifs # with a larger palette than 256 colors, which is all the gif format # supports. - filename.sub! /gif$/, 'png' + filename.sub! /gif$/i, 'png' content_type.sub!(/gif$/, 'png') - self.temp_path = write_to_temp_file(filename) + temp_paths.unshift write_to_temp_file(filename) grab_dimensions = lambda do |img| self.width = img.width if respond_to?(:width) self.height = img.height if respond_to?(:height) - img.save self.temp_path + + # We don't check for quality being a 0-100 value as we also allow FreeImage JPEG_xxx constants. + quality = content_type[/jpe?g/i] && get_jpeg_quality(false) + # Traditional ImageScience has a 1-arg save method, tdd-image_science has 1 mandatory + 1 optional + if quality && img.method(:save).arity == -2 + img.save self.temp_path, quality + else + img.save self.temp_path + end self.size = File.size(self.temp_path) callback_with_args :after_resize, img end @@ -52,7 +60,18 @@ module Technoweenie # :nodoc: end else new_size = [img.width, img.height] / size.to_s - img.resize(new_size[0], new_size[1], &grab_dimensions) + if size.ends_with?('!') + aspect = new_size[0].to_f / new_size[1].to_f + ih, iw = img.height, img.width + w, h = (ih * aspect), (iw / aspect) + w = [iw, w].min.to_i + h = [ih, h].min.to_i + img.with_crop((iw-w)/2, (ih-h)/2, (iw+w)/2, (ih+h)/2) { |crop| + crop.resize(new_size[0], new_size[1], &grab_dimensions) + } + else + img.resize(new_size[0], new_size[1], &grab_dimensions) + end end end end diff --git a/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/mini_magick_processor.rb b/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/mini_magick_processor.rb index 668a720..2a37b3a 100644 --- a/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/mini_magick_processor.rb +++ b/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/mini_magick_processor.rb @@ -7,12 +7,12 @@ module Technoweenie # :nodoc: base.send :extend, ClassMethods base.alias_method_chain :process_attachment, :processing end - + module ClassMethods # Yields a block containing an MiniMagick Image for the given binary data. def with_image(file, &block) begin - binary_data = file.is_a?(MiniMagick::Image) ? file : MiniMagick::Image.from_file(file) unless !Object.const_defined?(:MiniMagick) + binary_data = file.is_a?(MiniMagick::Image) ? file : MiniMagick::Image.open(file) unless !Object.const_defined?(:MiniMagick) rescue # Log the failure to load the image. logger.debug("Exception working with image: #{$!}") @@ -23,23 +23,30 @@ module Technoweenie # :nodoc: !binary_data.nil? end end - + protected def process_attachment_with_processing return unless process_attachment_without_processing with_image do |img| resize_image_or_thumbnail! img - self.width = img[:width] if respond_to?(:width) - self.height = img[:height] if respond_to?(:height) + self.width = img[:width] if respond_to?(:width) + self.height = img[:height] if respond_to?(:height) callback_with_args :after_resize, img end if image? end - + # Performs the actual resizing operation for a thumbnail def resize_image(img, size) size = size.first if size.is_a?(Array) && size.length == 1 + format = img[:format] img.combine_options do |commands| commands.strip unless attachment_options[:keep_profile] + + # GIF is not handled correctly, so we move to PNG, as in other processors… + if format == 'GIF' + img.format('PNG') + end + if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum)) if size.is_a?(Fixnum) size = [size, size] @@ -47,13 +54,89 @@ module Technoweenie # :nodoc: else commands.resize(size.join('x') + '!') end + # extend to thumbnail size + elsif size.is_a?(String) and size =~ /e$/ + size = size.gsub(/e/, '') + commands.resize(size.to_s + '>') + commands.background('#ffffff') + commands.gravity('center') + commands.extent(size) + # crop thumbnail, the smart way + elsif size.is_a?(String) and size =~ /c$/ + size = size.gsub(/c/, '') + + # calculate sizes and aspect ratio + thumb_width, thumb_height = size.split("x") + thumb_width = thumb_width.to_f + thumb_height = thumb_height.to_f + + thumb_aspect = thumb_width.to_f / thumb_height.to_f + image_width, image_height = img[:width].to_f, img[:height].to_f + image_aspect = image_width / image_height + + # only crop if image is not smaller in both dimensions + unless image_width < thumb_width and image_height < thumb_height + command = calculate_offset(image_width,image_height,image_aspect,thumb_width,thumb_height,thumb_aspect) + + # crop image + commands.extract(command) + end + + # don not resize if image is not as height or width then thumbnail + if image_width < thumb_width or image_height < thumb_height + commands.background('#ffffff') + commands.gravity('center') + commands.extent(size) + # resize image + else + commands.resize("#{size.to_s}") + end + # crop end else commands.resize(size.to_s) end end - self.temp_path = img + dims = img[:dimensions] + self.width = dims[0] if respond_to?(:width) + self.height = dims[1] if respond_to?(:height) + # Has to be done this far so we get proper dimensions + if format == 'JPEG' + quality = get_jpeg_quality + img.quality(quality) if quality + end + temp_paths.unshift img + self.size = File.size(self.temp_path) end + + def calculate_offset(image_width,image_height,image_aspect,thumb_width,thumb_height,thumb_aspect) + # only crop if image is not smaller in both dimensions + + # special cases, image smaller in one dimension then thumbsize + if image_width < thumb_width + offset = (image_height / 2) - (thumb_height / 2) + command = "#{image_width}x#{thumb_height}+0+#{offset}" + elsif image_height < thumb_height + offset = (image_width / 2) - (thumb_width / 2) + command = "#{thumb_width}x#{image_height}+#{offset}+0" + + # normal thumbnail generation + # calculate height and offset y, width is fixed + elsif (image_aspect <= thumb_aspect or image_width < thumb_width) and image_height > thumb_height + height = image_width / thumb_aspect + offset = (image_height / 2) - (height / 2) + command = "#{image_width}x#{height}+0+#{offset}" + # calculate width and offset x, height is fixed + else + width = image_height * thumb_aspect + offset = (image_width / 2) - (width / 2) + command = "#{width}x#{image_height}+#{offset}+0" + end + # crop image + command + end + + end end end -end +end \ No newline at end of file diff --git a/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/rmagick_processor.rb b/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/rmagick_processor.rb index aa83b29..6dce6e3 100644 --- a/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/rmagick_processor.rb +++ b/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/rmagick_processor.rb @@ -13,6 +13,7 @@ module Technoweenie # :nodoc: def with_image(file, &block) begin binary_data = file.is_a?(Magick::Image) ? file : Magick::Image.read(file).first unless !Object.const_defined?(:Magick) + binary_data && binary_data.auto_orient! rescue # Log the failure to load the image. This should match ::Magick::ImageMagickError # but that would cause acts_as_attachment to require rmagick. @@ -42,11 +43,22 @@ module Technoweenie # :nodoc: if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum)) size = [size, size] if size.is_a?(Fixnum) img.thumbnail!(*size) + elsif size.is_a?(String) && size =~ /^c.*$/ # Image cropping - example geometry string: c75x75 + dimensions = size[1..size.size].split("x") + img.crop_resized!(dimensions[0].to_i, dimensions[1].to_i) else - img.change_geometry(size.to_s) { |cols, rows, image| image.resize!(cols<1 ? 1 : cols, rows<1 ? 1 : rows) } + img.change_geometry(size.to_s) { |cols, rows, image| + image.resize!(cols<1 ? 1 : cols, rows<1 ? 1 : rows) + } end + self.width = img.columns if respond_to?(:width) + self.height = img.rows if respond_to?(:height) + img = img.sharpen if attachment_options[:sharpen_on_resize] && img.changed? img.strip! unless attachment_options[:keep_profile] - self.temp_path = write_to_temp_file(img.to_blob) + quality = img.format.to_s[/JPEG/] && get_jpeg_quality + out_file = write_to_temp_file(img.to_blob { self.quality = quality if quality }) + temp_paths.unshift out_file + self.size = File.size(self.temp_path) end end end diff --git a/vendor/plugins/attachment_fu/rackspace_cloudfiles.yml.tpl b/vendor/plugins/attachment_fu/rackspace_cloudfiles.yml.tpl new file mode 100644 index 0000000..ede689b --- /dev/null +++ b/vendor/plugins/attachment_fu/rackspace_cloudfiles.yml.tpl @@ -0,0 +1,14 @@ +development: + container_name: appname_development + username: + api_key: + +test: + container_name: appname_test + username: + api_key: + +production: + container_name: appname_production + username: + api_key: diff --git a/vendor/plugins/attachment_fu/test/backends/file_system_test.rb b/vendor/plugins/attachment_fu/test/backends/file_system_test.rb index d3250c1..8896477 100644 --- a/vendor/plugins/attachment_fu/test/backends/file_system_test.rb +++ b/vendor/plugins/attachment_fu/test/backends/file_system_test.rb @@ -1,4 +1,5 @@ require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper')) +require 'digest/sha2' class FileSystemTest < Test::Unit::TestCase include BaseAttachmentTests @@ -11,7 +12,7 @@ class FileSystemTest < Test::Unit::TestCase assert_equal attachment.size, File.open(attachment.full_filename).stat.size end end - + test_against_subclass :test_filesystem_size_for_file_attachment, FileAttachment def test_should_not_overwrite_file_attachment(klass = FileAttachment) @@ -21,15 +22,15 @@ class FileSystemTest < Test::Unit::TestCase assert_valid real assert !real.new_record?, real.errors.full_messages.join("\n") assert !real.size.zero? - + fake = upload_file :filename => '/files/fake/rails.png' assert_valid fake assert !fake.size.zero? - + assert_not_equal File.open(real.full_filename).stat.size, File.open(fake.full_filename).stat.size end end - + test_against_subclass :test_should_not_overwrite_file_attachment, FileAttachment def test_should_store_file_attachment_in_filesystem(klass = FileAttachment) @@ -38,13 +39,13 @@ class FileSystemTest < Test::Unit::TestCase assert_created do attachment = upload_file :filename => '/files/rails.png' assert_valid attachment - assert File.exists?(attachment.full_filename), "#{attachment.full_filename} does not exist" + assert File.exists?(attachment.full_filename), "#{attachment.full_filename} does not exist" end attachment end - + test_against_subclass :test_should_store_file_attachment_in_filesystem, FileAttachment - + def test_should_delete_old_file_when_updating(klass = FileAttachment) attachment_model klass attachment = upload_file :filename => '/files/rails.png' @@ -52,16 +53,16 @@ class FileSystemTest < Test::Unit::TestCase assert_not_created do use_temp_file 'files/rails.png' do |file| attachment.filename = 'rails2.png' - attachment.temp_path = File.join(fixture_path, file) + attachment.temp_paths.unshift File.join(FIXTURE_PATH, file) attachment.save! - assert File.exists?(attachment.full_filename), "#{attachment.full_filename} does not exist" + assert File.exists?(attachment.full_filename), "#{attachment.full_filename} does not exist" assert !File.exists?(old_filename), "#{old_filename} still exists" end end end - + test_against_subclass :test_should_delete_old_file_when_updating, FileAttachment - + def test_should_delete_old_file_when_renaming(klass = FileAttachment) attachment_model klass attachment = upload_file :filename => '/files/rails.png' @@ -69,12 +70,74 @@ class FileSystemTest < Test::Unit::TestCase assert_not_created do attachment.filename = 'rails2.png' attachment.save - assert File.exists?(attachment.full_filename), "#{attachment.full_filename} does not exist" + assert File.exists?(attachment.full_filename), "#{attachment.full_filename} does not exist" assert !File.exists?(old_filename), "#{old_filename} still exists" assert !attachment.reload.size.zero? assert_equal 'rails2.png', attachment.filename end end - + test_against_subclass :test_should_delete_old_file_when_renaming, FileAttachment -end \ No newline at end of file + + def test_path_partitioning_works_on_integer_id(klass = FileAttachment) + attachment_model klass + + # Create a random attachment object, doesn't matter what. + attachment = upload_file :filename => '/files/rails.png' + old_id = attachment.id + attachment.id = 1 + + begin + assert_equal ["0000", "0001", "bar.txt"], attachment.send(:partitioned_path, "bar.txt") + ensure + attachment.id = old_id + end + end + + test_against_subclass :test_path_partitioning_works_on_integer_id, FileAttachment + + def test_path_partitioning_with_string_id_works_by_generating_hash(klass = FileAttachmentWithStringId) + attachment_model klass + + # Create a random attachment object, doesn't matter what. + attachment = upload_file :filename => '/files/rails.png' + old_id = attachment.id + attachment.id = "hello world some long string" + hash = Digest::SHA512.hexdigest("hello world some long string") + + begin + assert_equal [ + hash[0..31], + hash[32..63], + hash[64..95], + hash[96..127], + "bar.txt" + ], attachment.send(:partitioned_path, "bar.txt") + ensure + attachment.id = old_id + end + end + + test_against_subclass :test_path_partitioning_with_string_id_works_by_generating_hash, FileAttachmentWithStringId + + def test_path_partition_string_id_hashing_is_turned_off_if_id_is_uuid(klass = FileAttachmentWithUuid) + attachment_model klass + + # Create a random attachment object, doesn't matter what. + attachment = upload_file :filename => '/files/rails.png' + old_id = attachment.id + attachment.id = "0c0743b698483569dc65909a8cdb3bf9" + + begin + assert_equal [ + "0c0743b698483569", + "dc65909a8cdb3bf9", + "bar.txt" + ], attachment.send(:partitioned_path, "bar.txt") + ensure + attachment.id = old_id + end + end + + test_against_subclass :test_path_partition_string_id_hashing_is_turned_off_if_id_is_uuid, FileAttachmentWithUuid +end diff --git a/vendor/plugins/attachment_fu/test/backends/remote/cloudfiles_test.rb b/vendor/plugins/attachment_fu/test/backends/remote/cloudfiles_test.rb new file mode 100644 index 0000000..f36dc09 --- /dev/null +++ b/vendor/plugins/attachment_fu/test/backends/remote/cloudfiles_test.rb @@ -0,0 +1,102 @@ +require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'test_helper')) +require 'net/http' + +class CloudfilesTest < Test::Unit::TestCase + def self.test_CloudFiles? + true unless ENV["TEST_CLOUDFILES"] == "false" + end + + if test_CloudFiles? && File.exist?(File.join(File.dirname(__FILE__), '../../rackspace_cloudfiles.yml')) + include BaseAttachmentTests + attachment_model CloudFilesAttachment + + def test_should_create_correct_container_name(klass = CloudFilesAttachment) + attachment_model klass + attachment = upload_file :filename => '/files/rails.png' + assert_equal attachment.cloudfiles_config[:container_name], attachment.container_name + end + + test_against_subclass :test_should_create_correct_container_name, CloudFilesAttachment + + def test_should_create_default_path_prefix(klass = CloudFilesAttachment) + attachment_model klass + attachment = upload_file :filename => '/files/rails.png' + assert_equal File.join(attachment_model.table_name, attachment.attachment_path_id), attachment.base_path + end + + test_against_subclass :test_should_create_default_path_prefix, CloudFilesAttachment + + def test_should_create_custom_path_prefix(klass = CloudFilesWithPathPrefixAttachment) + attachment_model klass + attachment = upload_file :filename => '/files/rails.png' + assert_equal File.join('some/custom/path/prefix', attachment.attachment_path_id), attachment.base_path + end + + test_against_subclass :test_should_create_custom_path_prefix, CloudFilesWithPathPrefixAttachment + + + def test_should_create_valid_url(klass = CloudFilesAttachment) + attachment_model klass + attachment = upload_file :filename => '/files/rails.png' + assert_match(%r!http://cdn.cloudfiles.mosso.com/(.*?)/cloud_files_attachments/1/rails.png!, attachment.cloudfiles_url) + end + + test_against_subclass :test_should_create_valid_url, CloudFilesAttachment + + def test_should_save_attachment(klass = CloudFilesAttachment) + attachment_model klass + assert_created do + attachment = upload_file :filename => '/files/rails.png' + assert_valid attachment + assert attachment.image? + assert !attachment.size.zero? + assert_kind_of Net::HTTPOK, http_response_for(attachment.cloudfiles_url) + end + end + + test_against_subclass :test_should_save_attachment, CloudFilesAttachment + + def test_should_delete_attachment_from_cloud_files_when_attachment_record_destroyed(klass = CloudFilesAttachment) + attachment_model klass + attachment = upload_file :filename => '/files/rails.png' + + urls = [attachment.cloudfiles_url] + attachment.thumbnails.collect(&:cloudfiles_url) + + urls.each {|url| assert_kind_of Net::HTTPOK, http_response_for(url) } + attachment.destroy + urls.each do |url| + begin + http_response_for(url) + rescue Net::HTTPForbidden, Net::HTTPNotFound + nil + end + end + end + + test_against_subclass :test_should_delete_attachment_from_cloud_files_when_attachment_record_destroyed, CloudFilesAttachment + + + + protected + def http_response_for(url) + url = URI.parse(url) + Net::HTTP.start(url.host, url.port) {|http| http.request_head(url.path) } + end + + def s3_protocol + Technoweenie::AttachmentFu::Backends::S3Backend.protocol + end + + def s3_hostname + Technoweenie::AttachmentFu::Backends::S3Backend.hostname + end + + def s3_port_string + Technoweenie::AttachmentFu::Backends::S3Backend.port_string + end + else + def test_flunk_s3 + puts "s3 config file not loaded, tests not running" + end + end +end \ No newline at end of file diff --git a/vendor/plugins/attachment_fu/test/backends/remote/s3_test.rb b/vendor/plugins/attachment_fu/test/backends/remote/s3_test.rb index bc27720..c7cb4f9 100644 --- a/vendor/plugins/attachment_fu/test/backends/remote/s3_test.rb +++ b/vendor/plugins/attachment_fu/test/backends/remote/s3_test.rb @@ -49,6 +49,18 @@ class S3Test < Test::Unit::TestCase end test_against_subclass :test_should_create_authenticated_url, S3Attachment + + def test_should_create_authenticated_url_for_thumbnail(klass = S3Attachment) + attachment_model klass + attachment = upload_file :filename => '/files/rails.png' + ['large', :large].each do |thumbnail| + assert_match( + /^http.+rails_large\.png.+AWSAccessKeyId.+Expires.+Signature/, + attachment.authenticated_s3_url(thumbnail), + "authenticated_s3_url failed with #{thumbnail.class} parameter" + ) + end + end def test_should_save_attachment(klass = S3Attachment) attachment_model klass diff --git a/vendor/plugins/attachment_fu/test/base_attachment_tests.rb b/vendor/plugins/attachment_fu/test/base_attachment_tests.rb index c9dbbd7..75fc7e3 100644 --- a/vendor/plugins/attachment_fu/test/base_attachment_tests.rb +++ b/vendor/plugins/attachment_fu/test/base_attachment_tests.rb @@ -1,10 +1,23 @@ module BaseAttachmentTests def test_should_create_file_from_uploaded_file assert_created do - attachment = upload_file :filename => '/files/foo.txt' + attachment = upload_file :filename => '/files/foo.txt', :content_type => 'text/plain' assert_valid attachment assert !attachment.db_file.new_record? if attachment.respond_to?(:db_file) - assert attachment.image? + assert !attachment.image? + assert !attachment.size.zero? + #assert_equal 3, attachment.size + assert_nil attachment.width + assert_nil attachment.height + end + end + + def test_should_create_file_from_merb_temp_file + assert_created do + attachment = upload_merb_file :filename => '/files/foo.txt', :content_type => 'text/plain' + assert_valid attachment + assert !attachment.db_file.new_record? if attachment.respond_to?(:db_file) + assert !attachment.image? assert !attachment.size.zero? #assert_equal 3, attachment.size assert_nil attachment.width @@ -18,7 +31,7 @@ module BaseAttachmentTests assert_valid attachment assert attachment.size > 0, "no data was set" - attachment.temp_data = 'wtf' + attachment.set_temp_data 'wtf' assert attachment.save_attachment? attachment.save! @@ -32,7 +45,7 @@ module BaseAttachmentTests assert_valid attachment assert attachment.size > 0, "no data was set" - attachment.temp_data = nil + attachment.set_temp_data nil assert !attachment.save_attachment? end end @@ -42,7 +55,7 @@ module BaseAttachmentTests assert_not_created do # no new db_file records use_temp_file 'files/rails.png' do |file| attachment.filename = 'rails2.png' - attachment.temp_path = File.join(fixture_path, file) + attachment.temp_paths.unshift File.join(FIXTURE_PATH, file) attachment.save! end end @@ -54,4 +67,11 @@ module BaseAttachmentTests assert !attachment.save_attachment? assert_nothing_raised { attachment.save! } end + + def test_should_handle_nil_file_upload + attachment = attachment_model.create :uploaded_data => '' + assert_raise ActiveRecord::RecordInvalid do + attachment.save! + end + end end \ No newline at end of file diff --git a/vendor/plugins/attachment_fu/test/basic_test.rb b/vendor/plugins/attachment_fu/test/basic_test.rb index f8f881c..a0a1ad6 100644 --- a/vendor/plugins/attachment_fu/test/basic_test.rb +++ b/vendor/plugins/attachment_fu/test/basic_test.rb @@ -1,18 +1,19 @@ +# -*- coding: utf-8 -*- require File.expand_path(File.join(File.dirname(__FILE__), 'test_helper')) class BasicTest < Test::Unit::TestCase def test_should_set_default_min_size assert_equal 1, Attachment.attachment_options[:min_size] end - + def test_should_set_default_max_size assert_equal 1.megabyte, Attachment.attachment_options[:max_size] end - + def test_should_set_default_size assert_equal (1..1.megabyte), Attachment.attachment_options[:size] end - + def test_should_set_default_thumbnails_option assert_equal Hash.new, Attachment.attachment_options[:thumbnails] end @@ -20,19 +21,19 @@ class BasicTest < Test::Unit::TestCase def test_should_set_default_thumbnail_class assert_equal Attachment, Attachment.attachment_options[:thumbnail_class] end - + def test_should_normalize_content_types_to_array assert_equal %w(pdf), PdfAttachment.attachment_options[:content_type] assert_equal %w(pdf doc txt), DocAttachment.attachment_options[:content_type] - assert_equal ['image/jpeg', 'image/pjpeg', 'image/gif', 'image/png', 'image/x-png', 'image/jpg'], ImageAttachment.attachment_options[:content_type] - assert_equal ['pdf', 'image/jpeg', 'image/pjpeg', 'image/gif', 'image/png', 'image/x-png', 'image/jpg'], ImageOrPdfAttachment.attachment_options[:content_type] + assert_equal Technoweenie::AttachmentFu.content_types, ImageAttachment.attachment_options[:content_type] + assert_equal ['pdf'] + Technoweenie::AttachmentFu.content_types, ImageOrPdfAttachment.attachment_options[:content_type] end - + def test_should_sanitize_content_type @attachment = Attachment.new :content_type => ' foo ' assert_equal 'foo', @attachment.content_type end - + def test_should_sanitize_filenames @attachment = Attachment.new :filename => 'blah/foo.bar' assert_equal 'foo.bar', @attachment.filename @@ -42,23 +43,79 @@ class BasicTest < Test::Unit::TestCase @attachment.filename = 'f o!O-.bar' assert_equal 'f_o_O-.bar', @attachment.filename + +# @attachment.filename = 'sheeps_says_bææ' +# assert_equal 'sheeps_says_b__', @attachment.filename + + @attachment.filename = nil + assert_nil @attachment.filename end - + def test_should_convert_thumbnail_name @attachment = FileAttachment.new :filename => 'foo.bar' assert_equal 'foo.bar', @attachment.thumbnail_name_for(nil) assert_equal 'foo.bar', @attachment.thumbnail_name_for('') assert_equal 'foo_blah.bar', @attachment.thumbnail_name_for(:blah) assert_equal 'foo_blah.blah.bar', @attachment.thumbnail_name_for('blah.blah') - + @attachment.filename = 'foo.bar.baz' assert_equal 'foo.bar_blah.baz', @attachment.thumbnail_name_for(:blah) end - + def test_should_require_valid_thumbnails_option klass = Class.new(ActiveRecord::Base) assert_raise ArgumentError do klass.has_attachment :thumbnails => [] end end -end \ No newline at end of file + + class ::ImageWithPolymorphicThumbsAttachment + cattr_accessor :thumbnail_creations + + def create_or_update_thumbnail(path, thumb, *size) + @@thumbnail_creations[thumb] = size.size == 1 ? size.first : size + end + + def self.reset_creations + @@thumbnail_creations = {} + end + end + + def test_should_handle_polymorphic_thumbnails_option + assert_polymorphic_thumb_creation nil, + :thumb => [50, 50], :geometry => 'x50' + assert_polymorphic_thumb_creation 'Product', + :thumb => [50, 50], :geometry => 'x50', :large_thumb => '169x169!', :zoomed => '500x500>' + assert_polymorphic_thumb_creation 'Editorial', + :thumb => [50, 50], :geometry => 'x50', :fullsize => '150x100>' + assert_polymorphic_thumb_creation 'User', + :thumb => [50, 50], :geometry => 'x50', :avatar => '64x64!' + end + + def test_should_compute_per_thumbnail_jpeg_quality + assert_jpeg_quality :thumb, 90 + assert_jpeg_quality :avatar, 85 + assert_jpeg_quality :large, 75 + assert_jpeg_quality :large, 0x200 | 75, false + assert_jpeg_quality nil, 75 + end + +private + def assert_jpeg_quality(thumbnail, quality, require_0_to_100 = true) + klass = ImageWithPerThumbJpegAttachment + w, h = if thumbnail + klass.attachment_options[:thumbnails][thumbnail].scan(/\d+/) + else + klass.attachment_options[:resize_to].scan(/\d+/) + end + attachment = klass.new(:thumbnail => thumbnail, :width => w, :height => h) + assert_equal quality, attachment.send(:get_jpeg_quality, require_0_to_100) + end + + def assert_polymorphic_thumb_creation(parent, defs) + attachment_model ImageWithPolymorphicThumbsAttachment + attachment_model.reset_creations + attachment = upload_file :filename => '/files/rails.png', :imageable_type => parent.to_s.classify, :imageable_id => nil + assert_equal defs, attachment_model.thumbnail_creations + end +end diff --git a/vendor/plugins/attachment_fu/test/database.yml b/vendor/plugins/attachment_fu/test/database.yml index 1c6ece7..3e8ef3e 100644 --- a/vendor/plugins/attachment_fu/test/database.yml +++ b/vendor/plugins/attachment_fu/test/database.yml @@ -1,9 +1,9 @@ sqlite: :adapter: sqlite - :dbfile: attachment_fu_plugin.sqlite.db + :database: attachment_fu_plugin.sqlite.db sqlite3: :adapter: sqlite3 - :dbfile: attachment_fu_plugin.sqlite3.db + :database: attachment_fu_plugin.sqlite3.db postgresql: :adapter: postgresql :username: postgres diff --git a/vendor/plugins/attachment_fu/test/extra_attachment_test.rb b/vendor/plugins/attachment_fu/test/extra_attachment_test.rb index 15b1852..6c58554 100644 --- a/vendor/plugins/attachment_fu/test/extra_attachment_test.rb +++ b/vendor/plugins/attachment_fu/test/extra_attachment_test.rb @@ -24,6 +24,16 @@ class OrphanAttachmentTest < Test::Unit::TestCase end end + def test_should_create_file_from_merb_temp_file + assert_created do + attachment = upload_merb_file :filename => '/files/foo.txt' + assert_valid attachment + assert !attachment.db_file.new_record? if attachment.respond_to?(:db_file) + assert attachment.image? + assert !attachment.size.zero? + end + end + def test_should_create_image_from_uploaded_file_with_custom_content_type assert_created do attachment = upload_file :content_type => 'foo/bar', :filename => '/files/rails.png' diff --git a/vendor/plugins/attachment_fu/test/fixtures/attachment.rb b/vendor/plugins/attachment_fu/test/fixtures/attachment.rb index 7476d7d..7c3b32e 100644 --- a/vendor/plugins/attachment_fu/test/fixtures/attachment.rb +++ b/vendor/plugins/attachment_fu/test/fixtures/attachment.rb @@ -3,11 +3,16 @@ class Attachment < ActiveRecord::Base cattr_accessor :saves has_attachment :processor => :rmagick validates_as_attachment - after_attachment_saved do |record| + after_save do |record| self.saves += 1 end end +class LowerQualityAttachment < Attachment + self.table_name = 'attachments' + has_attachment :resize_to => [55,55], :jpeg_quality => 50 +end + class SmallAttachment < Attachment has_attachment :max_size => 1.kilobyte end @@ -34,9 +39,26 @@ end class ImageWithThumbsAttachment < Attachment has_attachment :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }, :resize_to => [55,55] - after_resize do |record, img| - record.aspect_ratio = img.columns.to_f / img.rows.to_f - end + # after_resize do |record, img| + # record.aspect_ratio = img.columns.to_f / img.rows.to_f + # end +end + +class ImageWithPerThumbJpegAttachment < Attachment + has_attachment :resize_to => '500x500!', + :thumbnails => { :thumb => '50x50!', :large => '300x300!', :avatar => '64x64!' }, + :jpeg_quality => { :thumb => 90, '<5000' => 85, '>=5000' => 75, :large => 0x200 | 75 } +end + +class ImageWithPolymorphicThumbsAttachment < Attachment + belongs_to :imageable, :polymorphic => true + has_attachment :thumbnails => { + :thumb => [50, 50], + :geometry => 'x50', + :products => { :large_thumb => '169x169!', :zoomed => '500x500>' }, + :editorials => { :fullsize => '150x100>' }, + 'User' => { :avatar => '64x64!' } + } end class FileAttachment < ActiveRecord::Base @@ -44,6 +66,38 @@ class FileAttachment < ActiveRecord::Base validates_as_attachment end +class FileAttachmentWithStringId < ActiveRecord::Base + self.table_name = 'file_attachments_with_string_id' + has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', :processor => :rmagick + validates_as_attachment + + before_validation :auto_generate_id + before_save :auto_generate_id + @@last_id = 0 + + private + def auto_generate_id + @@last_id += 1 + self.id = "id_#{@@last_id}" + end +end + +class FileAttachmentWithUuid < ActiveRecord::Base + self.table_name = 'file_attachments_with_string_id' + has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', :processor => :rmagick, :uuid_primary_key => true + validates_as_attachment + + before_validation :auto_generate_id + before_save :auto_generate_id + @@last_id = 0 + + private + def auto_generate_id + @@last_id += 1 + self.id = "%0127dx" % @@last_id + end +end + class ImageFileAttachment < FileAttachment has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', :content_type => :image, :resize_to => [50,50] @@ -52,9 +106,9 @@ end class ImageWithThumbsFileAttachment < FileAttachment has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }, :resize_to => [55,55] - after_resize do |record, img| - record.aspect_ratio = img.columns.to_f / img.rows.to_f - end + # after_resize do |record, img| + # record.aspect_ratio = img.columns.to_f / img.rows.to_f + # end end class ImageWithThumbsClassFileAttachment < FileAttachment @@ -78,7 +132,7 @@ end class MinimalAttachment < ActiveRecord::Base has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', :processor => :rmagick validates_as_attachment - + def filename "#{id}.file" end @@ -87,7 +141,22 @@ end begin class ImageScienceAttachment < ActiveRecord::Base has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', - :processor => :image_science, :thumbnails => { :thumb => [50, 51], :geometry => '31>' }, :resize_to => 55 + :processor => :image_science, :thumbnails => { :thumb => [50, 51], :geometry => '31>', :aspect => '25x25!' }, :resize_to => 55 + end + + class ImageScienceLowerQualityAttachment < ActiveRecord::Base + self.table_name = 'image_science_attachments' + has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', + :processor => :image_science, :thumbnails => { :thumb => [50, 51], :geometry => '31>', :aspect => '25x25!' }, :resize_to => 55, + :jpeg_quality => 75 + end + + class ImageScienceWithPerThumbJpegAttachment < ImageScienceAttachment + has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', + :processor => :image_science, + :resize_to => '100x100', + :thumbnails => { :thumb => [50, 50], :editorial => '300x120', :avatar => '64x64!' }, + :jpeg_quality => { :thumb => 90, '<5000' => 80, '>=5000' => 75 } end rescue MissingSourceFile puts $!.message @@ -97,7 +166,21 @@ end begin class CoreImageAttachment < ActiveRecord::Base has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', - :processor => :core_image, :thumbnails => { :thumb => [50, 51], :geometry => '31>' }, :resize_to => 55 + :processor => :core_image, :thumbnails => { :thumb => [50, 51], :geometry => '31>', :aspect => '25x25!' }, :resize_to => 55 + end + + class LowerQualityCoreImageAttachment < CoreImageAttachment + has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', + :processor => :core_image, :thumbnails => { :thumb => [50, 51], :geometry => '31>', :aspect => '25x25!' }, :resize_to => 55, + :jpeg_quality => 50 + end + + class CoreImageWithPerThumbJpegAttachment < CoreImageAttachment + has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', + :processor => :core_image, + :resize_to => '100x100', + :thumbnails => { :thumb => [50, 50], :editorial => '300x120', :avatar => '64x64!' }, + :jpeg_quality => { :thumb => 90, '<5000' => 80, '>=5000' => 75 } end rescue MissingSourceFile puts $!.message @@ -107,8 +190,57 @@ end begin class MiniMagickAttachment < ActiveRecord::Base has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', - :processor => :mini_magick, :thumbnails => { :thumb => [50, 51], :geometry => '31>' }, :resize_to => 55 + :processor => :mini_magick, :thumbnails => { :thumb => [50, 51], :geometry => '31>', :aspect => '25x25!' }, :resize_to => 55 end + + class ImageThumbnailCrop < MiniMagickAttachment + has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', + :thumbnails => { :square => "50x50c", :vertical => "30x60c", :horizontal => "60x30c"} + + # TODO this is a bad duplication, this method is in the MiniMagick Processor + def self.calculate_offset(image_width,image_height,image_aspect,thumb_width,thumb_height,thumb_aspect) + # only crop if image is not smaller in both dimensions + + # special cases, image smaller in one dimension then thumbsize + if image_width < thumb_width + offset = (image_height / 2) - (thumb_height / 2) + command = "#{image_width}x#{thumb_height}+0+#{offset}" + elsif image_height < thumb_height + offset = (image_width / 2) - (thumb_width / 2) + command = "#{thumb_width}x#{image_height}+#{offset}+0" + + # normal thumbnail generation + # calculate height and offset y, width is fixed + elsif (image_aspect <= thumb_aspect or image_width < thumb_width) and image_height > thumb_height + height = image_width / thumb_aspect + offset = (image_height / 2) - (height / 2) + command = "#{image_width}x#{height}+0+#{offset}" + # calculate width and offset x, height is fixed + else + width = image_height * thumb_aspect + offset = (image_width / 2) - (width / 2) + command = "#{width}x#{image_height}+#{offset}+0" + end + # crop image + command + end + end + + class LowerQualityMiniMagickAttachment < ActiveRecord::Base + self.table_name = 'mini_magick_attachments' + has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', + :processor => :mini_magick, :thumbnails => { :thumb => [50, 51], :geometry => '31>', :aspect => '25x25!' }, :resize_to => 55, + :jpeg_quality => 50 + end + + class MiniMagickWithPerThumbJpegAttachment < MiniMagickAttachment + has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', + :processor => :mini_magick, + :resize_to => '100x100', + :thumbnails => { :thumb => [50, 50], :editorial => '300x120', :avatar => '64x64!' }, + :jpeg_quality => { :thumb => 90, '<5000' => 80, '>=5000' => 75 } + end + rescue MissingSourceFile puts $!.message puts "no Mini Magick" @@ -117,32 +249,49 @@ end begin class GD2Attachment < ActiveRecord::Base has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', - :processor => :gd2, :thumbnails => { :thumb => [50, 51], :geometry => '31>' }, :resize_to => 55 + :processor => :gd2, :thumbnails => { :thumb => [50, 51], :geometry => '31>', :aspect => '25x25!' }, :resize_to => 55 end -rescue MissingSourceFile - puts $!.message - puts "no GD2" -end + class LowerQualityGD2Attachment < GD2Attachment + has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', + :processor => :gd2, :thumbnails => { :thumb => [50, 51], :geometry => '31>', :aspect => '25x25!' }, :resize_to => 55, + :jpeg_quality => 50 + end -begin - class MiniMagickAttachment < ActiveRecord::Base + class GD2WithPerThumbJpegAttachment < GD2Attachment has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', - :processor => :mini_magick, :thumbnails => { :thumb => [50, 51], :geometry => '31>' }, :resize_to => 55 + :processor => :gd2, + :resize_to => '100x100', + :thumbnails => { :thumb => [50, 50], :editorial => '300x120', :avatar => '64x64!' }, + :jpeg_quality => { :thumb => 90, '<5000' => 80, '>=5000' => 75 } end rescue MissingSourceFile + puts $!.message + puts "no GD2" end + begin class S3Attachment < ActiveRecord::Base has_attachment :storage => :s3, :processor => :rmagick, :s3_config_path => File.join(File.dirname(__FILE__), '../amazon_s3.yml') validates_as_attachment end + class CloudFilesAttachment < ActiveRecord::Base + has_attachment :storage => :cloud_files, :processor => :rmagick, :cloudfiles_config_path => File.join(File.dirname(__FILE__), '../rackspace_cloudfiles.yml') + validates_as_attachment + end + class S3WithPathPrefixAttachment < S3Attachment has_attachment :storage => :s3, :path_prefix => 'some/custom/path/prefix', :processor => :rmagick validates_as_attachment end + + class CloudFilesWithPathPrefixAttachment < CloudFilesAttachment + has_attachment :storage => :cloud_files, :path_prefix => 'some/custom/path/prefix', :processor => :rmagick + validates_as_attachment + end + rescue puts "S3 error: #{$!}" end diff --git a/vendor/plugins/attachment_fu/test/fixtures/files/rails.jpg b/vendor/plugins/attachment_fu/test/fixtures/files/rails.jpg new file mode 100644 index 0000000..c2a94bc Binary files /dev/null and b/vendor/plugins/attachment_fu/test/fixtures/files/rails.jpg differ diff --git a/vendor/plugins/attachment_fu/test/geometry_test.rb b/vendor/plugins/attachment_fu/test/geometry_test.rb index ade4f48..c4df31c 100644 --- a/vendor/plugins/attachment_fu/test/geometry_test.rb +++ b/vendor/plugins/attachment_fu/test/geometry_test.rb @@ -23,6 +23,13 @@ class GeometryTest < Test::Unit::TestCase "100" => [100, 128] end + def test_should_resize_no_height_with_x + assert_geometry 50, 64, + "50x" => [50, 64], + "60x" => [60, 77], + "100x" => [100, 128] + end + def test_should_resize_with_percent assert_geometry 50, 64, "50x50%" => [25, 32], @@ -90,6 +97,12 @@ class GeometryTest < Test::Unit::TestCase "100>" => [50, 64] end + def test_should_resize_with_aspect + assert_geometry 50, 64, + "35x35!" => [35, 35], + "70x70!" => [70, 70] + end + protected def assert_geometry(width, height, values) values.each do |geo, result| diff --git a/vendor/plugins/attachment_fu/test/processors/core_image_test.rb b/vendor/plugins/attachment_fu/test/processors/core_image_test.rb index 09a9bbd..cf1f662 100644 --- a/vendor/plugins/attachment_fu/test/processors/core_image_test.rb +++ b/vendor/plugins/attachment_fu/test/processors/core_image_test.rb @@ -14,14 +14,41 @@ class CoreImageTest < Test::Unit::TestCase thumb = attachment.thumbnails.detect { |t| t.filename =~ /_thumb/ } geo = attachment.thumbnails.detect { |t| t.filename =~ /_geometry/ } + aspect = attachment.thumbnails.detect { |t| t.filename =~ /_aspect/ } # test exact resize dimensions assert_equal 50, thumb.width assert_equal 51, thumb.height - # test geometry string + # test geometry strings assert_equal 31, geo.width assert_equal 41, geo.height + assert_equal 25, aspect.width + assert_equal 25, aspect.height + + # This makes sure that we didn't overwrite the original file + # and will end up with a thumbnail instead of the original + assert_equal 42, attachment.width + assert_equal 55, attachment.height + + end + + def test_should_handle_jpeg_quality + attachment_model CoreImageAttachment + attachment = upload_file :filename => '/files/rails.jpg', :content_type => 'image/jpeg' + full_size = attachment.size + attachment_model LowerQualityCoreImageAttachment + attachment = upload_file :filename => '/files/rails.jpg', :content_type => 'image/jpeg' + lq_size = attachment.size + assert lq_size <= full_size * 0.9, 'Lower-quality JPEG filesize should be congruently smaller' + + # FIXME: wait for Marcus' reply to determine whether I can get exact-quality output or need to adjust for CoreImage. + # attachment_model CoreImageWithPerThumbJpegAttachment + # attachment = upload_file :filename => '/files/rails.jpg', :content_type => 'image/jpeg' + # assert_file_jpeg_quality attachment, :thumb, 90 + # assert_file_jpeg_quality attachment, :avatar, 80 + # assert_file_jpeg_quality attachment, :editorial, 75 + # assert_file_jpeg_quality attachment, nil, 75 end else def test_flunk diff --git a/vendor/plugins/attachment_fu/test/processors/gd2_test.rb b/vendor/plugins/attachment_fu/test/processors/gd2_test.rb index 298853b..c6484bf 100644 --- a/vendor/plugins/attachment_fu/test/processors/gd2_test.rb +++ b/vendor/plugins/attachment_fu/test/processors/gd2_test.rb @@ -12,16 +12,36 @@ class GD2Test < Test::Unit::TestCase assert_equal 43, attachment.width assert_equal 55, attachment.height - thumb = attachment.thumbnails.detect { |t| t.filename =~ /_thumb/ } - geo = attachment.thumbnails.detect { |t| t.filename =~ /_geometry/ } + thumb = attachment.thumbnails.detect { |t| t.filename =~ /_thumb/ } + geo = attachment.thumbnails.detect { |t| t.filename =~ /_geometry/ } + aspect = attachment.thumbnails.detect { |t| t.filename =~ /_aspect/ } # test exact resize dimensions assert_equal 50, thumb.width assert_equal 51, thumb.height - # test geometry string + # test geometry strings assert_equal 31, geo.width assert_equal 40, geo.height + assert_equal 25, aspect.width + assert_equal 25, aspect.height + end + + def test_should_handle_jpeg_quality + attachment_model GD2Attachment + attachment = upload_file :filename => '/files/rails.jpg', :content_type => 'image/jpeg' + full_size = attachment.size + attachment_model LowerQualityGD2Attachment + attachment = upload_file :filename => '/files/rails.jpg', :content_type => 'image/jpeg' + lq_size = attachment.size + assert lq_size <= full_size * 0.9, 'Lower-quality JPEG filesize should be congruently smaller' + + attachment_model GD2WithPerThumbJpegAttachment + attachment = upload_file :filename => '/files/rails.jpg', :content_type => 'image/jpeg' + assert_file_jpeg_quality attachment, :thumb, 90 + assert_file_jpeg_quality attachment, :avatar, 80 + assert_file_jpeg_quality attachment, :editorial, 75 + assert_file_jpeg_quality attachment, nil, 75 end else def test_flunk diff --git a/vendor/plugins/attachment_fu/test/processors/image_science_test.rb b/vendor/plugins/attachment_fu/test/processors/image_science_test.rb index 636918d..2b04277 100644 --- a/vendor/plugins/attachment_fu/test/processors/image_science_test.rb +++ b/vendor/plugins/attachment_fu/test/processors/image_science_test.rb @@ -14,14 +14,37 @@ class ImageScienceTest < Test::Unit::TestCase thumb = attachment.thumbnails.detect { |t| t.filename =~ /_thumb/ } geo = attachment.thumbnails.detect { |t| t.filename =~ /_geometry/ } + aspect = attachment.thumbnails.detect { |t| t.filename =~ /_aspect/ } # test exact resize dimensions assert_equal 50, thumb.width assert_equal 51, thumb.height - # test geometry string + # test geometry strings assert_equal 31, geo.width assert_equal 41, geo.height + assert_equal 25, aspect.width + assert_equal 25, aspect.height + end + + def test_should_handle_jpeg_quality + attachment = upload_file :filename => '/files/rails.jpg', :content_type => 'image/jpeg' + full_size = attachment.size + attachment_model ImageScienceLowerQualityAttachment + attachment = upload_file :filename => '/files/rails.jpg', :content_type => 'image/jpeg' + lq_size = attachment.size + if ImageScience.instance_method(:save).arity == -2 # tdd-image_science: JPEG quality processing + assert lq_size <= full_size * 0.75, 'Lower-quality JPEG filesize should be congruently smaller' + else + assert_equal full_size, lq_size, 'Unsupported lower-quality JPEG should yield exact same file size' + end + + attachment_model ImageScienceWithPerThumbJpegAttachment + attachment = upload_file :filename => '/files/rails.jpg', :content_type => 'image/jpeg' + assert_file_jpeg_quality attachment, :thumb, 90 + assert_file_jpeg_quality attachment, :avatar, 80 + assert_file_jpeg_quality attachment, :editorial, 75 + assert_file_jpeg_quality attachment, nil, 75 end else def test_flunk diff --git a/vendor/plugins/attachment_fu/test/processors/mini_magick_test.rb b/vendor/plugins/attachment_fu/test/processors/mini_magick_test.rb index 244a4a2..12e621f 100644 --- a/vendor/plugins/attachment_fu/test/processors/mini_magick_test.rb +++ b/vendor/plugins/attachment_fu/test/processors/mini_magick_test.rb @@ -14,18 +14,109 @@ class MiniMagickTest < Test::Unit::TestCase thumb = attachment.thumbnails.detect { |t| t.filename =~ /_thumb/ } geo = attachment.thumbnails.detect { |t| t.filename =~ /_geometry/ } + aspect = attachment.thumbnails.detect { |t| t.filename =~ /_aspect/ } # test exact resize dimensions assert_equal 50, thumb.width assert_equal 51, thumb.height - # test geometry string + # test geometry strings assert_equal 31, geo.width assert_equal 40, geo.height + assert_equal 25, aspect.width + assert_equal 25, aspect.height + end + + def test_should_crop_image(klass = ImageThumbnailCrop) + attachment_model klass + attachment = upload_file :filename => '/files/rails.png' + assert_valid attachment + assert attachment.image? + # has_attachment :thumbnails => { :square => "50x50c", :vertical => "30x60c", :horizontal => "60x30c"} + + square = attachment.thumbnails.detect { |t| t.filename =~ /_square/ } + vertical = attachment.thumbnails.detect { |t| t.filename =~ /_vertical/ } + horizontal = attachment.thumbnails.detect { |t| t.filename =~ /_horizontal/ } + + # test excat resize + assert_equal 50, square.width + assert_equal 50, square.height + + assert_equal 30, vertical.width + assert_equal 60, vertical.height + + assert_equal 60, horizontal.width + assert_equal 30, horizontal.height + end + + # tests the first step in resize, crop the image in original size to right format + def test_should_crop_image_right(klass = ImageThumbnailCrop) + @@testcases.collect do |testcase| + image_width, image_height, thumb_width, thumb_height = testcase[:data] + image_aspect, thumb_aspect = image_width/image_height, thumb_width/thumb_height + crop_comand = klass.calculate_offset(image_width, image_height, image_aspect, thumb_width, thumb_height,thumb_aspect) + # pattern matching on crop command + if testcase.has_key?(:height) + assert crop_comand.match(/^#{image_width}x#{testcase[:height]}\+0\+#{testcase[:yoffset]}$/) + else + assert crop_comand.match(/^#{testcase[:width]}x#{image_height}\+#{testcase[:xoffset]}\+0$/) + end + end + end + + def test_should_handle_jpeg_quality + attachment_model MiniMagickAttachment + attachment = upload_file :filename => '/files/rails.jpg', :content_type => 'image/jpeg' + full_size = attachment.size + attachment_model LowerQualityMiniMagickAttachment + attachment = upload_file :filename => '/files/rails.jpg', :content_type => 'image/jpeg' + lq_size = attachment.size + assert lq_size <= full_size * 0.9, 'Lower-quality JPEG filesize should be congruently smaller' + + attachment_model MiniMagickWithPerThumbJpegAttachment + attachment = upload_file :filename => '/files/rails.jpg', :content_type => 'image/jpeg' + assert_file_jpeg_quality attachment, :thumb, 90 + assert_file_jpeg_quality attachment, :avatar, 80 + assert_file_jpeg_quality attachment, :editorial, 75 + assert_file_jpeg_quality attachment, nil, 75 end else def test_flunk puts "MiniMagick not loaded, tests not running" end end + + @@testcases = [ + # image_aspect <= 1 && thumb_aspect >= 1 + {:data => [10.0,40.0,2.0,1.0], :height => 5.0, :yoffset => 17.5}, # 1b + {:data => [10.0,40.0,1.0,1.0], :height => 10.0, :yoffset => 15.0}, # 1b + + # image_aspect < 1 && thumb_aspect < 1 + {:data => [10.0,40.0,1.0,2.0], :height => 20.0, :yoffset => 10.0}, # 1a + {:data => [2.0,3.0,1.0,2.0], :width => 1.5, :xoffset => 0.25}, # 1a + + # image_aspect = thumb_aspect + {:data => [10.0,10.0,1.0,1.0], :height => 10.0, :yoffset => 0.0}, # QUADRAT 1c + + # image_aspect >= 1 && thumb_aspect > 1 && image_aspect < thumb_aspect + {:data => [6.0,3.0,4.0,1.0], :height => 1.5, :yoffset => 0.75}, # 2b + {:data => [6.0,6.0,4.0,1.0], :height => 1.5, :yoffset => 2.25}, # 2b + + # image_aspect > 1 && thumb_aspect > 1 && image_aspect > thumb_aspect + {:data => [9.0,3.0,2.0,1.0], :width => 6.0, :xoffset => 1.5}, # 2a + + # image_aspect > 1 && thumb_aspect < 1 && image_aspect < thumb_aspect + {:data => [10.0,5.0,0.1,2.0], :width => 0.25, :xoffset => 4.875}, # 4 + {:data => [10.0,5.0,1.0,2.0], :width => 2.5, :xoffset => 3.75}, # 4 + + # image_aspect > 1 && thumb_aspect > 1 && image_aspect > thumb_aspect + {:data => [9.0,3.0,2.0,1.0], :width => 6.0, :xoffset => 1.5}, # 3a + # image_aspect > 1 && thumb_aspect > 1 && image_aspect < thumb_aspect + {:data => [9.0,3.0,5.0,1.0], :height => 1.8, :yoffset => 0.6} # 3a + ] + + + + + end diff --git a/vendor/plugins/attachment_fu/test/processors/rmagick_test.rb b/vendor/plugins/attachment_fu/test/processors/rmagick_test.rb index 98b67dd..1571dcb 100644 --- a/vendor/plugins/attachment_fu/test/processors/rmagick_test.rb +++ b/vendor/plugins/attachment_fu/test/processors/rmagick_test.rb @@ -1,5 +1,4 @@ require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper')) - class RmagickTest < Test::Unit::TestCase attachment_model Attachment @@ -49,20 +48,21 @@ class RmagickTest < Test::Unit::TestCase end end - def test_should_create_thumbnail_with_geometry_string + def test_should_create_thumbnail_with_geometry_strings attachment = upload_file :filename => '/files/rails.png' assert_created do basename, ext = attachment.filename.split '.' - thumbnail = attachment.create_or_update_thumbnail(attachment.create_temp_file, 'thumb', 'x50') - assert_valid thumbnail - assert !thumbnail.size.zero? - #assert_equal 3915, thumbnail.size - assert_equal 39, thumbnail.width - assert_equal 50, thumbnail.height - assert_equal [thumbnail], attachment.thumbnails - assert_equal attachment.id, thumbnail.parent_id if thumbnail.respond_to?(:parent_id) - assert_equal "#{basename}_thumb.#{ext}", thumbnail.filename + { 'x50' => [39, 50], '25x25!' => [25, 25] }.each do |geo, (w, h)| + thumbnail = attachment.create_or_update_thumbnail(attachment.create_temp_file, 'thumb', geo) + assert_valid thumbnail + assert !thumbnail.size.zero? + assert_equal w, thumbnail.width + assert_equal h, thumbnail.height + assert_equal [thumbnail], attachment.thumbnails + assert_equal attachment.id, thumbnail.parent_id if thumbnail.respond_to?(:parent_id) + assert_equal "#{basename}_thumb.#{ext}", thumbnail.filename + end end end @@ -123,7 +123,7 @@ class RmagickTest < Test::Unit::TestCase assert_equal 55, attachment.width assert_equal 55, attachment.height assert_equal 2, attachment.thumbnails.length - assert_equal 1.0, attachment.aspect_ratio + # assert_equal 1.0, attachment.aspect_ratio thumb = attachment.thumbnails.detect { |t| t.filename =~ /_thumb/ } assert !thumb.new_record?, thumb.errors.full_messages.join("\n") @@ -131,7 +131,7 @@ class RmagickTest < Test::Unit::TestCase #assert_in_delta 4673, thumb.size, 2 assert_equal 50, thumb.width assert_equal 50, thumb.height - assert_equal 1.0, thumb.aspect_ratio + # assert_equal 1.0, thumb.aspect_ratio geo = attachment.thumbnails.detect { |t| t.filename =~ /_geometry/ } assert !geo.new_record?, geo.errors.full_messages.join("\n") @@ -139,7 +139,7 @@ class RmagickTest < Test::Unit::TestCase #assert_equal 3915, geo.size assert_equal 50, geo.width assert_equal 50, geo.height - assert_equal 1.0, geo.aspect_ratio + # assert_equal 1.0, geo.aspect_ratio end end @@ -181,7 +181,7 @@ class RmagickTest < Test::Unit::TestCase assert_not_created do use_temp_file "files/rails.png" do |file| attachment.filename = 'rails2.png' - attachment.temp_path = File.join(fixture_path, file) + attachment.temp_paths.unshift File.join(FIXTURE_PATH, file) attachment.save new_filenames = [attachment.reload.full_filename] + attachment.thumbnails.collect { |t| t.reload.full_filename } new_filenames.each { |f| assert File.exists?(f), "#{f} does not exist" } @@ -224,7 +224,7 @@ class RmagickTest < Test::Unit::TestCase # #temp_path calls #full_filename, which is not getting mixed into the attachment. Maybe we don't need to # set temp_path at all? # - # attachment.temp_path = File.join(fixture_path, file) + # attachment.temp_paths.unshift File.join(FIXTURE_PATH, file) attachment.save! end end @@ -247,6 +247,23 @@ class RmagickTest < Test::Unit::TestCase end test_against_subclass :test_should_overwrite_old_thumbnail_records_when_renaming, ImageWithThumbsAttachment + + def test_should_handle_jpeg_quality + attachment_model ImageWithThumbsAttachment + attachment = upload_file :filename => '/files/rails.jpg', :content_type => 'image/jpeg' + full_size = attachment.size + attachment_model LowerQualityAttachment + attachment = upload_file :filename => '/files/rails.jpg', :content_type => 'image/jpeg' + lq_size = attachment.size + assert lq_size <= full_size * 0.9, 'Lower-quality JPEG filesize should be congruently smaller' + + attachment_model ImageWithPerThumbJpegAttachment + attachment = upload_file :filename => '/files/rails.jpg', :content_type => 'image/jpeg' + assert_file_jpeg_quality attachment, :thumb, 90 + assert_file_jpeg_quality attachment, :avatar, 85 + assert_file_jpeg_quality attachment, :large, 75 + assert_file_jpeg_quality attachment, nil, 75 + end else def test_flunk puts "RMagick not installed, no tests running" diff --git a/vendor/plugins/attachment_fu/test/schema.rb b/vendor/plugins/attachment_fu/test/schema.rb index e46ce24..12fff6c 100644 --- a/vendor/plugins/attachment_fu/test/schema.rb +++ b/vendor/plugins/attachment_fu/test/schema.rb @@ -2,6 +2,8 @@ ActiveRecord::Schema.define(:version => 0) do create_table :attachments, :force => true do |t| t.column :db_file_id, :integer t.column :parent_id, :integer + t.column :imageable_id, :integer + t.column :imageable_type, :string, :limit => 255 t.column :thumbnail, :string t.column :filename, :string, :limit => 255 t.column :content_type, :string, :limit => 255 @@ -22,6 +24,19 @@ ActiveRecord::Schema.define(:version => 0) do t.column :type, :string t.column :aspect_ratio, :float end + + create_table :file_attachments_with_string_id, :id => false, :force => true do |t| + t.column :id, :string + t.column :parent_id, :string + t.column :thumbnail, :string + t.column :filename, :string, :limit => 255 + t.column :content_type, :string, :limit => 255 + t.column :size, :integer + t.column :width, :integer + t.column :height, :integer + t.column :type, :string + t.column :aspect_ratio, :float + end create_table :gd2_attachments, :force => true do |t| t.column :parent_id, :integer @@ -105,4 +120,17 @@ ActiveRecord::Schema.define(:version => 0) do t.column :type, :string t.column :aspect_ratio, :float end -end \ No newline at end of file + + create_table :cloud_files_attachments, :force => true do |t| + t.column :parent_id, :integer + t.column :thumbnail, :string + t.column :filename, :string, :limit => 255 + t.column :content_type, :string, :limit => 255 + t.column :size, :integer + t.column :width, :integer + t.column :height, :integer + t.column :type, :string + t.column :aspect_ratio, :float + end + +end diff --git a/vendor/plugins/attachment_fu/test/test_helper.rb b/vendor/plugins/attachment_fu/test/test_helper.rb index c3bbab9..7747641 100644 --- a/vendor/plugins/attachment_fu/test/test_helper.rb +++ b/vendor/plugins/attachment_fu/test/test_helper.rb @@ -1,50 +1,37 @@ -$:.unshift(File.dirname(__FILE__) + '/../lib') +$LOAD_PATH.unshift(File.dirname(__FILE__)) +$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) ENV['RAILS_ENV'] = 'test' -ENV['Rails.root'] ||= File.dirname(__FILE__) + '/../../../..' +require 'rails/all' require 'test/unit' -require File.expand_path(File.join(ENV['Rails.root'], 'config/environment.rb')) -require 'active_record/fixtures' -require 'action_controller/test_process' - -config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml')) -ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log") - -db_adapter = ENV['DB'] - -# no db passed, try one of these fine config-free DBs before bombing. -db_adapter ||= - begin - require 'rubygems' - require 'sqlite' - 'sqlite' - rescue MissingSourceFile - begin - require 'sqlite3' - 'sqlite3' - rescue MissingSourceFile - end +require 'pothoven-attachment_fu' +include ActionDispatch::TestProcess + +# Define the application and configuration +module RbConfig + class Application < ::Rails::Application + # configuration here if needed + config.active_support.deprecation = :stderr end - -if db_adapter.nil? - raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3." end -ActiveRecord::Base.establish_connection(config[db_adapter]) +# Initialize the application +RbConfig::Application.initialize! +# Setup database load(File.dirname(__FILE__) + "/schema.rb") -Test::Unit::TestCase.fixture_path = File.dirname(__FILE__) + "/fixtures" -$LOAD_PATH.unshift(Test::Unit::TestCase.fixture_path) +FIXTURE_PATH = File.dirname(__FILE__) + "/fixtures" +$LOAD_PATH.unshift(FIXTURE_PATH) class Test::Unit::TestCase #:nodoc: - include ActionController::TestProcess + # include ActionDispatch::TestProcess def create_fixtures(*table_names) if block_given? - Fixtures.create_fixtures(Test::Unit::TestCase.fixture_path, table_names) { yield } + Fixtures.create_fixtures(FIXTURE_PATH, table_names) { yield } else - Fixtures.create_fixtures(Test::Unit::TestCase.fixture_path, table_names) + Fixtures.create_fixtures(FIXTURE_PATH, table_names) end end @@ -53,16 +40,18 @@ class Test::Unit::TestCase #:nodoc: DbFile.transaction { [Attachment, FileAttachment, OrphanAttachment, MinimalAttachment, DbFile].each { |klass| klass.delete_all } } attachment_model self.class.attachment_model end - + def teardown FileUtils.rm_rf File.join(File.dirname(__FILE__), 'files') + # Files generated by random_tempfile_filename + FileUtils.rm_rf Dir['[0-9]*.{png,jpg}'] end - self.use_transactional_fixtures = true - self.use_instantiated_fixtures = false + #self.use_transactional_fixtures = true + #self.use_instantiated_fixtures = false def self.attachment_model(klass = nil) - @attachment_model = klass if klass + @attachment_model = klass if klass @attachment_model end @@ -81,7 +70,18 @@ class Test::Unit::TestCase #:nodoc: protected def upload_file(options = {}) use_temp_file options[:filename] do |file| - att = attachment_model.create :uploaded_data => fixture_file_upload(file, options[:content_type] || 'image/png') +puts options + opts = { :uploaded_data => fixture_file_upload(file, options[:content_type] || 'image/png') } + opts.update(options.reject { |k, v| ![:imageable_type, :imageable_id].include?(k) }) + att = attachment_model.create opts + att.reload unless att.new_record? + return att + end + end + + def upload_merb_file(options = {}) + use_temp_file options[:filename] do |file| + att = attachment_model.create :uploaded_data => {"size" => file.size, "content_type" => options[:content_type] || 'image/png', "filename" => file, 'tempfile' => fixture_file_upload(file, options[:content_type] || 'image/png')} att.reload unless att.new_record? return att end @@ -89,11 +89,13 @@ class Test::Unit::TestCase #:nodoc: def use_temp_file(fixture_filename) temp_path = File.join('/tmp', File.basename(fixture_filename)) - FileUtils.mkdir_p File.join(fixture_path, 'tmp') - FileUtils.cp File.join(fixture_path, fixture_filename), File.join(fixture_path, temp_path) - yield temp_path + temp_dir = File.join(FIXTURE_PATH, 'tmp') + use_file = File.join(FIXTURE_PATH, temp_path) + FileUtils.mkdir_p temp_dir + FileUtils.cp File.join(FIXTURE_PATH, fixture_filename), use_file + yield use_file ensure - FileUtils.rm_rf File.join(fixture_path, 'tmp') + FileUtils.rm_rf temp_dir end def assert_created(num = 1) @@ -107,11 +109,36 @@ class Test::Unit::TestCase #:nodoc: end end end - + + def assert_valid(record) + assert record.valid?, record.errors.full_messages.join("\n") + end + + def assert_file_jpeg_quality(model, thumbnail, expected) + filename = if model.respond_to?(:full_filename) + model.full_filename(thumbnail) + else + thumb = thumbnail ? model.thumbnails.find(:first, :conditions => { :thumbnail => thumbnail.to_s }, :include => :db_file) : model + unless thumb && thumb.db_file && thumb.db_file.data && thumb.db_file.data.size > 0 + STDERR.puts "Cannot find DB file data for thumbnail #{thumbnail.inspect} -> Aborting JPEG quality check." + return + end + result = Tempfile.new('dbfile_dump').path + File.open(result, 'wb') { |f| f.write(thumb.db_file.data) } + result + end + quality = %x(identify -format '%Q' "#{filename}" 2> /dev/null) + if $?.success? + assert_equal expected, quality.to_i, "Produced JPEG quality (thumbnail: #{thumbnail.inspect}) is incorrect." + else + STDERR.puts "ImageMagick's identify not found / not in PATH: can't quickly check produced image quality." + end + end + def assert_not_created assert_created(0) { yield } end - + def should_reject_by_size_with(klass) attachment_model klass assert_not_created do @@ -121,22 +148,22 @@ class Test::Unit::TestCase #:nodoc: assert_nil attachment.db_file if attachment.respond_to?(:db_file) end end - + def assert_difference(object, method = nil, difference = 1) initial_value = object.send(method) yield assert_equal initial_value + difference, object.send(method) end - + def assert_no_difference(object, method, &block) assert_difference object, method, 0, &block end - + def attachment_model(klass = nil) - @attachment_model = klass if klass + @attachment_model = klass if klass @attachment_model end end require File.join(File.dirname(__FILE__), 'fixtures/attachment') -require File.join(File.dirname(__FILE__), 'base_attachment_tests') \ No newline at end of file +require File.join(File.dirname(__FILE__), 'base_attachment_tests') diff --git a/vendor/plugins/attachment_fu/test/validation_test.rb b/vendor/plugins/attachment_fu/test/validation_test.rb index a14cf99..cf56c1b 100644 --- a/vendor/plugins/attachment_fu/test/validation_test.rb +++ b/vendor/plugins/attachment_fu/test/validation_test.rb @@ -4,52 +4,52 @@ class ValidationTest < Test::Unit::TestCase def test_should_invalidate_big_files @attachment = SmallAttachment.new assert !@attachment.valid? - assert @attachment.errors.on(:size) + assert @attachment.errors[:size] @attachment.size = 2000 assert !@attachment.valid? - assert @attachment.errors.on(:size), @attachment.errors.full_messages.to_sentence + assert @attachment.errors[:size], @attachment.errors.full_messages.to_sentence @attachment.size = 1000 assert !@attachment.valid? - assert_nil @attachment.errors.on(:size) + assert @attachment.errors[:size].empty? end def test_should_invalidate_small_files @attachment = BigAttachment.new assert !@attachment.valid? - assert @attachment.errors.on(:size) + assert @attachment.errors[:size] @attachment.size = 2000 assert !@attachment.valid? - assert @attachment.errors.on(:size), @attachment.errors.full_messages.to_sentence + assert @attachment.errors[:size], @attachment.errors.full_messages.to_sentence @attachment.size = 1.megabyte assert !@attachment.valid? - assert_nil @attachment.errors.on(:size) + assert @attachment.errors[:size].empty? end def test_should_validate_content_type @attachment = PdfAttachment.new assert !@attachment.valid? - assert @attachment.errors.on(:content_type) + assert @attachment.errors[:content_type] @attachment.content_type = 'foo' assert !@attachment.valid? - assert @attachment.errors.on(:content_type) + assert @attachment.errors[:content_type] @attachment.content_type = 'pdf' assert !@attachment.valid? - assert_nil @attachment.errors.on(:content_type) + assert @attachment.errors[:content_type].empty? end def test_should_require_filename @attachment = Attachment.new assert !@attachment.valid? - assert @attachment.errors.on(:filename) + assert @attachment.errors[:filename] @attachment.filename = 'foo' assert !@attachment.valid? - assert_nil @attachment.errors.on(:filename) + assert @attachment.errors[:filename].empty? end end \ No newline at end of file -- libgit2 0.21.2