Class: Url

Inherits:
Object
  • Object
show all
Defined in:
lib/imagekit/url.rb

Instance Method Summary collapse

Constructor Details

#initialize(request_obj) ⇒ Url

Returns a new instance of Url.



14
15
16
# File 'lib/imagekit/url.rb', line 14

def initialize(request_obj)
  @req_obj = request_obj
end

Instance Method Details

#build_url(options) ⇒ Object



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
# File 'lib/imagekit/url.rb', line 26

def build_url(options)
  # build url from all options

  path = options.fetch(:path, "")
  src = options.fetch(:src, "")
  url_endpoint = options.fetch(:url_endpoint, "")
  transformation_position = options[:transformation_position]

  unless Default::VALID_TRANSFORMATION_POSITION.include? transformation_position
    raise ArgumentError, INVALID_TRANSFORMATION_POS
  end

  src_param_used_for_url = false
  if (src != "") || (transformation_position == Default::QUERY_TRANSFORMATION_POSITION)
    src_param_used_for_url = true
  end

  if path == "" && src == ""
    return ""
  end

  result_url_hash = {'host': "", 'path': "", 'query': ""}
  existing_query=nil
  if path != ""
    parsed_url = Addressable::URI.parse(path)
    existing_query=parsed_url.query
    parsed_host = Addressable::URI.parse(url_endpoint)
    result_url_hash[:scheme] = parsed_host.scheme

    # making sure single '/' at end
    result_url_hash[:host] = parsed_host.host.to_s.chomp("/") + parsed_host.path.chomp("/") + "/"
    result_url_hash[:path] = trim_slash(parsed_url.path)
  else
    parsed_url = Addressable::URI.parse(src)
    existing_query=parsed_url.query
    host = parsed_url.host
    result_url_hash[:userinfo] = parsed_url.userinfo if parsed_url.userinfo
    result_url_hash[:host] = host
    result_url_hash[:scheme] = parsed_url.scheme
    result_url_hash[:path] = parsed_url.path
    src_param_used_for_url = true
  end
  query_params = {}
  if existing_query!=nil
    existing_query.split("&").each do |part|
      parts=part.split("=")
      if parts.length==2
        query_params[parts[0]]=parts[1]
      end
    end
  end
  options.fetch(:query_parameters, {}).each do |key, value|
    query_params[key]=value
  end
  transformation_str = transformation_to_str(options[:transformation]).chomp("/")

  unless transformation_str.nil? || transformation_str.strip.empty?
    if (transformation_position == Default::QUERY_TRANSFORMATION_POSITION) || src_param_used_for_url == true
      result_url_hash[:query] = "#{Default::TRANSFORMATION_PARAMETER}=#{transformation_str}"
      query_params[:tr]=transformation_str
    else
      result_url_hash[:path] = "#{Default::TRANSFORMATION_PARAMETER}:#{transformation_str}/#{result_url_hash[:path]}"
    end

  end

  result_url_hash[:host] = result_url_hash[:host].to_s.reverse.chomp("/").reverse
  result_url_hash[:path] = result_url_hash[:path].chomp("/")
  result_url_hash[:scheme] ||= "https"

  query_param_arr = []
  query_param_arr.push("ik-sdk-version=ruby-"+Imagekit::Sdk::VERSION)
  query_params.each do |key, value|
    if value.to_s == ""
      query_param_arr.push(key.to_s)
    else
      query_param_arr.push(key.to_s + "=" + value.to_s)
    end
  end

  query_param_str = query_param_arr.join("&")
  result_url_hash[:query] = query_param_str

  # Signature String and Timestamp
  # We can do this only for URLs that are created using urlEndpoint and path parameter
  # because we need to know the endpoint to be able to remove it from the URL to create a signature
  # for the remaining. With the src parameter, we would not know the "pattern" in the URL
  if options[:signed] && !(options[:src])
    intermediate_url = result_url_hash.fetch(:scheme, "") + "://" + result_url_hash.fetch(:host, "") + result_url_hash.fetch(:path, "")
    if result_url_hash[:query]!=nil && result_url_hash[:query]!=""
      intermediate_url += result_url_hash.fetch(:query, "")
    end
  end

  url=hash_to_url(result_url_hash)
  if options[:signed]
    private_key = options[:private_key]
    expire_seconds = options[:expire_seconds]
    expire_timestamp = get_signature_timestamp(expire_seconds)
    url_signature = get_signature(private_key, url, url_endpoint, expire_timestamp)
    query_param_arr.push(Default::SIGNATURE_PARAMETER + "=" + url_signature)

    if expire_timestamp && (expire_timestamp != Default::TIMESTAMP)
      query_param_arr.push(Default::TIMESTAMP_PARAMETER + "=" + expire_timestamp.to_s)
    end
  
    query_param_str = query_param_arr.join("&")
    result_url_hash[:query] = query_param_str
    
    url=hash_to_url(result_url_hash)
  end
  url
