LoginSignup
9
8

More than 5 years have passed since last update.

Google Drive APIでアップロードしたファイルの公開範囲を変更する

Last updated at Posted at 2015-06-14

この記事の続き。

googleapi - CSVダウンロードを作るのに飽きたからGoogle Drive APIを使ってみた - Qiita

「その他」の公開範囲を変更する方法を調べてみた。

まず最初にファイルアップロードするときにFile構造体の Permissions に情報を詰めてみました。アップロードしてすぐに公開範囲が変更されるとおもいきや非公開のまま。このフィールドはRead Onlyなのかな?

つぎに一旦アップロードを終わらせてから、そのファイルIDに対して公開範囲を設定するリクエストを投げてみました。
そしたらOK、ちゃんと公開範囲が設定されてました。

スクリーンショット 2015-06-14 22.46.09.png

(Google Appsで使っていて、同じ会社の人に公開したいというケースを想定)

使ったのはこのコード。前回と同じようにサンプルコードを改造して書きました。

gdrive_permission.go
package main

import (
    "code.google.com/p/goauth2/oauth"
    "fmt"
    "google.golang.org/api/drive/v2"
    "log"
    "net/http"
    "os"
)

// Settings for authorization.
var config = &oauth.Config{
    ClientId:     "YOUR_CLIENT_ID",
    ClientSecret: "YOUR_CLIENT_SECRET",
    Scope:        "https://www.googleapis.com/auth/drive",
    RedirectURL:  "urn:ietf:wg:oauth:2.0:oob",
    AuthURL:      "https://accounts.google.com/o/oauth2/auth",
    TokenURL:     "https://accounts.google.com/o/oauth2/token",
    TokenCache:   oauth.CacheFile("cache.json"),
}

// Uploads a file to Google Drive
func main() {
    t := &oauth.Transport{
        Config:    config,
        Transport: http.DefaultTransport,
    }

    // キャッシュがあったらブラウザ認証しない
    _, err := config.TokenCache.Token()
    if err != nil {
        // Generate a URL to visit for authorization.
        authUrl := config.AuthCodeURL("state")
        log.Printf("Go to the following link in your browser: %v\n", authUrl)

        // Read the code, and exchange it for a token.
        log.Printf("Enter verification code: ")
        var code string
        fmt.Scanln(&code)
        _, err := t.Exchange(code)
        if err != nil {
            log.Fatalf("An error occurred exchanging the code: %v\n", err)
        }
    }

    // Create a new authorized Drive client.
    svc, err := drive.New(t.Client())
    if err != nil {
        log.Fatalf("An error occurred creating Drive client: %v\n", err)
    }

    // Define the metadata for the file we are going to create.
    f := &drive.File{
        Title:       "My Document",
        Description: "My test document",
    }

    // Read the file data that we are going to upload.
    m, err := os.Open("document.txt")
    if err != nil {
        log.Fatalf("An error occurred reading the document: %v\n", err)
    }

    // Make the API request to upload metadata and file data.
    r, err := svc.Files.Insert(f).Media(m).Do()
    if err != nil {
        log.Fatalf("An error occurred uploading the document: %v\n", err)
    }
    log.Printf("Created: ID=%v, Title=%v\n", r.Id, r.Title)


    // 公開範囲変更のために追加したコード
    pm := &drive.Permission{
        Type:  "domain",
        Role:  "reader", // 閲覧者設定
        Value: "{GoogleAppsのドメイン}",
    }

    // SendNotificationEmails(false)にしないとスクリプト実行のたびにメールが飛んでしまう(?
    rpm, err := svc.Permissions.Insert(r.Id, pm).SendNotificationEmails(false).Do()
    if err != nil {
        log.Fatalf("Permission error : %v\n", err)
    }
    log.Printf("Permission: type:%v, role:%v\n", rpm.Type, rpm.Role)
}

上記では Role: "reader" で閲覧者権限をインサートしてますが、 wirterに変えると共同編集者になります。ほかに anyone とかあります。
詳しくは次の公式ドキュメント参照。

Share Files   |   Drive REST API   |   Google Developers

Googleグループで公開範囲を設定などもできるみたいですねー。

まずは調べた分だけ共有しまーす。

つづく。

9
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8