def uri_expand(url, limit = 5)
      case url
      when URI
        uri = url
      else
        url = url.to_s
        begin
          uri = Utils.normalize_uri(url)
        rescue URI::Error
          return url
        end
      end

      http = Faraday.new do |builder|
        builder.adapter :net_http
        # builder.use FaradayMiddleware::FollowRedirects, limit: limit
        # ...does not handle non-HTTP URLs.
      end

      limit.times do
        begin
          case uri
          when URI::HTTP
            return uri.to_s unless uri.host
            response = http.head(uri)
            case response.status
            when 301, 302, 303, 307
              if location = response['location']
                uri += Utils.normalize_uri(location)
                next
              end
            end
          end
        rescue URI::Error, Faraday::Error, SystemCallError => e
          logger.error "#{e.class} in #{__method__}(#{url.inspect}) [uri=#{uri.to_s.inspect}]: #{e.message}:\n#{e.backtrace.join("\n")}"
        end

        return uri.to_s
      end

      logger.error "Too many rediretions in #{__method__}(#{url.inspect}) [uri=#{uri.to_s.inspect}]"

      url
    end
def uri_expand(url, limit = 5)
      case url
      when URI
        uri = url
      else
        url = url.to_s
        begin
          uri = Utils.normalize_uri(url)
        rescue URI::Error
          return url
        end
      end

      http = Faraday.new do |builder|
        builder.adapter :net_http
        # builder.use FaradayMiddleware::FollowRedirects, limit: limit
        # ...does not handle non-HTTP URLs.
      end

      limit.times do
        begin
          case uri
          when URI::HTTP
            return uri.to_s unless uri.host
            response = http.head(uri)
            case response.status
            when 301, 302, 303, 307
              if location = response['location']
                uri += Utils.normalize_uri(location)
                next
              end
            end
          end
        rescue URI::Error, Faraday::Error, SystemCallError => e
          logger.error "#{e.class} in #{__method__}(#{url.inspect}) [uri=#{uri.to_s.inspect}]: #{e.message}:\n#{e.backtrace.join("\n")}"
        end

        return uri.to_s
      end

      logger.error "Too many rediretions in #{__method__}(#{url.inspect}) [uri=#{uri.to_s.inspect}]"

      url
    end
Get the destination URL of a given URL by recursively following
 redirects, up to 5 times in a row.  If a given string is not a
 valid absolute HTTP URL or in case of too many redirects, the
 original string is returned.  If any network/protocol error
 occurs while following redirects, the last URL followed is
 returned.