# -*- encoding : utf-8 -*- # Created by Thomas Boerger on 2012-03-16. # Copyright (c) 2012. All rights reserved. require 'exifr' require 'digest/md5' module Archiver class Record attr_accessor :path def initialize(path) @path = path end def filename(counter = 0) append = if counter > 0 sprintf('-%03d', counter) else nil end [ created.strftime('%Y%m%d-%H%M%S'), append, extension ].compact.join end def extension if mime_type.match /^image\/jpeg$/i return '.jpg' end if mime_type.match /^image\/gif$/i return '.gif' end if mime_type.match /^image\/png$/i return '.png' end if mime_type.match /^video\/3gpp$/i return '.mp4' end if mime_type.match /^video\/quicktime$/i return '.mov' end File.extname(path).downcase end def created if exif_data and exif_data.date_time_original exif_data.date_time_original else File.mtime(path) end end def checksum @checksum ||= Digest::MD5.hexdigest(File.read(path)) end def mime_type @mime_type ||= mime_detect .split(';') .first .strip end def exif_data @exif_data ||= exif_detect end def process? image? or video? end def image? if mime_type.match /^image\/.*/i true else false end end def video? if mime_type.match /^video\/.*/i true else false end end def same?(other) if other.is_a? Record checksum == other.checksum else checksum == Digest::MD5.hexdigest(File.read(other)) end end def move(directory, counter = 0) destination = File.join(directory, segment, filename(counter)) unless File.directory? File.dirname(destination) FileUtils.mkdir_p File.dirname(destination) end if File.exists? destination if same? destination FileUtils.rm_rf path else move(directory, counter + 1) end else FileUtils.cp path, destination FileUtils.rm_rf path end end def segment created.strftime('%Y') end protected def mime_detect `/usr/bin/env file --brief --mime "#{path}"` end def exif_detect if mime_type.match(/^image\/jpeg/i) return EXIFR::JPEG.new(path) end if mime_type.match(/^image\/tiff/i) return EXIFR::TIFF.new(path) end nil end end end