github.com/cloudreve/Cloudreve/v3@v3.0.0-20240224133659-3edb00a6484c/pkg/filesystem/driver/googledrive/client.go (about)

     1  package googledrive
     2  
     3  import (
     4  	"errors"
     5  	model "github.com/cloudreve/Cloudreve/v3/models"
     6  	"github.com/cloudreve/Cloudreve/v3/pkg/cluster"
     7  	"github.com/cloudreve/Cloudreve/v3/pkg/request"
     8  	"google.golang.org/api/drive/v3"
     9  )
    10  
    11  // Client Google Drive client
    12  type Client struct {
    13  	Endpoints  *Endpoints
    14  	Policy     *model.Policy
    15  	Credential *Credential
    16  
    17  	ClientID     string
    18  	ClientSecret string
    19  	Redirect     string
    20  
    21  	Request           request.Client
    22  	ClusterController cluster.Controller
    23  }
    24  
    25  // Endpoints OneDrive客户端相关设置
    26  type Endpoints struct {
    27  	UserConsentEndpoint string // OAuth认证的基URL
    28  	TokenEndpoint       string // OAuth token 基URL
    29  	EndpointURL         string // 接口请求的基URL
    30  }
    31  
    32  const (
    33  	TokenCachePrefix = "googledrive_"
    34  
    35  	oauthEndpoint   = "https://oauth2.googleapis.com/token"
    36  	userConsentBase = "https://accounts.google.com/o/oauth2/auth"
    37  	v3DriveEndpoint = "https://www.googleapis.com/drive/v3"
    38  )
    39  
    40  var (
    41  	// Defualt required scopes
    42  	RequiredScope = []string{
    43  		drive.DriveScope,
    44  		"openid",
    45  		"profile",
    46  		"https://www.googleapis.com/auth/userinfo.profile",
    47  	}
    48  
    49  	// ErrInvalidRefreshToken 上传策略无有效的RefreshToken
    50  	ErrInvalidRefreshToken = errors.New("no valid refresh token in this policy")
    51  )
    52  
    53  // NewClient 根据存储策略获取新的client
    54  func NewClient(policy *model.Policy) (*Client, error) {
    55  	client := &Client{
    56  		Endpoints: &Endpoints{
    57  			TokenEndpoint:       oauthEndpoint,
    58  			UserConsentEndpoint: userConsentBase,
    59  			EndpointURL:         v3DriveEndpoint,
    60  		},
    61  		Credential: &Credential{
    62  			RefreshToken: policy.AccessKey,
    63  		},
    64  		Policy:            policy,
    65  		ClientID:          policy.BucketName,
    66  		ClientSecret:      policy.SecretKey,
    67  		Redirect:          policy.OptionsSerialized.OauthRedirect,
    68  		Request:           request.NewClient(),
    69  		ClusterController: cluster.DefaultController,
    70  	}
    71  
    72  	return client, nil
    73  }