zip_extractor.rb 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. require 'zip'
  2. require 'exifr/jpeg'
  3. require 'fileutils'
  4. module Fotos
  5. class ZipExtractor
  6. def initialize(options)
  7. @zip_file_path = options[:zip]
  8. @destination_path = options[:dest]
  9. @tmp_dir_path = File.join(Pathname.pwd, 'tmp')
  10. @extracted_paths = []
  11. @copied_paths = []
  12. end
  13. attr_reader :zip_file_path, :destination_path
  14. def call
  15. Dir.mkdir(@tmp_dir_path) unless Dir.exist?(@tmp_dir_path)
  16. extract
  17. copy
  18. ensure
  19. FileUtils.rm_r(@tmp_dir_path)
  20. end
  21. private
  22. def extract
  23. Zip::File.open(zip_file_path) do |zip_file|
  24. zip_file.each do |entry|
  25. file_name = entry.name.split('/').last
  26. dest_path = File.join(@tmp_dir_path, file_name)
  27. @extracted_paths << dest_path
  28. entry.extract(dest_path)
  29. rescue Zip::DestinationFileExistsError
  30. next
  31. end
  32. end
  33. end
  34. def copy
  35. date_format = '%d-%m-%Y'
  36. @copied_paths = @extracted_paths.map do |fp|
  37. file_name = File.basename(fp)
  38. puts "looking at #{file_name}"
  39. exif = EXIFR::JPEG.new(fp)
  40. # get date from file's exif data
  41. exif_date_str = exif.date_time.strftime(date_format)
  42. # destination dir for given file in public/images/dd-mm-yyyy
  43. dest_dir = File.join(Pathname.pwd, destination_path, exif_date_str)
  44. dest_path = File.join(dest_dir, File.basename(fp))
  45. # create destination dir if not already there
  46. FileUtils.mkdir_p(dest_dir) unless Dir.exist?(dest_dir)
  47. puts "#{file_name} --> #{dest_path}"
  48. FileUtils.cp(fp, dest_path)
  49. dest_path
  50. end
  51. end
  52. def generate_thumbnails
  53. @copied_paths.map do |fp|
  54. Thumbnail.new(fp).create
  55. end
  56. end
  57. end
  58. end