Skip to content

Commit

Permalink
added utils to upload
Browse files Browse the repository at this point in the history
  • Loading branch information
allan committed Jul 8, 2024
1 parent cdab2d3 commit 48bbc7b
Show file tree
Hide file tree
Showing 3 changed files with 220 additions and 41 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,6 @@
go.work
go.work.sum

env/.env.local
env/.env.local

client_secret.json
44 changes: 4 additions & 40 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,57 +1,21 @@
package main

import (
"context"
"fmt"
"log"

"github.com/HiWay-Media/youtube-go-example/env"
"golang.org/x/oauth2"
"google.golang.org/api/option"
"google.golang.org/api/youtube/v3"
)

func main() {

appConfig := env.GetEnvConfig()
ctx := context.Background()
conf := &oauth2.Config{
ClientID: appConfig.ClientID, // from https://console.developers.google.com/project/<your-project-id>/apiui/credential
ClientSecret: appConfig.ClientSecret, // from https://console.developers.google.com/project/<your-project-id>/apiui/credential
Endpoint: oauth2.Endpoint{
AuthURL: "https://provider.com/o/oauth2/auth",
TokenURL: "https://provider.com/o/oauth2/token",
},
Scopes: []string{youtube.YoutubeUploadScope},
}

// use PKCE to protect against CSRF attacks
// https://www.ietf.org/archive/id/draft-ietf-oauth-security-topics-22.html#name-countermeasures-6
verifier := oauth2.GenerateVerifier()

// Redirect user to consent page to ask for permission
// for the scopes specified above.
url := conf.AuthCodeURL("state", oauth2.AccessTypeOffline, oauth2.S256ChallengeOption(verifier))
fmt.Printf("Visit the URL for the auth dialog: %v", url)
//appConfig := env.GetEnvConfig()

// Use the authorization code that is pushed to the redirect
// URL. Exchange will do the handshake to retrieve the
// initial access token. The HTTP Client returned by
// conf.Client will refresh the token as necessary.
var code string
if _, err := fmt.Scan(&code); err != nil {
log.Fatal(err)
}
tok, err := conf.Exchange(ctx, code, oauth2.VerifierOption(verifier))
if err != nil {
log.Fatal(err)
}
client := getClient(youtube.YoutubeUploadScope)

//client := conf.Client(ctx, tok)
//client.Get("...")
service, err := youtube.New(client)

// Create a new YouTube service
service, err := youtube.NewService(ctx, option.WithTokenSource(conf.TokenSource(ctx, tok)))
//service, err := youtube.NewService(ctx, option.WithTokenSource(conf.TokenSource(ctx, tok)))
if err != nil {
log.Fatalf("Unable to create YouTube service: %v", err)
}
Expand Down
213 changes: 213 additions & 0 deletions utils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
package main

import (
"context"
"encoding/json"
"fmt"
"log"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"os/user"
"path/filepath"
"runtime"

"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)

// This variable indicates whether the script should launch a web server to
// initiate the authorization flow or just display the URL in the terminal
// window. Note the following instructions based on this setting:
// * launchWebServer = true
// 1. Use OAuth2 credentials for a web application
// 2. Define authorized redirect URIs for the credential in the Google APIs
// Console and set the RedirectURL property on the config object to one
// of those redirect URIs. For example:
// config.RedirectURL = "http://localhost:8090"
// 3. In the startWebServer function below, update the URL in this line
// to match the redirect URI you selected:
// listener, err := net.Listen("tcp", "localhost:8090")
// The redirect URI identifies the URI to which the user is sent after
// completing the authorization flow. The listener then captures the
// authorization code in the URL and passes it back to this script.
//
// * launchWebServer = false
// 1. Use OAuth2 credentials for an installed application. (When choosing
// the application type for the OAuth2 client ID, select "Other".)
// 2. Set the redirect URI to "urn:ietf:wg:oauth:2.0:oob", like this:
// config.RedirectURL = "urn:ietf:wg:oauth:2.0:oob"
// 3. When running the script, complete the auth flow. Then copy the
// authorization code from the browser and enter it on the command line.
const launchWebServer = false

// getClient uses a Context and Config to retrieve a Token
// then generate a Client. It returns the generated Client.
func getClient(scope string) *http.Client {
ctx := context.Background()

b, err := os.ReadFile("client_secret.json")
if err != nil {
log.Fatalf("Unable to read client secret file: %v", err)
}

// If modifying the scope, delete your previously saved credentials
// at ~/.credentials/youtube-go.json
config, err := google.ConfigFromJSON(b, scope)
if err != nil {
log.Fatalf("Unable to parse client secret file to config: %v", err)
}

// Use a redirect URI like this for a web app. The redirect URI must be a
// valid one for your OAuth2 credentials.
config.RedirectURL = "http://localhost:8090"
// Use the following redirect URI if launchWebServer=false in oauth2.go
// config.RedirectURL = "urn:ietf:wg:oauth:2.0:oob"

cacheFile, err := tokenCacheFile()
if err != nil {
log.Fatalf("Unable to get path to cached credential file. %v", err)
}
tok, err := tokenFromFile(cacheFile)
if err != nil {
authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
if launchWebServer {
fmt.Println("Trying to get token from web")
tok, err = getTokenFromWeb(config, authURL)
} else {
fmt.Println("Trying to get token from prompt")
tok, err = getTokenFromPrompt(config, authURL)
}
if err == nil {
saveToken(cacheFile, tok)
}
}
return config.Client(ctx, tok)
}

// startWebServer starts a web server that listens on http://localhost:8080.
// The webserver waits for an oauth code in the three-legged auth flow.
func startWebServer() (codeCh chan string, err error) {
listener, err := net.Listen("tcp", "localhost:8090")
if err != nil {
return nil, err
}
codeCh = make(chan string)

go http.Serve(listener, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
code := r.FormValue("code")
codeCh <- code // send code to OAuth flow
listener.Close()
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintf(w, "Received code: %v\r\nYou can now safely close this browser window.", code)
}))

return codeCh, nil
}

