예제 #1
0
func SetupDatabase(wf *web.WebFace, db *database.StatTrackerDB) {
	webBuf := bytes.NewBufferString("Starting Server")
	fileCounter := 0
	numFiles := 0

	outBuf := io.MultiWriter(webBuf, os.Stdout)

	fmt.Fprintf(outBuf, "Hosting on %s \n", *addr)

	wf.RedirectHandler = func(rw http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(rw, "Files Processed: %4d/%d \n", fileCounter, numFiles)
		fmt.Fprint(rw, webBuf)
	}

	fmt.Fprintln(outBuf, "Fetching File List")

	cPage := make(chan int)

	var driveFilelist []*drive.File
	go func() {
		var errDrv error
		driveFilelist, errDrv = google.AllFiles("mimeType = 'application/vnd.google-apps.document'", cPage)
		if errDrv != nil {
			log.Fatalln("File List Error:", errDrv)
		}
	}()

	for i := <-cPage; i != -1; i = <-cPage {
		fmt.Fprintf(outBuf, "Getting Page: %d \n", i)
	}

	// Handle per file
	docStatList := []*stat.DocStat{}
	numFiles = len(driveFilelist)
	for ifile, file := range driveFilelist {
		fileCounter = ifile

		db.WriteFile(file)
		dStat := FilePullCalc(file, db)

		db.WriteFileStats(dStat)

		fmt.Fprintf(outBuf, "Stats File Generated: %s... %s %s\n", file.Id[:6], dStat.LastMod[:10], file.Title)
		docStatList = append(docStatList, dStat)
	}

	// Generate Daily Stat
	dates := stat.CreateDailyUserStat(docStatList)

	// Slower but good test (and get sorting from DB)
	for _, v := range dates {
		db.WriteDailyUserStats(&v)
	}

	wf.RedirectHandler = nil
}
예제 #2
0
func tokenFromWeb(ctx context.Context, config *oauth2.Config, wf *web.WebFace) *oauth2.Token {
	ch := make(chan string)
	randState := fmt.Sprintf("st%d", time.Now().UnixNano())

	config.RedirectURL = "http://" + wf.Addr + "/login"

	{ // Auto
		authURL := config.AuthCodeURL(randState)

		wf.RedirectHandler = func(rw http.ResponseWriter, req *http.Request) {

			if req.URL.Path == "/favicon.ico" {
				http.Error(rw, "", 404)
				return
			}

			if !strings.HasPrefix(req.URL.Path, "/login") {
				log.Println("Redirect ", req.URL.Path, strings.HasPrefix(req.URL.Path, "/login"))
				http.Redirect(rw, req, authURL, 302)
				return
			}

			if req.FormValue("state") != randState {
				log.Printf("State doesn't match: req = %#v", req)
				http.Error(rw, "", 500)
				return
			}

			if code := req.FormValue("code"); code != "" {
				wf.RedirectHandler = nil
				http.Redirect(rw, req, "http://"+wf.Addr+"/", 302)
				ch <- code
				return
			}
		}

		log.Println("Awaiting Authorize Token")
	}

	code := <-ch
	log.Printf("Got code: %s", code)

	token, err := config.Exchange(ctx, code)
	if err != nil {
		log.Fatalf("Token exchange error: %v", err)
	}
	return token
}