root/vendor/file-column-0.3.1/lib/file_column.rb @ 11

Revision 2, 20.1 kB (checked in by falcon, 17 years ago)

added plugins

  • Property svn:executable set to *
Line 
1require 'fileutils'
2require 'tempfile'
3require 'magick_file_column'
4
5module FileColumn # :nodoc:
6  def self.append_features(base)
7    super
8    base.extend(ClassMethods)
9  end
10
11  def self.create_state(options,instance,attr)
12    filename = instance[attr]
13    if filename.nil? or filename.empty?
14      NoUploadedFile.new(options,instance,attr)
15    else
16      PermanentUploadedFile.new(options,instance,attr)
17    end
18  end
19
20  def self.init_options(defaults, model, attr)
21    options = defaults.dup
22    options[:store_dir] ||= File.join(options[:root_path], model, attr)
23    options[:tmp_base_dir] ||= File.join(options[:store_dir], "tmp")
24    options[:base_url] ||= options[:web_root] + File.join(model, attr)
25    FileUtils.mkpath([ options[:store_dir], options[:tmp_base_dir] ])
26
27    options
28  end
29
30  class BaseUploadedFile # :nodoc:
31
32    def initialize(options,instance,attr)
33      @options, @instance, @attr = options, instance, attr
34    end
35
36
37    def assign(file)
38      if file.nil?
39        delete
40      else
41        if file.size == 0
42          # user did not submit a file, so we
43          # can simply ignore this
44          self
45        else
46          if file.is_a?(String)
47            # if file is a non-empty string it is most probably
48            # the filename and the user forgot to set the encoding
49            # to multipart/form-data. Since we would raise an exception
50            # because of the missing "original_filename" method anyways,
51            # we raise a more meaningful exception rightaway.
52            raise TypeError.new("Do not know how to handle a string with value '#{file}' that was passed to a file_column. Check if the form's encoding has been set to 'multipart/form-data'.")
53          end
54          upload(file)
55        end
56      end
57    end
58
59    def just_uploaded?
60      @just_uploaded
61    end
62
63    def on_save(&blk)
64      @on_save ||= []
65      @on_save << Proc.new
66    end
67   
68    # the following methods are overriden by sub-classes if needed
69
70    def temp_path
71      nil
72    end
73
74    def absolute_dir
75      if absolute_path then File.dirname(absolute_path) else nil end
76    end
77
78    def relative_dir
79      if relative_path then File.dirname(relative_path) else nil end
80    end
81
82    def after_save
83      @on_save.each { |blk| blk.call } if @on_save
84      self
85    end
86
87    def after_destroy
88    end
89
90    attr_accessor :options
91
92    private
93   
94    def store_dir
95      @options[:store_dir]
96    end
97
98    def tmp_base_dir
99      @options[:tmp_base_dir]
100    end
101
102    def clone_as(klass)
103      klass.new(@options, @instance, @attr)
104    end
105
106  end
107   
108
109  class NoUploadedFile < BaseUploadedFile # :nodoc:
110    def delete
111      # we do not have a file so deleting is easy
112      self
113    end
114
115    def upload(file)
116      # replace ourselves with a TempUploadedFile
117      temp = clone_as TempUploadedFile
118      temp.store_upload(file)
119      temp
120    end
121
122    def absolute_path(suffix=nil)
123      nil
124    end
125
126
127    def relative_path(suffix=nil)
128      nil
129    end
130
131    def assign_temp(temp_path)
132      return self if temp_path.nil? or temp_path.empty?
133      temp = clone_as TempUploadedFile
134      temp.parse_temp_path temp_path
135      temp
136    end
137  end
138
139  class RealUploadedFile < BaseUploadedFile # :nodoc:
140    def absolute_path(suffix=nil)
141      File.expand_path(File.join(@dir, filename_with_suffix(suffix)))
142    end
143
144    def relative_path(suffix=nil)
145      File.join(relative_path_prefix, filename_with_suffix(suffix))
146    end
147
148    private
149
150    def filename_with_suffix(suffix)
151      if suffix.nil?
152        @filename
153      else
154        base, ext = split_extension(@filename, :fallback_to_simple)
155        "#{base}-#{suffix}.#{ext}"
156      end
157    end
158
159    # regular expressions to try for identifying extensions
160    EXT_REGEXPS = [ 
161      /^(.+)\.([^.]+\.[^.]+)$/, # matches "something.tar.gz"
162      /^(.+)\.([^.]+)$/ # matches "something.jpg"
163    ]
164
165    def split_extension(filename,fallback=nil)
166      EXT_REGEXPS.each do |regexp|
167        if filename =~ regexp
168          base,ext = $1, $2
169          return [base, ext] if @options[:extensions].include?(ext.downcase)
170        end
171      end
172      if fallback and filename =~ EXT_REGEXPS.last
173        return [$1, $2]
174      end
175      [filename, ""]
176    end
177   
178  end
179
180  class TempUploadedFile < RealUploadedFile # :nodoc:
181
182    def store_upload(file)
183      @tmp_dir = FileColumn.generate_temp_name
184      @dir = File.join(tmp_base_dir, @tmp_dir)     
185      FileUtils.mkdir(@dir)
186     
187      @filename = FileColumn::sanitize_filename(file.original_filename)
188      local_file_path = File.join(tmp_base_dir,@tmp_dir,@filename)
189     
190      # stored uploaded file into local_file_path
191      # If it was a Tempfile object, the temporary file will be
192      # cleaned up automatically, so we do not have to care for this
193      if file.respond_to?(:local_path) and file.local_path and File.exists?(file.local_path)
194        FileUtils.copy_file(file.local_path, local_file_path)
195      elsif file.respond_to?(:read)
196        File.open(local_file_path, "wb") { |f| f.write(file.read) }
197      else
198        raise ArgumentError.new("Do not know how to handle #{file.inspect}")
199      end
200
201      if @options[:fix_file_extensions]
202        # try to determine correct file extension and fix
203        # if necessary
204        content_type = get_content_type((file.content_type.chomp if file.content_type))
205        if content_type and @options[:mime_extensions][content_type]
206          @filename = correct_extension(@filename,@options[:mime_extensions][content_type])
207        end
208
209        new_local_file_path = File.join(tmp_base_dir,@tmp_dir,@filename)
210        FileUtils.mv(local_file_path, new_local_file_path) unless new_local_file_path == local_file_path
211        local_file_path = new_local_file_path
212      end
213     
214      @instance[@attr] = @filename
215      @just_uploaded = true
216    end
217
218
219    # tries to identify and strip the extension of filename
220    # if an regular expresion from EXT_REGEXPS matches and the
221    # downcased extension is a known extension (in @options[:extensions])
222    # we'll strip this extension
223    def strip_extension(filename)
224      split_extension(filename).first
225    end
226
227    def correct_extension(filename, ext)
228      strip_extension(filename) << ".#{ext}"
229    end
230   
231    def parse_temp_path(temp_path, instance_options=nil)
232      raise ArgumentError.new("invalid format of '#{temp_path}'") unless temp_path =~ %r{^((\d+\.)+\d+)/([^/].+)$}
233      @tmp_dir, @filename = $1, FileColumn.sanitize_filename($3)
234      @dir = File.join(tmp_base_dir, @tmp_dir)
235
236      @instance[@attr] = @filename unless instance_options == :ignore_instance
237    end
238   
239    def upload(file)
240      # store new file
241      temp = clone_as TempUploadedFile
242      temp.store_upload(file)
243     
244      # delete old copy
245      delete_files
246
247      # and return new TempUploadedFile object
248      temp
249    end
250
251    def delete
252      delete_files
253      clone_as NoUploadedFile
254    end
255
256    def assign_temp(temp_path)
257      return self if temp_path.nil? or temp_path.empty?
258      # we can ignore this since we've already received a newly uploaded file
259
260      # however, we delete the old temporary files
261      temp = clone_as TempUploadedFile
262      temp.parse_temp_path(temp_path, :ignore_instance)
263      temp.delete_files
264
265      self
266    end
267
268    def temp_path
269      File.join(@tmp_dir, @filename)
270    end
271
272    def after_save
273      super
274
275      # we have a newly uploaded image, move it to the correct location
276      file = clone_as PermanentUploadedFile
277      file.move_from(File.join(tmp_base_dir, @tmp_dir), @just_uploaded)
278
279      # delete temporary files
280      delete_files
281
282      # replace with the new PermanentUploadedFile object
283      file
284    end
285
286    def delete_files
287      FileUtils.rm_rf(File.join(tmp_base_dir, @tmp_dir))
288    end
289
290    def get_content_type(fallback=nil)
291      if @options[:file_exec]
292        begin
293          content_type = `#{@options[:file_exec]} -bi "#{@local_file_path}"`.chomp
294          content_type = fallback unless $?.success?
295          content_type.gsub!(/;.+$/,"") if content_type
296          content_type
297        rescue
298          fallback
299        end
300      else
301        fallback
302      end
303    end
304
305    private
306
307    def relative_path_prefix
308      File.join("tmp", @tmp_dir)
309    end
310  end
311
312 
313  class PermanentUploadedFile < RealUploadedFile # :nodoc:
314    def initialize(*args)
315      super *args
316      @dir = File.join(store_dir,@instance.id.to_s)
317      @filename = @instance[@attr]
318      @filename = nil if @filename.empty?
319    end
320
321    def move_from(local_dir, just_uploaded)
322      # create a directory named after the primary key, first
323      FileUtils.mkdir(@dir) unless File.exists?(@dir)
324
325      # move the temporary files over
326      FileUtils.cp Dir.glob(File.join(local_dir, "*")), @dir
327     
328      @just_uploaded = just_uploaded
329
330      # remove all old files in the directory
331      FileUtils.rm(Dir.glob(File.join(@dir, "*")).reject! {
332                     |e| File.exists?(File.join(local_dir, File.basename(e)))
333                   })
334     
335    end
336
337    def upload(file)
338      temp = clone_as TempUploadedFile
339      temp.store_upload(file)
340      temp
341    end
342
343    def delete
344      file = clone_as NoUploadedFile
345      @instance[@attr] = nil
346      file.on_save { delete_files }
347      file
348    end
349
350    def assign_temp(temp_path)
351      return nil if temp_path.nil? or temp_path.empty?
352
353      temp = clone_as TempUploadedFile
354      temp.parse_temp_path(temp_path)
355      temp
356    end
357
358    def after_destroy
359      delete_files
360    end
361
362    def delete_files
363      FileUtils.rm_rf @dir
364    end
365
366    private
367   
368    def relative_path_prefix
369      @instance.id.to_s
370    end
371  end
372   
373  # The FileColumn module allows you to easily handle file uploads. You can designate
374  # one or more columns of your model's table as "file columns" like this:
375  #
376  #   class Entry < ActiveRecord::Base
377  #
378  #     file_column :image
379  #   end
380  #
381  # Now, by default, an uploaded file "test.png" for an entry object with primary key 42 will
382  # be stored in in "public/entry/image/42/test.png". The filename "test.png" will be stored
383  # in the record's +image+ column.
384  #
385  # The methods of this module are automatically included into ActiveRecord::Base as class
386  # methods, so that you can use them in your models.
387  #
388  # == Generated Methods
389  #
390  # After calling "<tt>file_column :image</tt>" as in the example above, a number of instance methods
391  # will automatically be generated, all prefixed by "image":
392  #
393  # * <tt>Entry#image=(uploaded_file)</tt>: this will handle a newly uploaded file
394  #   (see below). Note that
395  #   you can simply call your upload field "entry[image]" in your view (or use the
396  #   helper).
397  # * <tt>Entry#image(suffix=nil)</tt>: This will return an absolute path (as a
398  #   string) to the currently uploaded file
399  #   or nil if no file has been uploaded
400  # * <tt>Entry#image_relative_path(suffix)</tt>: This will return a path relative to
401  #   this file column's base directory
402  #   as a string or nil if no file has been uploaded. This would be "42/test.png" in the example.
403  # * <tt>Entry#image_just_uploaded?</tt>: Returns true if a new file has been uploaded to this instance.
404  #   You can use this in <tt>before_validation</tt> to resize images on newly uploaded files, for example.
405  #
406  # You can access the raw value of the "image" column (which will contain the filename) via the
407  # <tt>ActiveRecord::Base#attributes</tt> or <tt>ActiveRecord::Base#[]</tt> methods like this:
408  #
409  #   entry['image']    # e.g."test.png"
410  #
411  # == Storage of uploaded file
412  #
413  # For a model class +Entry+ and a column +image+, all files will be stored under
414  # "public/entry/image". A sub-directory named after the primary key of the object will
415  # be created, so that files can be stored using their real filename. For example, a file
416  # "test.png" stored in an Entry object with id 42 will be stored in
417  #
418  #   public/entry/image/42/test.png
419  #
420  # Files will be moved to this location in an +after_save+ callback. They will be stored in
421  # a temporary location previously as explained in the next section.
422  #
423  # == Handling of form redisplay
424  #
425  # Suppose you have a form for creating a new object where the user can upload an image. The form may
426  # have to be re-displayed because of validation errors. The uploaded file has to be stored somewhere so
427  # that the user does not have to upload it again. FileColumn will store these in a temporary directory
428  # (called "tmp" and located under the column's base directory by default) so that it can be moved to
429  # the final location if the object is successfully created. If the form is never completed, though, you
430  # can easily remove all the images in this "tmp" directory once per day or so.
431  #
432  # So in the example above, the image "test.png" would first be stored in
433  # "public/entry/image/tmp/<some_random_key>/test.png" and be moved to
434  # "public/entry/image/<primary_key>/test.png".
435  #
436  # This temporary location of newly uploaded files has another advantage when updating objects. If the
437  # update fails for some reasons (e.g. due to validations), the existing image will not be overwritten, so
438  # it has a kind of "transactional behaviour".
439  #
440  # == Suffixes
441  #
442  # FileColumn allows you to keep more than one file in a directory and will move/delete
443  # all the files it finds in a model object's directory when necessary. You can access
444  # these files via the optional suffix parameter that some of the generated methods
445  # accept (see above). This suffix is inserted into the filename before the extension,
446  # separated by a dash.
447  #
448  # Suppose your uploaded file is named "vancouver.jpg" and you want to create a
449  # thumb-nail and store it in the same directory. If you cal
450  # <tt>image("thumb")</tt>, you
451  # will receive an absolute path for the file "vancouver-thumb.jpg" in the same
452  # directory "vancouver.jpg" is stored. Look at the documentation of FileColumn::Magick
453  # for more examples.
454  #
455  # == File Extensions
456  #
457  # FileColumn will try to fix the file extension of uploaded files, so that
458  # the files are served with the correct mime-type by your web-server. Most
459  # web-servers are setting the mime-type based on the file's extension. You
460  # can disable this behaviour by passing the <tt>:fix_file_extensions</tt> option
461  # with a value of +nil+ to +file_column+.
462  #
463  # In order to set the correct extension, FileColumn tries to determine
464  # the files mime-type first. It then uses the +MIME_EXTENSIONS+ hash to
465  # choose the corresponding file extension. You can override this hash
466  # by passing in a <tt>:mime_extensions</tt> option to +file_column+.
467  #
468  # The mime-type of the uploaded file is determined with the following steps:
469  #
470  # 1. Run the external "file" utility. You can specify the full path to
471  #    the executable in the <tt>:file_exec</tt> option or set this option
472  #    to +nil+ to disable this step
473  #
474  # 2. If the file utility couldn't determine the mime-type or the utility was not
475  #    present, the content-type provided by the user's browser is used
476  #    as a fallback.
477  module ClassMethods
478
479
480    # default mapping of mime-types to file extensions. FileColumn will try to
481    # rename a file to the correct extension if it detects a known mime-type
482    MIME_EXTENSIONS = {
483      "image/gif" => "gif",
484      "image/jpeg" => "jpg",
485      "image/pjpeg" => "jpg",
486      "image/x-png" => "png",
487      "image/jpg" => "jpg",
488      "image/png" => "png",
489      "application/x-shockwave-flash" => "swf",
490      "application/pdf" => "pdf",
491      "application/pgp-signature" => "sig",
492      "application/futuresplash" => "spl",
493      "application/msword" => "doc",
494      "application/postscript" => "ps",
495      "application/x-bittorrent" => "torrent",
496      "application/x-dvi" => "dvi",
497      "application/x-gzip" => "gz",
498      "application/x-ns-proxy-autoconfig" => "pac",
499      "application/x-shockwave-flash" => "swf",
500      "application/x-tgz" => "tar.gz",
501      "application/x-tar" => "tar",
502      "application/zip" => "zip",
503      "audio/mpeg" => "mp3",
504      "audio/x-mpegurl" => "m3u",
505      "audio/x-ms-wma" => "wma",
506      "audio/x-ms-wax" => "wax",
507      "audio/x-wav" => "wav",
508      "image/x-xbitmap" => "xbm",             
509      "image/x-xpixmap" => "xpm",             
510      "image/x-xwindowdump" => "xwd",             
511      "text/css" => "css",             
512      "text/html" => "html",                         
513      "text/javascript" => "js",
514      "text/plain" => "txt",
515      "text/xml" => "xml",
516      "video/mpeg" => "mpeg",
517      "video/quicktime" => "mov",
518      "video/x-msvideo" => "avi",
519      "video/x-ms-asf" => "asf",
520      "video/x-ms-wmv" => "wmv"
521    }
522
523    EXTENSIONS = Set.new MIME_EXTENSIONS.values
524    EXTENSIONS.merge %w(jpeg)
525
526    # default options. You can override these with +file_column+'s +options+ parameter
527    DEFAULT_OPTIONS = {
528      :root_path => File.join(RAILS_ROOT, "public"),
529      :web_root => "",
530      :mime_extensions => MIME_EXTENSIONS,
531      :extensions => EXTENSIONS,
532      :fix_file_extensions => true,
533
534      # path to the unix "file" executbale for
535      # guessing the content-type of files
536      :file_exec => "file" 
537    }.freeze
538   
539    # handle the +attr+ attribute as a "file-upload" column, generating additional methods as explained
540    # above. You should pass the attribute's name as a symbol, like this:
541    #
542    #   file_column :image
543    #
544    # You can pass in an options hash that overrides the options
545    # in +DEFAULT_OPTIONS+.
546    def file_column(attr, options={})
547      options = DEFAULT_OPTIONS.merge(options) if options
548     
549      my_options = FileColumn::init_options(options, 
550                                            Inflector.underscore(self.name).to_s,
551                                            attr.to_s)
552     
553      state_attr = "@#{attr}_state".to_sym
554      state_method = "#{attr}_state".to_sym
555     
556      define_method state_method do
557        result = instance_variable_get state_attr
558        if result.nil?
559          result = FileColumn::create_state(my_options, self, attr.to_s)
560          instance_variable_set state_attr, result
561        end
562        result
563      end
564     
565      private state_method
566     
567      define_method attr do |*args|
568        send(state_method).absolute_path *args
569      end
570     
571      define_method "#{attr}_relative_path" do |*args|
572        send(state_method).relative_path *args
573      end
574
575      define_method "#{attr}_dir" do
576        send(state_method).absolute_dir
577      end
578
579      define_method "#{attr}_relative_dir" do
580        send(state_method).relative_dir
581      end
582
583      define_method "#{attr}=" do |file|
584        instance_variable_set state_attr, send(state_method).assign(file)
585        if my_options[:after_assign]
586          my_options[:after_assign].each do |sym|
587            self.send sym
588          end
589        end
590      end
591     
592      define_method "#{attr}_temp" do
593        send(state_method).temp_path
594      end
595     
596      define_method "#{attr}_temp=" do |temp_path|
597        instance_variable_set state_attr, send(state_method).assign_temp(temp_path)
598      end
599     
600      after_save_method = "#{attr}_after_save".to_sym
601     
602      define_method after_save_method do
603        instance_variable_set state_attr, send(state_method).after_save
604      end
605     
606      after_save after_save_method
607     
608      after_destroy_method = "#{attr}_after_destroy".to_sym
609     
610      define_method after_destroy_method do
611        send(state_method).after_destroy
612      end
613      after_destroy after_destroy_method
614     
615      define_method "#{attr}_just_uploaded?" do
616        send(state_method).just_uploaded?
617      end
618     
619      define_method "#{attr}_options" do
620        send(state_method).options
621      end
622     
623      private after_save_method, after_destroy_method
624
625      FileColumn::Magick::file_column(self, attr, my_options) if options[:magick]
626    end
627   
628  end
629 
630  private
631 
632  def self.generate_temp_name
633    now = Time.now
634    "#{now.to_i}.#{now.usec}.#{Process.pid}"
635  end
636 
637  def self.sanitize_filename(filename)
638    filename = File.basename(filename.gsub("\\", "/")) # work-around for IE
639    filename.gsub!(/[^a-zA-Z0-9\.\-\+_]/,"_")
640    filename = "_#{filename}" if filename =~ /^\.+$/
641    filename = "unnamed" if filename.size == 0
642    filename
643  end
644 
645  def self.remove_file_with_dir(path)
646    return unless File.file?(path)
647    FileUtils.rm_f path
648    dir = File.dirname(path)
649    Dir.rmdir(dir) if File.exists?(dir)
650  end
651
652end
653
654
Note: See TracBrowser for help on using the browser.