我想为Google Apps服务的用户自动创建文档 考虑:
这可以通过现有的Ruby库实现吗? (大多数人使用2-legged auth来完成此操作,而不是管理员。)
答案 0 :(得分:1)
我能够通过“服务帐户”和Google的(alpha)gem google-api-client
完成此操作。这是一个Ruby类,从不同的Google文档中采样,在实例化时收集用户的电子邮件(来自您管理的Google Apps域)。
require 'google/api_client'
class GoogleDriveConnection
def initialize(user_email=nil)
@client = Google::APIClient.new
@drive = @client.discovered_api('drive', 'v2')
key_file_name = '<DOWNLOADED WHEN CREATING A SERVICE ACCOUNT>.p12'
key = Google::APIClient::PKCS12.load_key("#{Rails.root.to_s}/config/#{key_file_name}", 'notasecret')
asserter = Google::APIClient::JWTAsserter.new(
'<THE EMAIL ADDRESS OF YOUR SERVICE ACCOUNT>',
'https://www.googleapis.com/auth/drive',
key)
@client.authorization = asserter.authorize(user_email)
end
def insert_file(title, description, parent_id, mime_type, file_name)
file = @drive.files.insert.request_schema.new({
'title' => title,
'description' => description,
'mimeType' => mime_type
})
# Set the parent folder.
if parent_id
file.parents = [{'id' => parent_id}]
end
media = Google::APIClient::UploadIO.new(file_name, mime_type)
result = @client.execute(
:api_method => @drive.files.insert,
:body_object => file,
:media => media,
:parameters => {
'uploadType' => 'multipart',
'convert' => true,
'alt' => 'json'})
if result.status == 200
return result.data
else
puts "An error occurred: #{result.data['error']['message']}"
return nil
end
end
def list_files
result = @client.execute!(:api_method => @drive.files.list)
result.data.to_hash
end
def get_file(file_id)
result = @client.execute!(
:api_method => @drive.files.get,
:parameters => { 'fileId' => file_id })
result.data.to_hash
end
private
def token
@client.authorization.access_token
end
end
用法很简单:
g = GoogleDriveConnection.new('me@mycompany.com')
g.insert_file('My file', 'File stuff', nil, 'text/csv', "#{Rails.root}/tmp/test.csv")
*创建服务帐户并管理“API项目”非常棘手。 This guide似乎最有用。