【问题标题】:Update user photo in G Suite在 G Suite 中更新用户照片
【发布时间】:2016-11-12 00:23:49
【问题描述】:

我正在尝试使用以下代码更新 G Suite 用户的用户照片:

require 'google/apis/admin_directory_v1'
require 'googleauth'
require 'googleauth/stores/file_token_store'

require 'fileutils'

OOB_URI = 'urn:ietf:wg:oauth:2.0:oob'
CLIENT_SECRETS_PATH = 'client_secrets.json'
CREDENTIALS_PATH = File.join(Dir.home, '.credentials',
                             "admin-directory_v1-ruby-quickstart.yaml")
SCOPE = "https://www.googleapis.com/auth/admin.directory.user"    

def authorize
  FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))

  client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)
  token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)
  authorizer = Google::Auth::UserAuthorizer.new(
    client_id, SCOPE, token_store)
  user_id = 'default'
  credentials = authorizer.get_credentials(user_id)
  if credentials.nil?
    url = authorizer.get_authorization_url(
      base_url: OOB_URI)
    puts "Open the following URL in the browser and enter the " +
         "resulting code after authorization"
    puts url
    code = gets
    credentials = authorizer.get_and_store_credentials_from_code(
      user_id: user_id, code: code, base_url: OOB_URI)
  end
  credentials
end

# Initialize the API
service = Google::Apis::AdminDirectoryV1::DirectoryService.new
service.authorization = authorize

require "base64"    
pic = Base64.encode64(File.read('profilepic.png')).tr("+/", "-_")

photo = Google::Apis::AdminDirectoryV1::UserPhoto.new
photo.photo_data = pic

service.update_user_photo("user@domain.com", photo)

但是我收到了错误"invalid: Invalid Input: photoData (Google::Apis::ClientError)"。我开始怀疑这可能是客户端库上的错误,但我想先检查其他人是否成功执行此操作。

我已经能够使用pic = Base64.encode64(File.read('profilepic.png')).tr("+/", "-_") 返回的base64 编码字符串更新"Try it!" section here 中的照片,并且我已经能够使用PHP 客户端库来做到这一点。我认为这是一个错误是否正确?

【问题讨论】:

  • 请不要回滚好的编辑,Morfinismo - 标题相当简短,正文相当健谈,并且可以通过一些段落来完成。如果您对编辑不满意,那么很好的第一步是使用他们的@username ping 编辑器说出原因。所有的编辑都应该愿意听取你的意见。请注意,“不要编辑我的帖子”不是拒绝好的编辑的正当理由 - 相互编辑是这里的重点。
  • @halfer 多谢指教!

标签: ruby google-api google-api-ruby-client


【解决方案1】:

我知道这是一个非常古老的问题,但我遇到了同样的问题,结果是 google-api-client 库会自动对您的 photo_data 进行 base64 编码/解码,因此您只需将文件数据传递给它而不是编码它,否则它会被编码两次,你会遇到一个 400 错误。

# Read file
photo_data = File.read(image_path)

# Create a UserPhoto object
user_photo_object = Google::Apis::AdminDirectoryV1::UserPhoto.new(photo_data: photo_data)

# Update Photo
directory.update_user(user_key, user_photo_object)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-14
    • 1970-01-01
    • 2020-05-11
    相关资源
    最近更新 更多