Module: Rabbit::Parser::Ext::Image::Private

Defined in:
lib/rabbit/parser/ext/image.rb

Constant Summary collapse

ALLOWED_IMG_URL_SCHEME =
["http", "https", "file"]

Class Method Summary collapse

Class Method Details

.local_path_to_image_filename(canvas, path) ⇒ Object



86
87
88
89
90
91
92
93
94
95
96
# File 'lib/rabbit/parser/ext/image.rb', line 86

def local_path_to_image_filename(canvas, path)
  path = Pathname.new(Filename.new(path).encode)
  return path.to_s if path.absolute?

  expanded_path = canvas.full_path(path.to_s)
  if start_with_scheme?(expanded_path)
    uri_string_to_image_filename(canvas, expanded_path)
  else
    expanded_path
  end
end

.other_uri_filename(canvas, uri) ⇒ Object



104
105
106
107
108
# File 'lib/rabbit/parser/ext/image.rb', line 104

def other_uri_filename(canvas, uri)
  filename = tmp_filename(canvas, uri.to_s)
  setup_image_file(canvas, uri, filename)
  filename
end

.setup_image_file(canvas, uri, filename) ⇒ Object



110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/rabbit/parser/ext/image.rb', line 110

def setup_image_file(canvas, uri, filename)
  return if File.exist?(filename)
  begin
    URI.open(uri, "rb") do |in_file|
      File.open(filename, "wb") do |out|
        out.print(in_file.read)
      end
    end
  rescue SocketError, OpenURI::HTTPError
    canvas.logger.warn("#{$!.message}: #{uri}")
  end
end

.start_with_scheme?(uri_string) ⇒ Boolean

Returns:

  • (Boolean)


123
124
125
# File 'lib/rabbit/parser/ext/image.rb', line 123

def start_with_scheme?(uri_string)
  /\A[a-z][a-z\d+\-.]+:/i =~ uri_string
end

.tmp_filename(canvas, key) ⇒ Object



98
99
100
101
102
# File 'lib/rabbit/parser/ext/image.rb', line 98

def tmp_filename(canvas, key)
  dir = canvas.tmp_dir_name
  FileUtils.mkdir_p(dir)
  File.join(dir, CGI.escape(key))
end

.uri_string_to_image_filename(canvas, uri_string) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/rabbit/parser/ext/image.rb', line 62

def uri_string_to_image_filename(canvas, uri_string)
  if start_with_scheme?(uri_string)
    uri = URI.parse(uri_string)
    scheme = uri.scheme
    unless ALLOWED_IMG_URL_SCHEME.include?(scheme.to_s.downcase)
      return nil
    end
    uri_to_image_filename(canvas, uri)
  else
    local_path_to_image_filename(canvas, uri_string)
  end
end

.uri_to_image_filename(canvas, uri) ⇒ Object



75
76
77
78
79
80
81
82
83
84
# File 'lib/rabbit/parser/ext/image.rb', line 75

def uri_to_image_filename(canvas, uri)
  case uri.scheme.to_s.downcase
  when "file"
    Filename.new(uri.path).encode
  when "http", "https", "ftp"
    other_uri_filename(canvas, uri)
  else
    nil
  end
end