-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice.go
87 lines (69 loc) · 2.07 KB
/
service.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main
import (
"encoding/json"
"fmt"
"golang.org/x/net/context"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/option"
"google.golang.org/api/youtube/v3"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
)
func credentialFile() string {
return filepath.Join(configDir(), ".credentials")
}
func tokenFile() string {
return filepath.Join(configDir(), ".token")
}
func getCachedToken() (*oauth2.Token, error) {
file, err := os.Open(tokenFile())
if nil != err {
return nil, err
}
token := &oauth2.Token{}
err = json.NewDecoder(file).Decode(token)
defer fclose(file)
return token, err
}
func saveToken(token *oauth2.Token) {
path := tokenFile()
log.Printf("Saving token to: %s\n", path)
file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
onError(err, "Unable to cache oauth token")
defer fclose(file)
onError(json.NewEncoder(file).Encode(token), "Unable to encode oauth token")
}
func getNewToken(config *oauth2.Config) *oauth2.Token {
authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
log.Printf("Go to the following link in your browser then type the "+
"authorization code: \n\t%v\n", authURL)
var code string
_, err := fmt.Scan(&code)
onError(err, "Unable to read authorization code")
token, err := config.Exchange(context.TODO(), code)
onError(err, "Unable to retrieve token from web")
saveToken(token)
return token
}
func getClient(ctx context.Context, config *oauth2.Config) *http.Client {
token, err := getCachedToken()
if nil != err {
token = getNewToken(config)
}
return config.Client(ctx, token)
}
func getService() *youtube.Service {
ctx := context.Background()
bytes, err := ioutil.ReadFile(credentialFile())
onError(err, "Unable to read client credentials file")
config, err := google.ConfigFromJSON(bytes, youtube.YoutubeScope)
onError(err, "Unable to parse client credentials file to config")
client := getClient(ctx, config)
service, err := youtube.NewService(ctx, option.WithHTTPClient(client))
onError(err, "Error creating YouTube client")
return service
}