// openURL opens a browser window to the specified location.
// This code originally appeared at:
//
// http://stackoverflow.com/questions/10377243/how-can-i-launch-a-process-that-is-not-a-file-in-go
func openURL(url string) error {
var err error
switch runtime.GOOS {
case "linux":
err = exec.Command("xdg-open", url).Start()
case "windows":
err = exec.Command("rundll32", "url.dll,FileProtocolHandler", "http://localhost:4001/").Start()
case "darwin":
err = exec.Command("open", url).Start()
default:
err = fmt.Errorf("Cannot open URL %s on this platform", url)
}
return err
}

// Exchange the authorization code for an access token
func exchangeToken(config *oauth2.Config, code string) (*oauth2.Token, error) {
tok, err := config.Exchange(oauth2.NoContext, code)
if err != nil {
log.Fatalf("Unable to retrieve token %v", err)
}
return tok, nil
}

// getTokenFromPrompt uses Config to request a Token and prompts the user
// to enter the token on the command line. It returns the retrieved Token.
func getTokenFromPrompt(config *oauth2.Config, authURL string) (*oauth2.Token, error) {
var code string
fmt.Printf("Go to the following link in your browser. After completing "+
"the authorization flow, enter the authorization code on the command "+
"line: \n%v\n", authURL)

if _, err := fmt.Scan(&code); err != nil {
log.Fatalf("Unable to read authorization code %v", err)
}
fmt.Println(authURL)
return exchangeToken(config, code)
}

// getTokenFromWeb uses Config to request a Token.
// It returns the retrieved Token.
func getTokenFromWeb(config *oauth2.Config, authURL string) (*oauth2.Token, error) {
codeCh, err := startWebServer()
if err != nil {
fmt.Printf("Unable to start a web server.")
return nil, err
}

err = openURL(authURL)
if err != nil {
log.Fatalf("Unable to open authorization URL in web server: %v", err)
} else {
fmt.Println("Your browser has been opened to an authorization URL.",
" This program will resume once authorization has been provided.\n")
fmt.Println(authURL)
}

// Wait for the web server to get the code.
code := <-codeCh
return exchangeToken(config, code)
}

// tokenCacheFile generates credential file path/filename.
// It returns the generated credential path/filename.
func tokenCacheFile() (string, error) {
usr, err := user.Current()
if err != nil {
return "", err
}
tokenCacheDir := filepath.Join(usr.HomeDir, ".credentials")
os.MkdirAll(tokenCacheDir, 0700)
return filepath.Join(tokenCacheDir,
url.QueryEscape("youtube-go.json")), err
}

// tokenFromFile retrieves a Token from a given file path.
// It returns the retrieved Token and any read error encountered.
func tokenFromFile(file string) (*oauth2.Token, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
}
t := &oauth2.Token{}
err = json.NewDecoder(f).Decode(t)
defer f.Close()
return t, err
}

// saveToken uses a file path to create a file and store the
// token in it.
func saveToken(file string, token *oauth2.Token) {
fmt.Println("trying to save token")
fmt.Printf("Saving credential file to: %s\n", file)
f, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
log.Fatalf("Unable to cache oauth token: %v", err)
}
defer f.Close()
json.NewEncoder(f).Encode(token)
}

0 comments on commit 48bbc7b

Please sign in to comment.