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



69
70
71
72
73
74
75
76
77
78
79
# File 'lib/rabbit/parser/ext/image.rb', line 69

def local_path_to_image_filename(canvas, path)
  path = Pathname.new(GLib.filename_from_utf8(path))
  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



87
88
89
90
91
# File 'lib/rabbit/parser/ext/image.rb', line 87

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



93
94
95
96
97
98
99
100
101
102
103
# File 'lib/rabbit/parser/ext/image.rb', line 93

def setup_image_file(canvas, uri, filename)
  begin
    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)


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

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

.tmp_filename(canvas, key) ⇒ Object



81
82
83
84
85
# File 'lib/rabbit/parser/ext/image.rb', line 81

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



45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/rabbit/parser/ext/image.rb', line 45

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



58
59
60
61
62
63
64
65
66
67
# File 'lib/rabbit/parser/ext/image.rb', line 58

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