Skip to content
This repository
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 454 lines (403 sloc) 11.715 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
# -- encoding: utf-8 --
#
# MiniExiftool
#
# This library is wrapper for the Exiftool command-line
# application (http://www.sno.phy.queensu.ca/~phil/exiftool/)
# written by Phil Harvey.
# Read and write access is done in a clean OO manner.
#
# Author: Jan Friedrich
# Copyright (c) 2007-2011 by Jan Friedrich
# Licensed under the GNU LESSER GENERAL PUBLIC LICENSE,
# Version 2.1, February 1999
#

require 'fileutils'
require 'tempfile'
require 'pstore'
require 'set'
require 'shellwords'
require 'time'

# Simple OO access to the Exiftool command-line application.
class MiniExiftool

  # Name of the Exiftool command-line application
  @@cmd = 'exiftool'

  # Hash of the standard options used when call MiniExiftool.new
  @@opts = { :numerical => false, :composite => true, :convert_encoding => false, :timestamps => Time }

  attr_reader :filename
  attr_accessor :numerical, :composite, :convert_encoding, :errors, :timestamps

  VERSION = '1.3.1'

  # +opts+ support at the moment
  # * <code>:numerical</code> for numerical values, default is +false+
  # * <code>:composite</code> for including composite tags while loading,
  # default is +true+
  # * <code>:convert_encoding</code> convert encoding (See -L-option of
  # the exiftool command-line application, default is +false+
  # * <code>:timestamps</code> generating DateTime objects instead of
  # Time objects if set to <code>DateTime</code>, default is +Time+
  #
  # <b>ATTENTION:</b> Time objects are created using <code>Time.local</code>
  # therefore they use <em>your local timezone</em>, DateTime objects instead
  # are created <em>without timezone</em>!
  def initialize filename=nil, opts={}
    opts = @@opts.merge opts
    @numerical = opts[:numerical]
    @composite = opts[:composite]
    @convert_encoding = opts[:convert_encoding]
    @timestamps = opts[:timestamps]
    @values = TagHash.new
    @tag_names = TagHash.new
    @changed_values = TagHash.new
    @errors = TagHash.new
    load filename unless filename.nil?
  end

  def initialize_from_hash hash # :nodoc:
    hash.each_pair do |tag,value|
      set_value tag, value
    end
    set_attributes_by_heuristic
    self
  end

  # Load the tags of filename.
  def load filename
    unless filename && File.exist?(filename)
      raise MiniExiftool::Error.new("File '#{filename}' does not exist.")
    end
    if File.directory?(filename)
      raise MiniExiftool::Error.new("'#{filename}' is a directory.")
    end
    @filename = filename
    @values.clear
    @tag_names.clear
    @changed_values.clear
    opt_params = ''
    opt_params << (@numerical ? '-n ' : '')
    opt_params << (@composite ? '' : '-e ')
    opt_params << (@convert_encoding ? '-L ' : '')
    cmd = %Q(#@@cmd -q -q -s -t #{opt_params} #{@@sep_op} #{Shellwords.escape(filename)})
    if run(cmd)
      parse_output
    else
      raise MiniExiftool::Error.new(@error_text)
    end
    self
  end

  # Reload the tags of an already read file.
  def reload
    load @filename
  end

  # Returns the value of a tag.
  def [] tag
    @changed_values[tag] || @values[tag]
  end

  # Set the value of a tag.
  def []=(tag, val)
    @changed_values[tag] = val
  end

  # Returns true if any tag value is changed or if the value of a
  # given tag is changed.
  def changed? tag=false
    if tag
      @changed_values.include? tag
    else
      !@changed_values.empty?
    end
  end

  # Revert all changes or the change of a given tag.
  def revert tag=nil
    if tag
      val = @changed_values.delete(tag)
      res = val != nil
    else
      res = @changed_values.size > 0
      @changed_values.clear
    end
    res
  end

  # Returns an array of the tags (original tag names) of the read file.
  def tags
    @values.keys.map { |key| @tag_names[key] }
  end

  # Returns an array of all changed tags.
  def changed_tags
    @changed_values.keys.map { |key| MiniExiftool.original_tag(key) }
  end

  # Save the changes to the file.
  def save
    return false if @changed_values.empty?
    @errors.clear
    temp_file = Tempfile.new('mini_exiftool')
    temp_file.close
    temp_filename = temp_file.path
    FileUtils.cp filename, temp_filename
    all_ok = true
    @changed_values.each do |tag, val|
      original_tag = MiniExiftool.original_tag(tag)
      arr_val = val.kind_of?(Array) ? val : [val]
      arr_val.map! {|e| convert e}
      tag_params = ''
      arr_val.each do |v|
        tag_params << %Q(-#{original_tag}="#{v}" )
      end
      opt_params = ''
      opt_params << (arr_val.detect {|x| x.kind_of?(Numeric)} ? '-n ' : '')
      opt_params << (@convert_encoding ? '-L ' : '')
      cmd = %Q(#@@cmd -q -P -overwrite_original #{opt_params} #{tag_params} #{temp_filename})
      if convert_encoding && cmd.respond_to?(:encode)
        cmd.encode('ISO-8859-1')
      end
      result = run(cmd)
      unless result
        all_ok = false
        @errors[tag] = @error_text.gsub(/Nothing to do.\n\z/, '').chomp
      end
    end
    if all_ok
      FileUtils.cp temp_filename, filename
      reload
    end
    temp_file.delete
    all_ok
  end

  # Returns a hash of the original loaded values of the MiniExiftool
  # instance.
  def to_hash
    result = {}
    @values.each do |k,v|
      result[@tag_names[k]] = v
    end
    result
  end

  # Returns a YAML representation of the original loaded values of the
  # MiniExiftool instance.
  def to_yaml
    to_hash.to_yaml
  end

  # Create a MiniExiftool instance from a hash
  def self.from_hash hash
    instance = MiniExiftool.new
    instance.initialize_from_hash hash
    instance
  end

  # Create a MiniExiftool instance from YAML data created with
  # MiniExiftool#to_yaml
  def self.from_yaml yaml
    MiniExiftool.from_hash YAML.load(yaml)
  end

  # Returns the command name of the called Exiftool application.
  def self.command
    @@cmd
  end

  # Setting the command name of the called Exiftool application.
  def self.command= cmd
    @@cmd = cmd
  end

  # Returns the options hash.
  def self.opts
    @@opts
  end

  # Returns a set of all known tags of Exiftool.
  def self.all_tags
    unless defined? @@all_tags
      @@all_tags = pstore_get :all_tags
    end
    @@all_tags
  end

  # Returns a set of all possible writable tags of Exiftool.
  def self.writable_tags
    unless defined? @@writable_tags
      @@writable_tags = pstore_get :writable_tags
    end
    @@writable_tags
  end

  # Returns the original Exiftool name of the given tag
  def self.original_tag tag
    unless defined? @@all_tags_map
      @@all_tags_map = pstore_get :all_tags_map
    end
    @@all_tags_map[tag]
  end

  # Returns the version of the Exiftool command-line application.
  def self.exiftool_version
    output = `#{MiniExiftool.command} -ver 2>&1`
    unless $?.exitstatus == 0
      raise MiniExiftool::Error.new("Command '#{MiniExiftool.command}' not found")
    end
    output.chomp!
  end

  def self.unify tag
    tag.to_s.gsub(/[-_]/,'').downcase
  end

  # Exception class
  class MiniExiftool::Error < StandardError; end

  ############################################################################
  private
  ############################################################################

  @@error_file = Tempfile.new 'errors'
  @@error_file.close

  if Float(exiftool_version) < 7.41
    @@separator = ', '
    @@sep_op = ''
  else
    @@separator = '@@'
    @@sep_op = '-sep @@'
  end

  def run cmd
    if $DEBUG
      $stderr.puts cmd
    end
    @output = `#{cmd} 2>#{@@error_file.path}`
    if convert_encoding && @output.respond_to?(:force_encoding)
      @output.force_encoding('ISO-8859-1')
    end
    @status = $?
    unless @status.exitstatus == 0
      @error_text = File.readlines(@@error_file.path).join
      return false
    else
      @error_text = ''
      return true
    end
  end

  def convert val
    case val
    when Time
      val = val.strftime('%Y:%m:%d %H:%M:%S')
    end
    val
  end

  def method_missing symbol, *args
    tag_name = symbol.id2name
    if tag_name.sub!(/=$/, '')
      self[tag_name] = args.first
    else
      self[tag_name]
    end
  end

  def parse_output
    @output.each_line do |line|
      tag, value = parse_line line
      set_value tag, value
    end
  end

  def parse_line line
    if line =~ /^([^\t]+)\t(.*)$/
      tag, value = $1, $2
      case value
      when /^\d{4}:\d\d:\d\d \d\d:\d\d:\d\d/
        s = value.sub(/^(\d+):(\d+):/, '\1-\2-')
        begin
          if @timestamps == Time
            value = Time.parse(s)
            elsif @timestamps == DateTime
            value = DateTime.parse(s)
          else
            raise MiniExiftool::Error.new("Value #@timestamps not allowed for option timestamps.")
          end
        rescue ArgumentError
          value = false
        end
      when /^\d+\.\d+$/
        value = value.to_f
      when /^0+[1-9]+$/
        # nothing => String
      when /^-?\d+$/
        value = value.to_i
      when /^[\d ]+$/
        # nothing => String
      when /#{@@separator}/
        value = value.split @@separator
      end
    else
      raise MiniExiftool::Error.new("Malformed line #{line.inspect} of exiftool output.")
    end
    unless value.respond_to?('to_a')
      class << value
        def to_a
          [self]
        end
      end
    end
    return [tag, value]
  end

  def set_value tag, value
    @tag_names[tag] = tag
    @values[tag] = value
  end

  def set_attributes_by_heuristic
    self.composite = tags.include?('ImageSize') ? true : false
    self.numerical = self.file_size.kind_of?(Integer) ? true : false
    # TODO: Is there a heuristic to determine @convert_encoding?
    self.timestamps = self.FileModifyDate.kind_of?(DateTime) ? DateTime : Time
  end

  def temp_filename
    unless @temp_filename
      temp_file = Tempfile.new('mini-exiftool')
      temp_file.close
      FileUtils.cp(@filename, temp_file.path)
      @temp_filename = temp_file.path
    end
    @temp_filename
  end

  def self.pstore_get attribute
    load_or_create_pstore unless defined? @@pstore
    result = nil
    @@pstore.transaction(true) do |ps|
      result = ps[attribute]
    end
    result
  end

  def self.load_or_create_pstore
    # This will hopefully work on *NIX and Windows systems
    home = ENV['HOME'] || ENV['HOMEDRIVE'] + ENV['HOMEPATH'] || ENV['USERPROFILE']
    subdir = RUBY_PLATFORM =~ /\bmswin/i ? '_mini_exiftool' : '.mini_exiftool'
    FileUtils.mkdir_p(File.join(home, subdir))
    filename = File.join(home, subdir, 'exiftool_tags_' << exiftool_version.gsub('.', '_') << '.pstore')
    @@pstore = PStore.new filename
    if !File.exist?(filename) || File.size(filename) == 0
      @@pstore.transaction do |ps|
        ps[:all_tags] = all_tags = determine_tags('list')
        ps[:writable_tags] = determine_tags('listw')
        map = {}
        all_tags.each { |k| map[unify(k)] = k }
        ps[:all_tags_map] = map
      end
    end
  end

  def self.determine_tags arg
    output = `#{@@cmd} -#{arg}`
    lines = output.split(/\n/)
    tags = Set.new
    lines.each do |line|
      next unless line =~ /^\s/
      tags |= line.chomp.split
    end
    tags
  end


  # Hash with indifferent access:
  # DateTimeOriginal == datetimeoriginal == date_time_original
  class TagHash < Hash # :nodoc:
    def[] k
      super(unify(k))
    end
    def []= k, v
      super(unify(k), v)
    end
    def delete k
      super(unify(k))
    end

    def unify tag
      MiniExiftool.unify tag
    end
  end

end

# Add to_a to Numerical if it's not yet defined
unless Numeric.instance_methods.include? 'to_a'
  class Numeric
    def to_a
      [self]
    end
  end
end

# Test if we can run the Exiftool command
MiniExiftool.exiftool_version
Something went wrong with that request. Please try again.