Пример #1
1
func NewGDrive() *GDrive {
	var err error

	usr, err := user.Current()
	if err != nil {
		return nil
	}

	tokenCacheDir := filepath.Join(usr.HomeDir, ".credentials")
	os.MkdirAll(tokenCacheDir, 0700)
	tokenCacheFile := filepath.Join(tokenCacheDir,
		url.QueryEscape("drive-go-quickstart.json"))

	b, err := ioutil.ReadFile("gdrive_client_secret.json")
	if err != nil {
		logError.Printf("Unable to read client secret file: %v", err)
		return nil
	}

	cfg, err := google.ConfigFromJSON(b, drive.DriveScope)
	if err != nil {
		logError.Printf("Unable to parse client secret file to config: %v", err)
		return nil
	}

	return &GDrive{
		clientSecret: "gdrive_client_secret.json",
		cacheFile:    tokenCacheFile,
		config:       cfg,
	}
}
Пример #2
0
// CreateGmailConfig returns OAuth 2.0 config.
func CreateGmailConfig() (*oauth2.Config, error) {
	b, err := readClient()
	if err != nil {
		return nil, err
	}
	return google.ConfigFromJSON(b, gmail.GmailComposeScope, gmail.GmailModifyScope)
}
Пример #3
0
func main() {
	ctx := context.Background()

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

	config, err := google.ConfigFromJSON(b, drive.DriveMetadataReadonlyScope)
	if err != nil {
		log.Fatalf("Unable to parse client secret file to config: %v", err)
	}
	client := getClient(ctx, config)

	srv, err := drive.New(client)
	if err != nil {
		log.Fatalf("Unable to retrieve drive Client %v", err)
	}

	r, err := srv.Files.List().PageSize(100).
		Fields("nextPageToken, files(id, name)").Do()
	if err != nil {
		log.Fatalf("Unable to retrieve files.", err)
	}

	fmt.Println("Files:")
	if len(r.Files) > 0 {
		for _, i := range r.Files {
			fmt.Printf("%s (%s)\n", i.Name, i.Id)
		}
	} else {
		fmt.Print("No files found.")
	}

}
Пример #4
0
// InstalledAppClient creates an oauth authenticated client for an installed
// app based on the credentials from the developer console from an
// account labeled 'Client ID for native application'.
// cacheFilePath is the path to where the token should be cached,
// configFilePath is the path to the config file downloaded from GCE and
// scopes is the list of desired oauth2 scopes.
// If transport is nil, the default transport will be used.
// If the cache file does not contain a token the oauth2 flow will be trigger.
func InstalledAppClient(cacheFilePath, configFilePath string, transport http.RoundTripper, scopes ...string) (*http.Client, error) {
	jsonKey, err := ioutil.ReadFile(configFilePath)
	if err != nil {
		return nil, err
	}

	config, err := google.ConfigFromJSON(jsonKey, scopes...)
	if err != nil {
		return nil, err
	}

	tokenSource, err := newCachingTokenSource(cacheFilePath, oauth2.NoContext, config)
	if err != nil {
		return nil, err
	}

	client := &http.Client{
		Transport: &oauth2.Transport{
			Source: tokenSource,
			Base:   transport,
		},
		Timeout: util.REQUEST_TIMEOUT,
	}

	return client, nil
}
Пример #5
0
func getFilesFromGDrive() {
	ctx := context.Background()

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

	config, err := google.ConfigFromJSON(b, drive.DriveMetadataReadonlyScope)
	if err != nil {
		log.Fatalf("Unable to parse client secret file to config: %v", err)
	}
	client := gdrive.GetClient(ctx, config)

	srv, err := drive.New(client)
	if err != nil {
		log.Fatalf("Unable to retrieve drive Client %v", err)
	}

	r, err := srv.Files.List().MaxResults(10).Do()
	if err != nil {
		log.Fatalf("Unable to retrieve files.", err)
	}

	fmt.Println("Files:")
	if len(r.Items) > 0 {
		for _, i := range r.Items {
			fmt.Printf("%s (%s)\n", i.Title, i.Id)
		}
	} else {
		fmt.Print("No files found.")
	}

}
Пример #6
0
// InitFromMetadataOrJSON must be called before any other login methods.
//
// InitFromMetadataOrJSON will eventually replace all instances of Init, at
// which point it will be renamed back to Init().
//
// The function first tries to load the cookie salt, client id, and client
// secret from GCE project level metadata. If that fails it looks for a
// "client_secret.json" file in the current directory to extract the client id
// and client secret from. If both of those fail then it returns an error.
//
// The authWhiteList is the space separated list of domains and email addresses
// that are allowed to log in. The authWhiteList will be overwritten from
// GCE instance level metadata if present.
func InitFromMetadataOrJSON(redirectURL, scopes string, authWhiteList string) error {
	cookieSalt, clientID, clientSecret := tryLoadingFromMetadata()
	if clientID == "" {
		b, err := ioutil.ReadFile("client_secret.json")
		if err != nil {
			return fmt.Errorf("Failed to read from metadata and from client_secret.json file: %s", err)
		}
		config, err := google.ConfigFromJSON(b)
		if err != nil {
			return fmt.Errorf("Failed to read from metadata and decode client_secret.json file: %s", err)
		}
		clientID = config.ClientID
		clientSecret = config.ClientSecret
	}
	secureCookie = securecookie.New([]byte(cookieSalt), nil)
	oauthConfig.ClientId = clientID
	oauthConfig.ClientSecret = clientSecret
	oauthConfig.RedirectURL = redirectURL
	oauthConfig.Scope = scopes
	// We allow for meta data to not be present.
	whiteList, err := metadata.Get(metadata.AUTH_WHITE_LIST)
	if err != nil {
		glog.Infof("Failed to retrieve auth whitelist from instance meta data: %s", err)
	} else {
		authWhiteList = whiteList
	}
	activeDomainWhiteList, activeEmailWhiteList = splitAuthWhiteList(authWhiteList)
	return nil
}
Пример #7
0
func uploadfile(filename string) {
	ctx := context.Background()

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

	config, err := google.ConfigFromJSON(b, drive.DriveScope)
	if err != nil {
		log.Fatalf("Unable to parse client secret file to config: %v", err)
	}
	client := getClient(ctx, config)
	svn, err := drive.New(client)
	fmt.Printf("Svn type is %T\n", svn)
	if err != nil {
		log.Fatalf("Unable to retrieve drive Client %v", err)
	}
	m, err := os.Open(filename)
	if err != nil {
		fmt.Printf("An error occurred: %v\n", err)

	}
	//f := &drive.File{Title: filename}
	fmt.Printf("\nHi\n")
	r, err := svn.Files.Insert(&drive.File{Title: filename}).Media(m).Do()
	if err != nil {
		fmt.Printf("An error occurred: %v\n", err)
	}
	defer m.Close()
	fmt.Printf("\nBye\n %T", r)

}
Пример #8
0
Файл: cal2.go Проект: elos/elos
func (c *Cal2Command) runGoogle(args []string) int {
	ctx, _ := context.WithTimeout(context.Background(), 1*time.Minute)
	config, err := google.ConfigFromJSON([]byte(clientSecret), calendar.CalendarScope)
	if err != nil {
		c.UI.Error(fmt.Sprintf("unable to parse client secrete file to config: %v", err))
		return failure
	}

	u, err := stringInput(c.UI, "Username:"******"unable to retrieve calendar client %v", err))
		return failure
	}
	events, err := srv.Events.List("primary").
		ShowDeleted(false).
		SingleEvents(true).
		TimeMin(time.Now().AddDate(0, -1, 0).Format(time.RFC3339)).
		OrderBy("startTime").Do()
	if err != nil {
		c.UI.Error(fmt.Sprintf("unable to retrieve user events: $v", err))
		return failure
	}

	n := 0
	recurring := map[string]bool{}
	for _, e := range events.Items {
		if e.RecurringEventId != "" {
			recurring[e.RecurringEventId] = true
			continue // don't ingest recurring instances
		}
		c.UI.Output(fmt.Sprintf("Processing: %v", e.Summary))
		_, err := ingestEvent(ctx, c.DBClient, c.UserID, e)
		if err != nil {
			c.UI.Error(err.Error())
			return failure
		}
		n++
	}
	for id := range recurring {
		e, err := srv.Events.Get("primary", id).Do()
		if err != nil {
			c.UI.Error(err.Error())
			return failure
		}
		_, err = ingestEvent(ctx, c.DBClient, c.UserID, e)
		if err != nil {
			c.UI.Error(err.Error())
			return failure
		}
	}
	return success
}
Пример #9
0
func (yt *YouTube) createConfig() error {
	b, err := ioutil.ReadFile(yt.configFilename)
	if err != nil {
		return err
	}

	yt.config, err = google.ConfigFromJSON(b, "https://www.googleapis.com/auth/youtube")
	return err
}
Пример #10
0
func form(c web.C, w http.ResponseWriter, r *http.Request) {

	b, err := ioutil.ReadFile("client_secret.json")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}

	config, err := google.ConfigFromJSON(b,
		drive.DriveMetadataReadonlyScope,
		drive.DriveFileScope,
		plus.UserinfoProfileScope)

	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}

	config.RedirectURL = redirectUrl

	ctx := context.Background()

	authToken := c.Env["access-token"].(oauth2.Token)

	plusClient := config.Client(ctx, &authToken)

	plusService, err := plus.New(plusClient)

	user, err := plusService.People.Get("me").Do()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}

	templateData := make(map[string]interface{})
	templateData["Image"] = user.Image.Url
	templateData["Name"] = user.DisplayName

	session, err := store.Get(r, "p2drive")
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}

	if flashes := session.Flashes("error"); len(flashes) > 0 {
		templateData["ErrorFlash"] = flashes[0]
	}

	if flashes := session.Flashes("success"); len(flashes) > 0 {
		templateData["SuccessFlash"] = flashes[0]
	}

	session.Save(r, w)

	if err := templates.Render(w, "projects-param2drive-form.html", templateData); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}

}
Пример #11
0
func GetConfig() *oauth2.Config {
	b, err := ioutil.ReadFile("client_id.json")
	if err != nil {
		log.Fatalf("Unable to read client secret file: %v", err)
	}
	config, err := google.ConfigFromJSON(b, gmail.GmailModifyScope)
	if err != nil {
		log.Fatalf("Unable to parse client secret file to config: %v", err)
	}
	return config
}
Пример #12
0
func GoogleAuthConfig(keyPath string, debug bool) *oauth2.Config {
	jsonKey, err := ioutil.ReadFile(keyPath)
	if err != nil {
		log.Fatal(err)
	}
	conf, _ := google.ConfigFromJSON(jsonKey, "profile")
	if debug {
		conf.RedirectURL = "http://localhost:8080/auth/google/callback"
	}
	return conf
}
Пример #13
0
func main() {

	client_secret_file := flag.String("client_secret_file", "", "Full Path of Client Secret File")
	gDrive_folder_id := flag.String("gDrive_folder_id", "", "Folder ID of Google Drive")
	backup_package_file := flag.String("backup_file", "", "Full Paht of backup file")

	flag.Parse()

	if *client_secret_file == "" || *gDrive_folder_id == "" || *backup_package_file == "" {
		fmt.Println("Please Input all arguments")
		os.Exit(-1)
	} else {

		ctx := context.Background()

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

		config, err := google.ConfigFromJSON(b, drive.DriveScope)
		if err != nil {
			log.Fatalf("Unable to parse client secret file to config: %v", err)
		}

		client := getClient(ctx, config)

		srv, err := drive.New(client)
		if err != nil {
			log.Fatalf("Unable to create Drive service: %v", err)
		}

		fmt.Println("Client Secret File -> ", *client_secret_file)
		fmt.Println("Google Driver Folder ID -> ", *gDrive_folder_id)
		fmt.Println("Backup File Name -> ", *backup_package_file)

		goFile, err := os.Open(*backup_package_file)
		uploadfiles := new(drive.File)
		p := &drive.ParentReference{Id: *gDrive_folder_id}
		uploadfiles.Parents = []*drive.ParentReference{p}

		currentTime := time.Now()

		uploadfiles.Title = fmt.Sprintf("%04d%02d%02d-%02d%02d.tar.bz2", currentTime.Year(), currentTime.Month(), currentTime.Day(), currentTime.Hour(), currentTime.Minute())

		r, err := srv.Files.Insert(uploadfiles).Media(goFile).Do()

		if err != nil {
			log.Fatalf("Unable to retrieve files.", err)
		}

		fmt.Println("\n\nDownload URL = ", r.DownloadUrl, " \n File ID = ", r.Id, "\n File Name = ", r.OriginalFilename)
	}
}
Пример #14
0
func initGoogleCalendarApi() {
	b, err := ioutil.ReadFile("/etc/sac/google_api_secret.json")
	if err != nil {
		Log.Fatalf("Unable to read client secret file: %v", err)
	}

	oauthConfig, err = google.ConfigFromJSON(b, calendar.CalendarReadonlyScope)
	if err != nil {
		Log.Fatalf("Unable to parse client secret file to config: %v", err)
	}
	Log.Info("Read Google API oauth config.")
}
Пример #15
0
func main() {
	ctx := context.Background()

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

	config, err := google.ConfigFromJSON(b, gmail.GmailReadonlyScope)
	if err != nil {
		log.Fatalf("Unable to parse client secret file to config: %v", err)
	}
	client := getClient(ctx, config)

	srv, err := gmail.New(client)
	if err != nil {
		log.Fatalf("Unable to retrieve gmail Client %v", err)
	}

	user := "******"
	r, err := srv.Users.Labels.List(user).Do()
	if err != nil {
		log.Fatalf("Unable to retrieve labels. %v", err)
	}
	if len(r.Labels) > 0 {
		fmt.Print("Labels:\n")
		for _, l := range r.Labels {
			fmt.Printf("- %s\n", l.Name)
		}
	} else {
		fmt.Print("No labels found.")
	}

	msgsCall := srv.Users.Messages.List(user)
	msgsCall.MaxResults(1)
	msgs, er := msgsCall.Do()
	if er != nil {
		log.Fatalf("Unable to retrieve messages. %v", er)
	}

	if len(msgs.Messages) > 0 {
		var wg sync.WaitGroup
		fmt.Print("Messages:\n")
		for _, m := range msgs.Messages {
			wg.Add(1)
			go readAndRespond(user, srv, m, &wg)
		}
		wg.Wait()
	} else {
		fmt.Print("No messages found.")
	}
}
Пример #16
0
func main() {
	ctx := context.Background()

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

	config, err := google.ConfigFromJSON(b, calendar.CalendarReadonlyScope)
	if err != nil {
		log.Fatalf("Unable to parse client secret file to config: %v", err)
	}
	client := getClient(ctx, config)

	srv, err := calendar.New(client)
	if err != nil {
		log.Fatalf("Unable to retrieve calendar Client %v", err)
	}

	//events, err := srv.Events.List("primary").ShowDeleted(false).SingleEvents(true).OrderBy("startTime").Do()
	now := time.Now()
	startDate := now //.AddDate(0, -1, 0)
	endDate := now.AddDate(0, 1, 0)
	fmt.Printf("Reading dates from %s to %s", startDate, now)
	events, err := srv.Events.List("primary").ShowDeleted(false).
		SingleEvents(true).TimeMin(startDate.Format(time.RFC3339)).TimeMax(endDate.Format(time.RFC3339)).OrderBy("startTime").Do()
	if err != nil {
		log.Fatalf("Unable to retrieve next ten of the user's events. %v", err)
	}

	fmt.Println("Upcoming events:")
	if len(events.Items) > 0 {
		for _, i := range events.Items {
			if i.Visibility != "private" && i.Visibility != "confidential" {
				// If the DateTime is an empty string the Event is an all-day Event.
				// So only Date is available.
				fmt.Printf("NEW ENTRY\n")
				js, _ := json.Marshal(i)
				fmt.Printf(string(js))
			}
		}
	} else {
		fmt.Printf("No upcoming events found.\n")
	}
	var stats Stats
	stats, err = dumpStats(events, endDate)
	if err != nil {
		log.Fatalf("Could not dump stats. %v", err)
	}
	js, _ := json.Marshal(stats)
	fmt.Printf(string(js))
}
// NewGoogleDrive reads the information from the supplied secret file and
// parses it into the config of a new googledrive object. It returns the newly
// created object.
func NewGoogleDrive(filepath string) (*GoogleDrive, error) {
	secret, err := ioutil.ReadFile(filepath)
	if err != nil {
		return nil, err
	}

	config, err := google.ConfigFromJSON(secret, drive.DriveScope)
	if err != nil {
		return nil, err
	}

	return &GoogleDrive{config: config}, nil
}
Пример #18
0
func Handler(w http.ResponseWriter, r *http.Request) {
	//	c := appengine.NewContext(r)
	b, err := ioutil.ReadFile("client_secret.json")
	if err != nil {
		panic(err)
	}
	config, err := google.ConfigFromJSON(b, drive.DriveReadonlyScope)
	authUrl := config.AuthCodeURL("state-token", oauth2.AccessTypeOnline)

	w.Header().Set("Location", authUrl)
	w.WriteHeader(http.StatusFound)
	return
}
Пример #19
0
func GetGCloudClientSource(credentialsFilePath string, tokenCacheFilePath string, tryWebUI bool) (ClientSource, error) {
	credentialsJson, err := ioutil.ReadFile(credentialsFilePath)
	if err != nil {
		return nil, fmt.Errorf("failed to read google cloud client-secret file: %v", err)
	}

	conf, err := google.ConfigFromJSON(credentialsJson,
		storage.ScopeFullControl,
		datastore.ScopeDatastore,
		datastore.ScopeUserEmail,
	)
	if err != nil {
		return nil, fmt.Errorf("invalid google cloud key json: %v", err)
	}

	revertToWebUI := func() (ClientSource, error) {
		if !tryWebUI {
			return nil, fmt.Errorf("OAuth2 token cache invalid.")
		}

		token, err := GetGCloudTokenViaWebUI(conf)
		if err != nil {
			return nil, fmt.Errorf("Failed to get valid gcloud token: %v", err)
		}
		if err := updateGCloudTokenCache(token, tokenCacheFilePath); err != nil {
			return nil, fmt.Errorf("Failed to update token cache: %v", err)
		}

		// FIXME: Token cache is not updated if token was refreshed by tokenRefresher from conf.Client
		return func(ctx context.Context) *http.Client { return conf.Client(ctx, token) }, nil
	}

	token, err := getGCloudTokenCached(tokenCacheFilePath)
	if err != nil {
		return revertToWebUI()
	}
	if !token.Valid() {
		// try refresh
		token, err = conf.TokenSource(oauth2.NoContext, token).Token()
		if err != nil {
			return revertToWebUI()
		}
		if updateGCloudTokenCache(token, tokenCacheFilePath); err != nil {
			return nil, fmt.Errorf("Failed to update token cache: %v", err)
		}
	}

	// FIXME: Token cache is not updated if token was refreshed by tokenRefresher from conf.Client
	return func(ctx context.Context) *http.Client { return conf.Client(ctx, token) }, nil
}
Пример #20
0
func main() {
	log.SetFlags(log.LstdFlags | log.Lshortfile)

	googleJsonKey, err := ioutil.ReadFile(GOOGLE_CLIENT_SECRET_FILE_PATH)
	if err != nil {
		log.Fatalln("unable to read file ", GOOGLE_CLIENT_SECRET_FILE_PATH,
			":", err)
	}
	facebookJsonKey, err := ioutil.ReadFile(FACEBOOK_CLIENT_SECRET_FILE_PATH)
	if err != nil {
		log.Fatalln("unable to read file ", FACEBOOK_CLIENT_SECRET_FILE_PATH,
			":", err)
	}

	// do I need more scopes?
	// https://developers.google.com/+/domains/authentication/scopes
	googleConfig, err := google.ConfigFromJSON(googleJsonKey)
	if err != nil {
		log.Fatalln("unable to get google provider config:", err)
	}
	facebookConfig := &genericConfig{}
	err = json.Unmarshal(facebookJsonKey, facebookConfig)
	if err != nil {
		log.Fatalln("unable to get facebook provider config:", err)
	}

	//I need "profile", "email", scopes. gplus and facebook provide these by
	//default.
	goth.UseProviders(
		gplus.New(googleConfig.ClientID, googleConfig.ClientSecret,
			AUTH_CALLBACK_URL),
		facebook.New(facebookConfig.Client_id, facebookConfig.Client_secret, AUTH_CALLBACK_URL),
	)

	chat = NewChat()
	router = pat.New()

	router.Get("/ws", WsHandler)
	router.Get("/oauth2callback", AuthCallbackHandler)
	router.Get("/auth/{provider}", BeginAuthHandler)
	router.Get("/", AuthChoiceHandler)
	// router.Add("GET", "/app", http.FileServer(http.Dir("app/")))
	// router.PathPrefix("/app").Handler(http.FileServer(http.Dir("app/")))
	http.Handle("/", router)
	http.Handle("/app/", http.StripPrefix("/app/",
		http.FileServer(http.Dir("app/"))))

	go http.ListenAndServeTLS(":8080", "cert.crt", "key.key", nil)
	http.ListenAndServe(":8000", http.HandlerFunc(redirectHandler))
}
Пример #21
0
func getNewService() (*gmail.Service, error) {
	b, err := ioutil.ReadFile("client_secret.json")
	if err != nil {
		log.Fatalf("Unable to read client secret file: %v", err)
	}

	config, err := google.ConfigFromJSON(b, gmail.MailGoogleComScope)
	if err != nil {
		log.Fatalf("Unable to parse client secret file to config: %v", err)
	}
	client := getClient(context.Background(), config)

	srv, err := gmail.New(client)
	return srv, err
}
Пример #22
0
func NewClient(cfg Config) (*http.Client, error) {
	ctx := context.Background()

	b, err := ioutil.ReadFile(cfg.SecretFile)
	if err != nil {
		return nil, fmt.Errorf("Unable to read client secret file: %v", err)
	}

	config, err := google.ConfigFromJSON(b, cfg.Scope)
	if err != nil {
		return nil, fmt.Errorf("Unable to parse client secret file to config: %v", err)
	}

	return getClient(ctx, config)
}
Пример #23
0
func genClient(filename string) *http.Client {
	ctx := context.Background()

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

	config, err := google.ConfigFromJSON(b, calendar.CalendarReadonlyScope)
	if err != nil {
		log.Fatalf("Unable to parse client secret file to config: %v", err)
	}

	return getClient(filename, ctx, config)
}
Пример #24
0
func getConfig() *oauth2.Config {
	clientIdFile, err := ioutil.ReadFile(clientIdFile)

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

	config, err := google.ConfigFromJSON(clientIdFile, drive.DriveScope, calendar.CalendarScope)

	if err != nil {
		log.Fatalf("Unable to parse client secret file to config: %v", err)
	}

	return config
}
Пример #25
0
func getGmailConfig() (*oauth2.Config, error) {

	b, err := ioutil.ReadFile("client_secret.json")
	if err != nil {
		return nil, err
	}

	config, err := google.ConfigFromJSON(b, gmail.GmailReadonlyScope)
	if err != nil {
		return nil, err
	}

	return config, nil

}
Пример #26
0
func main() {
	b, err := ioutil.ReadFile(CONFIG_DIR + "google_api_secret.json")
	if err != nil {
		Log.Fatalf("Unable to read client secret file: %v", err)
	}

	oauthConfig, err = google.ConfigFromJSON(b, calendar.CalendarReadonlyScope)

	if err != nil {
		Log.Fatalf("Unable to parse client secret file to config: %v", err)
	}

	http.HandleFunc("/register", registerHandler)
	http.HandleFunc("/oauth2callback", oauthCallbackHandler)
	Log.Fatal(http.ListenAndServeTLS(":2443", KEY_DIR+"cert.pem", KEY_DIR+"key.pem", nil))
}
Пример #27
0
func AppendLog(msg string) {
	ctx := context.Background()

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

	config, err := google.ConfigFromJSON(b, drive.DriveScope)
	if err != nil {
		log.Fatalf("Unable to parse client secret file to config: %v", err)
	}
	client := getClient(ctx, config)

	srv, err := drive.New(client)
	if err != nil {
		log.Fatalf("Unable to retrieve drive Client %v", err)
	}

	children, err := GetLog(srv, "0B14gQeVTanyZfnhwalk2OG9UVHVucHhLOE44ZHlySnpIM0FvdmYzMjNiOUZVVjEySzBzZk0")
	if err != nil {
		fmt.Println(err)
	}
	if children != nil {
		fileId := children.Id
		content, err := GetFile(srv, client, fileId)
		if err != nil {
			fmt.Println(err)
			return
		}
		content = content + "\n" + msg
		// remove redundant empty line
		reBlank := regexp.MustCompile(`([ \t]*\n){2,}`)
		output := reBlank.ReplaceAllLiteralString(content, "\n")
		UpdateFile(srv, fileId, output)
	} else {
		// create a new file
		f := &drive.File{Title: ThisWeek(), MimeType: "text/plain"}
		p := &drive.ParentReference{Id: "0B14gQeVTanyZfnhwalk2OG9UVHVucHhLOE44ZHlySnpIM0FvdmYzMjNiOUZVVjEySzBzZk0"}
		f.Parents = []*drive.ParentReference{p}
		_, err := srv.Files.Insert(f).Media(bytes.NewReader([]byte(msg))).Do()
		if err != nil {
			fmt.Printf("An error occurred: %v\n", err)
		}
	}
}
Пример #28
0
func getCalendarEvents() []event {
	ctx := context.Background()

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

	calendarConfig, err := google.ConfigFromJSON(b, calendar.CalendarReadonlyScope)
	if err != nil {
		log.Fatalf("Unable to parse client secret file to config: %v", err)
	}
	client := getClient(ctx, calendarConfig)

	srv, err := calendar.New(client)
	if err != nil {
		log.Fatalf("Unable to retrieve calendar Client %v", err)
	}

	t := time.Now().Format(time.RFC3339)
	events, err := srv.Events.List(config.FullCalendarID).ShowDeleted(false).SingleEvents(true).TimeMin(t).MaxResults(30).OrderBy("startTime").Do()
	if err != nil {
		log.Fatalf("Unable to retrieve next ten of the user's events. %v", err)
	}

	var compiledEvents []event
	for _, i := range events.Items {
		var dateStart, dateEnd string
		// If the DateTime is an empty string the Event is an all-day Event.
		// So only Date is available.
		if i.Start.DateTime != "" {
			startDate, _ := time.Parse(time.RFC3339, i.Start.DateTime)
			endDate, _ := time.Parse(time.RFC3339, i.End.DateTime)
			dateStart = startDate.Format("2006-01-02")
			dateEnd = endDate.Format("2006-01-02")
		} else {
			startDate, _ := time.Parse("2006-01-02", i.Start.Date)
			endDate, _ := time.Parse("2006-01-02", i.End.Date)
			dateStart = startDate.Format("2006-01-02")
			dateEnd = endDate.Format("2006-01-02")
		}
		compiledEvents = append(compiledEvents, event{Date: dateStart, EndDate: dateEnd, Event: i})
	}
	return compiledEvents
}
Пример #29
0
func main() {
	ctx := context.Background()

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

	config, err := google.ConfigFromJSON(b, calendar.CalendarScope)
	if err != nil {
		log.Fatalf("Unable to parse client secret file to config: %v", err)
	}
	client := getClient(ctx, config)

	srv, err := calendar.New(client)
	if err != nil {
		log.Fatalf("Unable to retrieve calendar Client %v", err)
	}

	args := os.Args[1:]
	if len(args) != 1 {
		log.Fatalf("Must provide a day you are working from home")
	}

	dateString := getDateString()

	event := &calendar.Event{
		Summary:     nameFromEnv() + " WFH",
		Location:    "Home",
		Description: "Working from home",
		Start: &calendar.EventDateTime{
			Date: *dateString,
		},
		End: &calendar.EventDateTime{
			Date: *dateString,
		},
	}

	calendarId := calendarIdFromEnv()
	event, err = srv.Events.Insert(calendarId, event).Do()
	if err != nil {
		log.Fatalf("Unable to create event. %v\n", err)
	}
	fmt.Printf("Event created: %s\n", event.HtmlLink)
}
Пример #30
0
func newReportsServiceWithSecret(bytes []byte) (*ar.Service, error) {
	config, err := google.ConfigFromJSON(bytes,
		ar.AdminReportsAuditReadonlyScope)
	if err != nil {
		log.Fatalf("Unable to parse client secret file to config: %v", err)
		return nil, err
	}

	ctx := context.Background()
	client := getClient(ctx, config)
	srv, err := ar.New(client)
	if err != nil {
		log.Fatalf("Unable to retrieve reports client %v", err)
		return nil, err
	}

	return srv, err
}