首页 > 解决方案 > Ruby Google Drive API - web_content_link 上的 403 禁止

问题描述

我可以在 Google Drive 中很好地阅读和扫描文件,但无论我做什么,我似乎都无法访问 web_content_link。我的 Auth 烫发看起来不错。我完全不知所措。

我将一些 Google Drive API 逻辑抽象为 google_setup.rb。

然后在我的 rake 文件中,我要做的就是访问下载文件。我似乎能够很好地扫描文件,但即使在我看来,我应该有权访问下载链接,但我总是收到 403 Forbidden 错误。

如果你能帮上忙,请告诉我!

google_setup.rb

require 'google/apis/drive_v3'
require 'googleauth'
require 'googleauth/stores/file_token_store'
require 'fileutils'
require 'open-uri'

module GoogleSetup
  OOB_URI = "urn:ietf:wg:oauth:2.0:oob".freeze
  def self.authorize
    client_id = Google::Auth::ClientId.from_file Rails.root.join('lib', 'assets', 'credentials.json').freeze
    token_store = Google::Auth::Stores::FileTokenStore.new file: 'token.yaml'
    authorizer = Google::Auth::UserAuthorizer.new client_id, Google::Apis::DriveV3::AUTH_DRIVE, token_store
    user_id = 'default'

    credentials = authorizer.get_credentials user_id
    if credentials.nil?
      url = authorizer.get_authorization_url base_url: 'https://seeburg.herokuapp.com/'
      puts 'Open the following URL in the browser and enter the ' \
           "resulting code after authorization:\n" + url
      code = ENV["GOOGLE_CODE"]
      credentials = authorizer.get_and_store_credentials_from_code(
        user_id: user_id, code: code, base_url: OOB_URI
      )
    end
    drive_service = Google::Apis::DriveV3::DriveService.new
    drive_service.client_options.application_name = 'Seeburg Google Drive Integration'
    drive_service.authorization = credentials
    drive_service
  end

  def self.get_files(query)
    drive_service = GoogleSetup.authorize
    files = []
    @page_token = ''
    while @page_token

      begin
        response = drive_service.list_files(page_size: 100, q: query, page_token: @page_token, fields: 'nextPageToken, files')
        @page_token = response.next_page_token || false
        if response.files.empty?
          puts 'No files found'
        else
          files = response.files
        end
        sleep 0.5
      rescue StandardError => e
        puts e
      end
    end

    files
  end
end

test_google.rake

require 'google_setup'
require 'fileutils'
require 'open-uri'

desc 'Test Google Drive API'

task test_google: :environment do
  folder_id = "1j1Ly_NveiCtfrolzSxmrbHS1DenPZagV";
  query = "name contains 'MP3' and '#{folder_id}' in parents";

  GoogleSetup.get_files(query).each do |file|

    ##If I can get this section to work, everything else I need will work
    begin
      puts download = URI.open(file.web_content_link)
    rescue StandardError => e
      puts e
    end

  end
end

标签: rubygoogle-drive-api

解决方案


它最终成为超时问题。Google 只允许您在身份验证的时间范围内采取某些行动。


推荐阅读