Esempio n. 1
0
func main() {

	configFile, err := ioutil.ReadFile("config.json")
	if err != nil {
		panic("Error opening config file: " + err.Error())
	}

	var c config
	err = json.Unmarshal(configFile, &c)
	if err != nil {
		panic(err)
	}

	var db *dropbox.Dropbox
	// 1. Create a new dropbox object.
	db = dropbox.NewDropbox()

	// 2. Provide your clientid and clientsecret (see prerequisite).
	db.SetAppInfo(c.Clientid, c.Clientsecret)

	// 3. Provide the user token.
	db.SetAccessToken(c.Token)
	fmt.Println(c.DropboxPath)
	err = db.DownloadToFile(c.DropboxPath, c.Destination, "")
	if err != nil {
		panic(err)
	}
}
Esempio n. 2
0
// New creates a client to connect to Dropbox.
func New(key, secret, token string) (db *Dropbox, err error) {
	if key == "" {
		err = errors.New("empty key")
		return
	}
	if secret == "" {
		err = errors.New("empty secret")
		return
	}
	if token == "" {
		err = errors.New("empty token")
		return
	}

	var (
		client *dropbox.Dropbox
	)

	client = dropbox.NewDropbox()
	client.SetAppInfo(key, secret)
	client.SetAccessToken(token)

	db = &Dropbox{
		client: client,
		cwd:    "/",
	}

	return
}
Esempio n. 3
0
func main() {

	err := rpio.Open()
	if err != nil {
		fmt.Println("rpio.Open()")
		fmt.Println(err)
	}
	// Unmap gpio memory when done
	defer rpio.Close()

	toggleLight(9)

	var db *dropbox.Dropbox

	db = dropbox.NewDropbox()

	db.SetAppInfo(clientid, clientsecret)
	db.SetAccessToken(token)

	toggleLight(10)

	shoot(db)

	toggleLight(11)
}
Esempio n. 4
0
func dropboxClient(context context.Context, accessToken string) *dropbox.Dropbox {
	db := dropbox.NewDropbox()
	db.SetContext(context)
	db.SetAppInfo(clientId, clientSecret)
	db.SetAccessToken(accessToken)

	return db
}
Esempio n. 5
0
func handler(w http.ResponseWriter, r *http.Request) {
	var err error
	var db *dropbox.Dropbox
	var input io.ReadCloser
	var length int64
	var ok bool
	var cachedItem interface{}
	var s string

	if r.URL.Path[1:] == "favicon.ico" {
		return
	}

	cachedItem, ok = Lru.Get(r.URL.Path[1:])

	if ok {
		item := cachedItem.(cacheItem)
		s = item.Value
		length = item.Length
	} else {

		var clientid, clientsecret string
		var token string

		clientid = os.Getenv("CLIENTID")
		clientsecret = os.Getenv("CLIENTSECRET")
		token = os.Getenv("TOKEN")

		// 1. Create a new dropbox object.
		db = dropbox.NewDropbox()

		// 2. Provide your clientid and clientsecret (see prerequisite).
		db.SetAppInfo(clientid, clientsecret)

		// 3. Provide the user token.
		db.SetAccessToken(token)

		// 4. Send your commands.
		// In this example, you will create a new folder named "demo".
		if input, length, _, err = db.Thumbnails("/"+r.URL.Path[2:], "jpeg", r.URL.Path[1:2]); err != nil {
			fmt.Printf("Error: %s Url: %s Size: \n", err, r.URL.Path[2:], r.URL.Path[1:2])
		} else {
			//fmt.Printf("Error %s\n", input)

			buf := new(bytes.Buffer)
			buf.ReadFrom(input)
			s = buf.String()
			Lru.Add(r.URL.Path[1:], cacheItem{Value: s, Length: length})

		}
	}

	w.Header().Set("Content-Length", strconv.FormatInt(length, 10))
	fmt.Fprintf(w, "%s", s)

}
Esempio n. 6
0
// NewDropboxBackend returns a new Dropbox backend to read JSON from.
// You must provide an accessToken, which you can get by creating an app
// in the Dropbox API and then pressing Generate.
// Access tokens do not expire.
// If a storageLocation isn't provided, the default location is
//   /Apps/Reporter-App/
func NewDropboxBackend(accessToken, storageLocation string) (*DropboxBackend, error) {
	if accessToken == "" {
		return nil, errors.New("No access token provided for Dropbox backend")
	}
	db := dropbox.NewDropbox()
	db.SetAccessToken(accessToken)
	if storageLocation == "" {
		storageLocation = "/Apps/Reporter-App/"
	}
	return &DropboxBackend{db, storageLocation}, nil
}
Esempio n. 7
0
func WriteFile(config *DropboxConfig, file string, content string) error {
	var db *dropbox.Dropbox

	db = dropbox.NewDropbox()
	db.SetAppInfo(config.AppKey, config.AppSecret)
	db.SetAccessToken(config.Token)

	in := ioutil.NopCloser(bytes.NewBufferString(content))
	_, err := db.UploadByChunk(in, 1024, file, true, "")
	return err
}
Esempio n. 8
0
// Makes a new dropbox from the config
func newDropbox(name string) (*dropbox.Dropbox, error) {
	db := dropbox.NewDropbox()

	appKey := fs.ConfigFileGet(name, "app_key")
	if appKey == "" {
		appKey = rcloneAppKey
	}
	appSecret := fs.ConfigFileGet(name, "app_secret")
	if appSecret == "" {
		appSecret = fs.MustReveal(rcloneEncryptedAppSecret)
	}

	err := db.SetAppInfo(appKey, appSecret)
	return db, err
}
Esempio n. 9
0
// Makes a new dropbox from the config
func newDropbox(name string) *dropbox.Dropbox {
	db := dropbox.NewDropbox()

	appKey := fs.ConfigFile.MustValue(name, "app_key")
	if appKey == "" {
		appKey = rcloneAppKey
	}
	appSecret := fs.ConfigFile.MustValue(name, "app_secret")
	if appSecret == "" {
		appSecret = rcloneAppSecret
	}

	db.SetAppInfo(appKey, appSecret)

	return db
}
Esempio n. 10
0
func uploadFile(file multipart.File) string {
	clientid := os.Getenv("DROPBOX_KEY")
	clientsecret := os.Getenv("DROPBOX_TOKEN")
	token := os.Getenv("DROPBOX_ACCESS_TOKEN")

	DB := dropbox.NewDropbox()
	DB.SetAppInfo(clientid, clientsecret)
	DB.SetAccessToken(token)

	filename := fmt.Sprintf("%s.png", strconv.FormatInt(rand.Int63(), 32))
	filepath := fmt.Sprintf("/Public/Screenshots/%s", filename)

	var tmpstr []byte
	length, _ := file.Read(tmpstr)
	DB.FilesPut(file, int64(length), filepath, true, "")

	account, _ := DB.GetAccountInfo()
	uid := strconv.FormatInt(int64(account.UID), 10)

	return fmt.Sprintf("https://dl.dropbox.com/u/%s/Screenshots/%s", uid, filename)
}
Esempio n. 11
0
func ReadFile(config *DropboxConfig, file string) (string, error) {

	var err error
	var db *dropbox.Dropbox
	var s string

	db = dropbox.NewDropbox()
	db.SetAppInfo(config.AppKey, config.AppSecret)
	db.SetAccessToken(config.Token)

	rd, _, err := db.Download(file, "", 0)
	if err != nil {
		return s, err
	}

	buf := new(bytes.Buffer)
	buf.ReadFrom(rd)
	s = buf.String()

	return s, nil
}
Esempio n. 12
0
func build(config map[string]string) (gofile.Driver, error) {

	var clientID, clientSecret, token string
	var ok bool

	if clientID, ok = config["client_id"]; !ok {
		return nil, fmt.Errorf("godropbox: Client ID not specified")
	}

	if clientSecret, ok = config["client_secret"]; !ok {
		return nil, fmt.Errorf("godropbox: Client Secret not specified")
	}

	if token, ok = config["token"]; !ok {
		return nil, fmt.Errorf("godropbox: Token not specified")
	}

	db := dropbox.NewDropbox()
	db.SetAppInfo(clientID, clientSecret)
	db.SetAccessToken(token)

	return dropboxDriver{db: db}, nil
}
Esempio n. 13
0
func main() {

	//Set our environment
	martini.Env = martini.Prod

	//Load our config information and start our web server.
	config := LoadConfiguration("./config.json")
	auth, encrypt := securecookie.GenerateRandomKey(64), securecookie.GenerateRandomKey(32)
	store := sessions.NewCookieStore(auth, encrypt)
	server := martini.New()
	db := dropbox.NewDropbox()
	router := martini.NewRouter()
	r := render.New()
	oAuthConf := &oauth2.Config{
		ClientID:     config.Dropbox.AppKey,
		ClientSecret: config.Dropbox.AppSecret,
		RedirectURL:  config.Server.HostName + "/auth/response",
		Endpoint: oauth2.Endpoint{
			AuthURL:  "https://www.dropbox.com/1/oauth2/authorize",
			TokenURL: "https://api.dropbox.com/1/oauth2/token",
		},
	}

	//Configure our Dropbox access
	db.SetAppInfo(config.Dropbox.AppKey, config.Dropbox.AppSecret)

	//Set our public web root and our session storage.
	server.Use(martini.Logger())
	server.Use(martini.Recovery())
	server.Use(sessions.Sessions("ynawb", store))
	server.Use(martini.Static(config.Server.WebRoot))

	//Configure the Martini router
	server.MapTo(router, (*martini.Routes)(nil))
	server.Action(router.Handle)

	//Redirects the users over to Dropbox for authentication
	router.Get("/auth", func(res http.ResponseWriter, req *http.Request) {

		/* So, this is a weird edge case. Because we're serving most
		 * of our app via the static files handler and the HTTPS redirect
		 * in the martinin-contrib/secure package only works for defined routes,
		 * any of our main files own't get redirected. Because of that, we're
		 * going to redirect people when they go to auth their Dropbox
		 * accounts. This should fix the issue. */
		if strings.ToLower(req.URL.Scheme) == "http" && strings.ToLower(req.URL.Host) != "localhost" {

			url := req.URL
			url.Scheme = "https"
			url.Host = req.Host

			http.Redirect(res, req, url.String(), http.StatusFound)

		} else {

			// Redirect user to consent page to ask for permission
			// for the scopes specified above.
			url := oAuthConf.AuthCodeURL("state")

			http.Redirect(res, req, url, http.StatusFound)
		}

	})

	/* Accepts the response after authorizing with Dropbox. */
	router.Get("/auth/response", func(res http.ResponseWriter, req *http.Request) {

		//If they cancelled their login, redirect them back to the home page.
		if authError := req.FormValue("error"); authError != "" {
			http.Redirect(res, req, config.Server.HostName, http.StatusFound)
			return
		}

		code := req.FormValue("code")

		//If we didn't somehow get an authentication code, take them back home.
		if code == "" {
			http.Redirect(res, req, config.Server.HostName, http.StatusFound)
			return
		}

		fmt.Printf("Exchanging code '%v'\n", code)

		//token, err := oAuthConf.Exchange(nil, code)
		token, err := oAuthConf.Exchange(oauth2.NoContext, code)

		//If our token exchange doesn't work, throw an error and go to our error page.
		if err != nil {
			handleError(err, res, req, config)
			return
		}

		session, err := store.Get(req, "ynawb")

		//If we can't get our session store, throw an error and go to our error page.
		if err != nil {
			handleError(err, res, req, config)
			return
		}

		//Set our dropbox session token and save.
		session.Options.HttpOnly = true

		//Sets the max age of our cookie. Defaults is fifteen minutes.
		session.Options.MaxAge = config.Server.SessionMaxAge

		//Set our token
		session.Values["token"] = token.AccessToken

		//Save our token and its settings
		session.Save(req, res)

		url := config.Server.HostName + "/budgets"

		//Redirect them to a page where they can select their needed budget
		http.Redirect(res, req, url, http.StatusFound)
	})

	/* Retrieves a list of the users YNAB budgets and devices from
	 * their Dropbox account. Redirects them back to the home page if
	 * their cookie has expired. */
	router.Get("/api/budgets", func(res http.ResponseWriter, req *http.Request) {

		session, _ := store.Get(req, "ynawb")
		cookie := session.Values["token"]

		if token, ok := cookie.(string); ok {

			db.SetAccessToken(token)

			if file, err := loadDropboxFile("/.ynabSettings.yroot", db); err != nil && err.Error() != "EOF" {

				handleError(err, res, req, config)

			} else {

				settings := LoadYNABSettings(file)
				results := make(map[string][]map[string]string)

				for _, setting := range settings.RelativeKnownBudgets {

					bm, err := loadDropboxFile(setting+"/Budget.ymeta", db)

					if err != nil && err.Error() != "EOF" {
						handleError(err, res, req, config)
						return
					}

					metadata := LoadYNABBudgetMetadata(bm)
					devicesPath := setting + "/" + metadata.RelativeDataFolderName + "/devices"
					entries, err := db.Search(devicesPath, ".ydevice", 0, false)

					if err != nil && err.Error() != "EOF" {
						handleError(err, res, req, config)
						return
					}

					devicesCollection := make([]map[string]string, len(entries))

					for j, entry := range entries {

						dev, err := loadDropboxFile(entry.Path, db)

						if err != nil && err.Error() != "EOF" {
							handleError(err, res, req, config)
						}

						device := LoadYNABDevice(dev)

						devicesCollection[j] = map[string]string{
							"name": device.FriendlyName,
							"guid": device.DeviceGUID,
						}

					}

					results[setting] = devicesCollection

				}

				res.Header().Set("Content-Type", "application/json")

				r.JSON(res, http.StatusOK, results)
			}

		} else {

			http.Redirect(res, req, config.Server.HostName, http.StatusUnauthorized)
			return

		}

	})

	/* Retrieves the users YNAB budget data from their Dropbox account.
	 * Redirects them back to the home page if their cookie has expired. */
	router.Get("/api/budgetdata/:budget/:path", func(res http.ResponseWriter, req *http.Request, params martini.Params) string {

		//Do some checks on our parameters
		if params["budget"] == "" || params["budget"] == "undefined" {
			return ""
		}

		if params["path"] == "" || params["path"] == "undefined" {
			return ""
		}

		session, _ := store.Get(req, "ynawb")
		cookie := session.Values["token"]

		if token, ok := cookie.(string); ok {

			db.SetAccessToken(token)

			s, err := loadDropboxFile(".ynabSettings.yroot", db)

			if err != nil && err.Error() != "EOF" {
				handleError(err, res, req, config)
			}

			settings := LoadYNABSettings(s)
			relativePath := ""

			for _, p := range settings.RelativeKnownBudgets {

				if strings.Contains(p, params["budget"]) {
					relativePath = p
				}

			}

			path := "/" + relativePath + "/"

			m, err := loadDropboxFile(path+"Budget.ymeta", db)

			if err != nil && err.Error() != "EOF" {
				handleError(err, res, req, config)
			}

			metadata := LoadYNABBudgetMetadata(m)

			budget := path + metadata.RelativeDataFolderName + "/" + params["path"] + "/Budget.yfull"

			b, err := loadDropboxFile(budget, db)

			if err != nil && err.Error() != "EOF" {
				handleError(err, res, req, config)
			}

			res.Header().Set("Content-Type", "application/json")

			return string(b)

		} else {

			http.Redirect(res, req, config.Server.HostName, http.StatusUnauthorized)

			return ""

		}

	})

	// HTTP
	go func() {

		if err := http.ListenAndServe(":"+strconv.Itoa(config.Server.Port), server); err != nil {
			log.Fatal(err)
		} else {
			fmt.Printf("Listing on port :%v\n", config.Server.Port)
		}
	}()

	server.RunOnAddr(":" + strconv.Itoa(config.Server.PortSSL))
	server.Run()

}
Esempio n. 14
0
func handleOriginalFile(w http.ResponseWriter, r *http.Request) {
	var err error
	var db *dropbox.Dropbox
	//        var input io.ReadCloser
	var length int64
	var ok bool
	var cachedItem interface{}
	var s string

	if r.URL.Path[1:] == "favicon.ico" {
		return
	}

	cachedItem, ok = Lru.Get(r.URL.Path[5:])

	if ok {
		item := cachedItem.(cacheItem)
		s = item.Value
		length = item.Length
	} else {
		var clientid, clientsecret string
		var token, rev string

		clientid = os.Getenv("CLIENTID")
		clientsecret = os.Getenv("CLIENTSECRET")
		token = os.Getenv("TOKEN")

		// 1. Create a new dropbox object.
		db = dropbox.NewDropbox()

		// 2. Provide your clientid and clientsecret (see prerequisite).
		db.SetAppInfo(clientid, clientsecret)

		// 3. Provide the user token.
		db.SetAccessToken(token)

		rev = ""

		//h := md5.New()
		//io.WriteString(h, r.URL.Path[5:])
		//b := h.Sum(nil)
		str := strings.Replace(r.URL.Path[5:], "/", "-", -1)

		err = db.DownloadToFile("/"+r.URL.Path[5:], "/tmp/"+str, rev)
		if err != nil {
			fmt.Printf("123 Error: %s Url: %s Size: \n", err, r.URL.Path[5:], r.URL.Path[1:2])
		} else {
			dat, err := ioutil.ReadFile("/tmp/" + str)
			if err != nil {

			} else {
				f, err := os.Open("/tmp/" + str)
				if err != nil {

				}
				fi, err := f.Stat()
				if err != nil {
					// Could not obtain stat, handle error
				}

				length = fi.Size()
				s = string(dat[:])
				//				w.Header().Set("Content-Length", strconv.FormatInt(fi.Size(), 10))
				fmt.Fprintf(w, "%s", dat)
				Lru.Add(r.URL.Path[5:], cacheItem{Value: s, Length: length})
			}
		}
	}
	w.Header().Set("Content-Length", strconv.FormatInt(length, 10))
	fmt.Fprintf(w, "%s", s)
}
Esempio n. 15
0
func main() {
	flag.Parse()
	setFromEnv()

	if *appID == "" || *appSecret == "" {
		fatalf("Application ID and Secret is required.")
	}

	dbox := dropbox.NewDropbox()
	dbox.SetAppInfo(*appID, *appSecret)

	if *appToken == "" {
		if err := dbox.Auth(); err != nil {
			fmt.Println(err)
			return
		}
	} else {
		dbox.SetAccessToken(*appToken)
	}

	if *fileName == "" && *inputFile == "" {
		fmt.Println("Filename is required.")
		os.Exit(1)
		return
	} else if *fileName == "" {
		*fileName = *inputFile
	}

	if *doMkdir && *dirName != "" {
		if _, err := dbox.CreateFolder(*dirName); err != nil && strings.Contains(err.Error(), "already exists") {
			fmt.Printf("Folder %s already exists\n", *dirName)
		} else if err != nil {
			fatalf("Error creating folder %s: %s", *dirName, err)
		}
		fmt.Printf("Folder %s successfully created\n", *dirName)
	}

	fname := strings.Trim(strings.Join([]string{*dirName, *fileName}, "/"), "/")
	fmt.Printf("Uploading file %s => %s\n", *inputFile, fname)

	var input io.ReadCloser
	if *inputFile != "" {
		// _, err = dbox.UploadFile(*inputFile, fname, true, "")
		info, err := os.Stat(*inputFile)
		if err != nil {
			fatalf("%v", err)
		}

		file, err := os.Open(*inputFile)
		if err != nil {
			fatalf("Error opening file %q: %v", *inputFile, err)
		}
		defer file.Close()
		bar := pb.StartNew(int(info.Size()))
		bar.Units = pb.U_BYTES

		input = ioutil.NopCloser(&ioprogress.Reader{
			Reader: file,
			Size:   info.Size(),
			DrawFunc: func(progress int64, total int64) error {
				bar.Set(int(progress))
				if progress >= total {
					bar.FinishPrint("Done")
				}
				return nil
			},
		})
	} else {
		input = os.Stdin
	}

	_, err := dbox.UploadByChunk(input, *chunkSize*1024, fname, false, "")
	if err != nil {
		fatalf("Error uploading file %s: %v", fname, err)
	}

	fmt.Printf("File %s successfully created\n", fname)
}
func main() {
	var err error

	do_not_include = []string{}
	// Ignore all .txt files
	do_not_include = append(do_not_include, ".txt")

	config = Config{}
	cache_instance = cache.New(12*time.Hour, 15*time.Minute)
	db = dropbox.NewDropbox()

	data, read_err := ioutil.ReadFile("config.yml")
	if read_err != nil {
		log.Fatal(read_err)
	}

	yaml_err := yaml.Unmarshal(data, &config)
	if yaml_err != nil {
		log.Fatal("error: %v", yaml_err)
	}
	fmt.Printf("--- config_file dump:\n%s\n\n", data)
	fmt.Printf("--- config dump:\n%s\n\n", config)

	db.SetAppInfo(config.Api_key, config.Api_secret)
	if len(config.Client_token) >= 1 {
		db.SetAccessToken(config.Client_token)
	} else {
		if err = db.Auth(); err != nil {
			fmt.Println(err)
			return
		}
		config.Client_token = db.AccessToken()
		db.SetAccessToken(config.Client_token)
		d, marshal_err := yaml.Marshal(&config)
		if marshal_err != nil {
			log.Fatal("error: %v", marshal_err)
		}
		ioutil.WriteFile("config.yml", []byte(d), 0644)
	}

	// root_paths := get_directories(cache, db, "")
	// fmt.Printf("--- paths dump:\n%s\n\n", root_paths)

	// nightly_files := get_files(cache, db, "ARMv7")
	// fmt.Printf("--- paths dump:\n%s\n\n", nightly_files)

	// setup server to link
	api := rest.NewApi()
	statusMw := &rest.StatusMiddleware{}
	api.Use(statusMw)
	api.Use(rest.DefaultDevStack...)
	router, err := rest.MakeRouter(
		// Status endpoint for monitoring
		rest.Get("/status", func(w rest.ResponseWriter, r *rest.Request) {
			w.WriteJson(statusMw.GetStatus())
		}),
		// The JSON endpoints for data about the next endpoint
		rest.Get("/", list_arches),
		rest.Get("/#arch", list_softwares),
		rest.Get("/#arch/#software", list_versions),
		rest.Get("/#arch/#software/#version", list_targets),
		// Endpoint that redirects the client
		rest.Get("/#arch/#software/#version/#target", link_target),
	)
	if err != nil {
		log.Fatal(err)
	}
	api.SetApp(router)
	s := []string{}
	s = append(s, config.Server_listen)
	s = append(s, config.Server_port)
	server_listen := strings.Join(s, ":")
	http.Handle(strings.Join([]string{config.Context_root, "/"}, ""), http.StripPrefix(config.Context_root, api.MakeHandler()))
	log.Fatal(http.ListenAndServe(server_listen, nil))
}