<commit_before>class Canvas

  def initialize(canvas_uri, canvas_api_key, refresh_token_options=nil)
    @per_page = 100
    @canvas_uri = UrlHelper.scheme_host(canvas_uri)
    @canvas_api_key = canvas_api_key
    @refresh_token_options = refresh_token_options
  end

  def headers
    {
      "Authorization" => "Bearer #{@canvas_api_key}",
      "content_type" => "json",
      'User-Agent' => "CanvasAPI Ruby"
    }
  end

  def full_url(api_url, use_api_prefix=true)
    if api_url[0...4] == 'http'
      api_url
    else
      if use_api_prefix
        "#{@canvas_uri}/api/v1/#{api_url}"
      else
        "#{@canvas_uri}/#{api_url}"
      end
    end
  end

  def api_put_request(api_url, payload)
    @method = 'PUT'
    @api_url = api_url
    @payload = payload
    check_result(HTTParty.put(full_url(api_url), :headers => headers, :body => payload))
  end

  def api_post_request(api_url, payload, use_api_prefix=true)
    unless @refreshing_token
      @method = 'POST'
      @api_url = api_url
      @payload = payload
    end
    result = HTTParty.post(full_url(api_url, use_api_prefix), :headers => headers, :body => payload)
    check_result(result)
  end

  def api_get_request(api_url)
    @method = 'GET'
    @api_url = api_url
    check_result(HTTParty.get(full_url(api_url), :headers => headers))
  end

  def refresh_token
    result = api_post_request("login/oauth2/token", {
      grant_type: 'refresh_token',
      client_id: @refresh_token_options[:client_id],
      client_secret: @refresh_token_options[:client_secret],
      refresh_token: @refresh_token_options[:refresh_token]
    }, false)
    if result
      @canvas_api_key = result['access_token']
      @refresh_token_options[:auth].update_attribute(:token, @canvas_api_key)
      repeat_request_once
    end
  end

  def repeat_request_once
    case @method
      when 'GET'
        api_get_request(@api_url)
      when 'POST'
        api_post_request(@api_url, @payload)
      when 'PUT'
        api_put_request(@api_url, @payload)
    end
  end

  def refresh_token_and_try_again
    if @refresh_token_options
      @refreshing_token = true
      refresh_token
    end
  end

  def check_result(result)
    if result.response.code == '401'
      refresh_token_and_try_again unless @refreshing_token
      @refreshing_token = false
      raise Canvas::UnauthorizedException, result['errors']
    elsif result.response.code == '404'
      raise Canvas::NotFoundException, result['errors']
    elsif !['200', '201'].include?(result.response.code)
      raise Canvas::InvalidRequestException, result['errors']
    end
    result
  end

  def get_next_url(link)
    return nil if link.blank?
    if url = link.split(',').find{|l| l.split(";")[1].strip == 'rel="next"' }
      url.split(';')[0].gsub(/[\<\>\s]/, "")
    end
  end

  def make_paged_api_request(api_url)
    connector = api_url.include?('?') ? '&' : '?'
    next_url = "#{api_url}#{connector}per_page=#{@per_page}"
    results = []
    while next_url do
      result = api_get_request(next_url)
      result.each{ |r| results << r }
      next_url = get_next_url(result.headers['link'])
    end
    results
  end

  def page_requests(api_url)
    connector = api_url.include?('?') ? '&' : '?'<commit_msg>Fixed refresh token code bug<commit_after>class Canvas

  def initialize(canvas_uri, canvas_api_key, refresh_token_options=nil)
    @per_page = 100
    @canvas_uri = UrlHelper.scheme_host(canvas_uri)
    @canvas_api_key = canvas_api_key
    @refresh_token_options = refresh_token_options
  end

  def headers
    {
      "Authorization" => "Bearer #{@canvas_api_key}",
      "content_type" => "json",
      'User-Agent' => "CanvasAPI Ruby"
    }
  end

  def full_url(api_url, use_api_prefix=true)
    if api_url[0...4] == 'http'
      api_url
    else
      if use_api_prefix
        "#{@canvas_uri}/api/v1/#{api_url}"
      else
        "#{@canvas_uri}/#{api_url}"
      end
    end
  end

  def api_put_request(api_url, payload)
    @method = 'PUT'
    @api_url = api_url
    @payload = payload
    check_result(HTTParty.put(full_url(api_url), :headers => headers, :body => payload))
  end

  def api_post_request(api_url, payload, use_api_prefix=true)
    unless @refreshing_token
      @method = 'POST'
      @api_url = api_url
      @payload = payload
    end
    result = HTTParty.post(full_url(api_url, use_api_prefix), :headers => headers, :body => payload)
    check_result(result)
  end

  def api_get_request(api_url)
    @method = 'GET'
    @api_url = api_url
    check_result(HTTParty.get(full_url(api_url), :headers => headers))
  end

  def refresh_token
    result = api_post_request("login/oauth2/token", {
      grant_type: 'refresh_token',
      client_id: @refresh_token_options[:client_id],
      client_secret: @refresh_token_options[:client_secret],
      refresh_token: @refresh_token_options[:refresh_token]
    }, false)
    if result
      @canvas_api_key = result['access_token']
      @refresh_token_options[:auth].update_attribute(:token, @canvas_api_key)
      repeat_request_once
    end
  end

  def repeat_request_once
    case @method
      when 'GET'
        api_get_request(@api_url)
      when 'POST'
        api_post_request(@api_url, @payload)
      when 'PUT'
        api_put_request(@api_url, @payload)
    end
  end

  def refresh_token_and_try_again
    if @refresh_token_options
      @refreshing_token = true
      refresh_token
    end
  end

  def check_result(result)
    if result.response.code == '401'
      unless @refreshing_token
        @refreshing_token = false
        return refresh_token_and_try_again
      end
      raise Canvas::UnauthorizedException, result['errors']
    elsif result.response.code == '404'
      raise Canvas::NotFoundException, result['errors']
    elsif !['200', '201'].include?(result.response.code)
      raise Canvas::InvalidRequestException, "#{result.response.code} - #{result['errors']} (#{@api_url})"
    end
    result
  end

  def get_next_url(link)
    return nil if link.blank?
    if url = link.split(',').find{|l| l.split(";")[1].strip == 'rel="next"' }
      url.split(';')[0].gsub(/[\<\>\s]/, "")
    end
  end

  def make_paged_api_request(api_url)
    connector = api_url.include?('?') ? '&' : '?'
    next_url = "#{api_url}#{connector}per_page=#{@per_page}"
    results = []
    while next_url do
      result = api_get_request(next_url)
      result.each{ |r| results << r }
      next_url = get_next_url(result.headers['link'])
    end
    results
  end

  def page_requests(api_url)
    connector = api_url.include?('?') ? '&' : '?'
{'fraction_non_alphanumeric': 0.1258157535286083, 'fraction_numerical': 0.0063742601305205645, 'mean_word_length': 3.282001299545159, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7268127', 'n_tokens_mistral': 2314, 'n_tokens_neox': 2269, 'n_words': 416}