mirror of https://github.com/synctv-org/synctv
You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
75 lines
2.0 KiB
Go
75 lines
2.0 KiB
Go
1 year ago
|
package providers
|
||
1 year ago
|
|
||
|
import (
|
||
|
"context"
|
||
|
"fmt"
|
||
|
"net/http"
|
||
|
|
||
|
json "github.com/json-iterator/go"
|
||
1 year ago
|
"github.com/synctv-org/synctv/internal/provider"
|
||
1 year ago
|
"golang.org/x/oauth2"
|
||
|
)
|
||
|
|
||
|
// https://pan.baidu.com/union/apply
|
||
|
type BaiduNetDiskProvider struct {
|
||
|
config oauth2.Config
|
||
|
}
|
||
|
|
||
1 year ago
|
func (p *BaiduNetDiskProvider) Init(c provider.Oauth2Option) {
|
||
1 year ago
|
p.config.Scopes = []string{"basic", "netdisk"}
|
||
|
p.config.Endpoint = oauth2.Endpoint{
|
||
|
AuthURL: "https://openapi.baidu.com/oauth/2.0/authorize",
|
||
|
TokenURL: "https://openapi.baidu.com/oauth/2.0/token",
|
||
|
}
|
||
1 year ago
|
p.config.ClientID = c.ClientID
|
||
|
p.config.ClientSecret = c.ClientSecret
|
||
|
p.config.RedirectURL = c.RedirectURL
|
||
1 year ago
|
}
|
||
|
|
||
1 year ago
|
func (p *BaiduNetDiskProvider) Provider() provider.OAuth2Provider {
|
||
1 year ago
|
return "baidu-netdisk"
|
||
|
}
|
||
|
|
||
1 year ago
|
func (p *BaiduNetDiskProvider) NewAuthURL(state string) string {
|
||
|
return p.config.AuthCodeURL(state, oauth2.AccessTypeOnline)
|
||
1 year ago
|
}
|
||
|
|
||
1 year ago
|
func (p *BaiduNetDiskProvider) GetToken(ctx context.Context, code string) (*oauth2.Token, error) {
|
||
|
return p.config.Exchange(ctx, code)
|
||
|
}
|
||
1 year ago
|
func (p *BaiduNetDiskProvider) GetUserInfo(ctx context.Context, tk *oauth2.Token) (*provider.UserInfo, error) {
|
||
1 year ago
|
client := p.config.Client(ctx, tk)
|
||
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("https://pan.baidu.com/rest/2.0/xpan/nas?method=uinfo&access_token=%s", tk.AccessToken), nil)
|
||
1 year ago
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
resp, err := client.Do(req)
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
defer resp.Body.Close()
|
||
|
ui := baiduNetDiskProviderUserInfo{}
|
||
|
err = json.NewDecoder(resp.Body).Decode(&ui)
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
if ui.Errno != 0 {
|
||
|
return nil, fmt.Errorf("baidu oauth2 get user info error: %s", ui.Errmsg)
|
||
|
}
|
||
1 year ago
|
return &provider.UserInfo{
|
||
1 year ago
|
Username: ui.BaiduName,
|
||
|
ProviderUserID: ui.Uk,
|
||
|
}, nil
|
||
|
}
|
||
|
|
||
|
func init() {
|
||
1 year ago
|
provider.RegisterProvider(new(BaiduNetDiskProvider))
|
||
1 year ago
|
}
|
||
|
|
||
|
type baiduNetDiskProviderUserInfo struct {
|
||
|
BaiduName string `json:"baidu_name"`
|
||
|
Errmsg string `json:"errmsg"`
|
||
|
Errno int `json:"errno"`
|
||
|
Uk uint `json:"uk"`
|
||
|
}
|