end

#extend_url_options(options) ⇒ Object



198
199
200
201
202
203
204
205
# File 'lib/imagekit/url.rb', line 198

def extend_url_options(options)
  attr_dict = {"public_key": @req_obj.public_key,
               "private_key": @req_obj.private_key,
               "url_endpoint": @req_obj.url_endpoint,
               "transformation_position": @req_obj.transformation_position, }
  # extending  url options
  attr_dict.merge(options)
end

#generate_url(options) ⇒ Object



18
19
20
21
22
23
24
# File 'lib/imagekit/url.rb', line 18

def generate_url(options)
  if options.key? :src
    options[:transformation_position] = Default::TRANSFORMATION_POSITION
  end
  extended_options = extend_url_options(options)
  build_url(extended_options)
end

#get_signature(private_key, url, url_endpoint, expiry_timestamp) ⇒ Object



184
185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/imagekit/url.rb', line 184

def get_signature(private_key, url, url_endpoint, expiry_timestamp)
  # creates signature(hashed hex key) and returns from
  # private_key, url, url_endpoint and expiry_timestamp
  if expiry_timestamp==0
    expiry_timestamp=Default::DEFAULT_TIMESTAMP
  end
  if url_endpoint[url_endpoint.length-1]!="/"
    url_endpoint+="/"
  end
  replaced_url=url.gsub(url_endpoint, "")
  replaced_url =  replaced_url + expiry_timestamp.to_s
  OpenSSL::HMAC.hexdigest("SHA1", private_key, replaced_url)
end

#get_signature_timestamp(seconds) ⇒ Object



172
173
174
175
176
177
178
179
180
181
182
# File 'lib/imagekit/url.rb', line 172

def get_signature_timestamp(seconds)
  # this function returns either default time stamp
  # or current unix time and expiry seconds to get
  # signature time stamp

  if seconds.to_i == 0
    Default::DEFAULT_TIMESTAMP
  else
    DateTime.now.strftime("%s").to_i + seconds.to_i
  end
end

#hash_to_url(url_hash) ⇒ Object



207
208
209
210
211
212
213
214
# File 'lib/imagekit/url.rb', line 207

def hash_to_url(url_hash)
  generated_url = url_hash.fetch(:scheme, "") + "://" + url_hash.fetch(:host, "") + url_hash.fetch(:path, "")
  if url_hash[:query] != ""
    generated_url = generated_url + "?" + url_hash.fetch(:query, "")
    return generated_url
  end
  generated_url
end

#transformation_to_str(transformation) ⇒ Object



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
# File 'lib/imagekit/url.rb', line 140

def transformation_to_str(transformation)
  # creates transformation_position string for url
  # from transformation dictionary

  unless transformation.is_a?(Array)
    return ""
  end

  parsed_transforms = []
  (0..(transformation.length - 1)).each do |i|
    parsed_transform_step = []

    transformation[i].keys.each do |key|
      transform_key = SUPPORTED_TRANS.fetch(key, nil)
      transform_key ||= key

      if transform_key == "oi" || transform_key == "di"
        transformation[i][key][0] = "" if transformation[i][key][0] == "/"
        transformation[i][key] = transformation[i][key].gsub("/", "@@")
      end

      if transformation[i][key] == "-"
        parsed_transform_step.push(transform_key)
      else
        parsed_transform_step.push("#{transform_key}#{Default::TRANSFORM_KEY_VALUE_DELIMITER}#{transformation[i][key]}")
      end
    end
    parsed_transforms.push(parsed_transform_step.join(Default::TRANSFORM_DELIMITER))
  end
  parsed_transforms.join(Default::CHAIN_TRANSFORM_DELIMITER)
end

#trim_slash(str, both = true) ⇒ Object



216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'lib/imagekit/url.rb', line 216

def trim_slash(str, both = true)
  if str == ""
    return ""
  end
  # remove slash from a string
  # if both is not provide trims both slash
  # example - '/abc/' returns 'abc'
  # if both=false it will only trim end slash
  # example - '/abc/' returns '/abc'
  # NOTE: IT'S RECOMMENDED TO USE inbuilt .chomp('string you want to remove')
  # FOR REMOVING ONLY TRAILING SLASh
  if both
    str[0].chomp("/") + str[1..-2] + str[-1].chomp("/")
  else
    str.chomp("/")
  end
end