dropbox

package
v0.10.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 21, 2023 License: AGPL-3.0-or-later, BSD-2-Clause Imports: 21 Imported by: 0

README

dropbox

Go client library for the Dropbox core and Datastore API with support for uploading and downloading encrypted files.

Support of the Datastore API should be considered as a beta version.

Prerequisite

To use this library, you must have a valid client ID (app key) and client secret (app secret) provided by Dropbox.
To register a new client application, please visit https://www.dropbox.com/developers/apps/create

Installation

This library depends on the oauth2 package, it can be installed with the go get command:

$ go get golang.org/x/oauth2

This package can be installed with the go get command:

$ go get github.com/stacktic/dropbox

Examples

This simple 4-step example will show you how to create a folder:

package main

import (
    "dropbox"
    "fmt"
)

func main() {
    var err error
    var db *dropbox.Dropbox

    var clientid, clientsecret string
    var token string

    clientid = "xxxxx"
    clientsecret = "yyyyy"
    token = "zzzz"

    // 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".
    folder := "demo"
    if _, err = db.CreateFolder(folder); err != nil {
        fmt.Printf("Error creating folder %s: %s\n", folder, err)
    } else {
        fmt.Printf("Folder %s successfully created\n", folder)
    }
}

If you do not know the user token, you can replace step 3 by a call to the Auth method:

    // This method will ask the user to visit an URL and paste the generated code.
    if err = db.Auth(); err != nil {
        fmt.Println(err)
        return
    }
    // You can now retrieve the token if you want.
    token = db.AccessToken()

If you want a more complete example, please check the following project: https://github.com/stacktic/dbox.

Documentation

API documentation can be found here: http://godoc.org/github.com/stacktic/dropbox.

Documentation

Overview

Package dropbox implements the Dropbox core and datastore API.

Index

Constants

View Source
const (
	// PollMinTimeout is the minimum timeout for longpoll.
	PollMinTimeout = 30
	// PollMaxTimeout is the maximum timeout for longpoll.
	PollMaxTimeout = 480
	// DefaultChunkSize is the maximum size of a file sendable using files_put.
	DefaultChunkSize = 4 * 1024 * 1024
	// MaxPutFileSize is the maximum size of a file sendable using files_put.
	MaxPutFileSize = 150 * 1024 * 1024
	// MetadataLimitMax is the maximum number of entries returned by metadata.
	MetadataLimitMax = 25000
	// MetadataLimitDefault is the default number of entries returned by metadata.
	MetadataLimitDefault = 10000
	// RevisionsLimitMax is the maximum number of revisions returned by revisions.
	RevisionsLimitMax = 1000
	// RevisionsLimitDefault is the default number of revisions returned by revisions.
	RevisionsLimitDefault = 10
	// SearchLimitMax is the maximum number of entries returned by search.
	SearchLimitMax = 1000
	// SearchLimitDefault is the default number of entries returned by search.
	SearchLimitDefault = 1000
	// DateFormat is the format to use when decoding a time.
	DateFormat = time.RFC1123Z
)

Variables

View Source
var ErrNotAuth = errors.New("authentication required")

ErrNotAuth is the error returned when the OAuth token is not provided

Functions

func GenerateKey

func GenerateKey(length int) ([]byte, error)

GenerateKey generates a key by reading length bytes from /dev/random

func NewAESCrypterReader

func NewAESCrypterReader(key []byte, input io.Reader, size int) (io.ReadCloser, int, error)

NewAESCrypterReader creates and returns a new io.ReadCloser to encrypt the given io.Reader containing size bytes with the given AES key. The AES key should be either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.

func NewAESDecrypterReader

func NewAESDecrypterReader(key []byte, input io.Reader, size int) (io.ReadCloser, error)

NewAESDecrypterReader creates and returns a new io.ReadCloser to decrypt the given io.Reader containing size bytes with the given AES key. The AES key should be either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.

Types

type Account

type Account struct {
	ReferralLink string `json:"referral_link,omitempty"` // URL for referral.
	DisplayName  string `json:"display_name,omitempty"`  // User name.
	UID          int    `json:"uid,omitempty"`           // User account ID.
	Country      string `json:"country,omitempty"`       // Country ISO code.
	QuotaInfo    struct {
		Shared int64 `json:"shared,omitempty"` // Quota for shared files.
		Quota  int64 `json:"quota,omitempty"`  // Quota in bytes.
		Normal int64 `json:"normal,omitempty"` // Quota for non-shared files.
	} `json:"quota_info"`
}

Account represents information about the user account.

type AtomType

type AtomType int

AtomType represents the type of the value.

const (
	// TypeBoolean is the returned type when the value is a bool
	TypeBoolean AtomType = iota
	// TypeInteger is the returned type when the value is an int
	TypeInteger
	// TypeDouble is the returned type when the value is a float
	TypeDouble
	// TypeString is the returned type when the value is a string
	TypeString
	// TypeBytes is the returned type when the value is a []byte
	TypeBytes
	// TypeDate is the returned type when the value is a Date
	TypeDate
	// TypeList is the returned type when the value is a List
	TypeList
)

type ChunkUploadResponse

type ChunkUploadResponse struct {
	UploadID string `json:"upload_id"` // Unique ID of this upload.
	Offset   int64  `json:"offset"`    // Size in bytes of already sent data.
	Expires  DBTime `json:"expires"`   // Expiration time of this upload.
}

ChunkUploadResponse represents the reply of chunked_upload.

type CopyRef

type CopyRef struct {
	CopyRef string `json:"copy_ref"` // Reference to use on fileops/copy.
	Expires string `json:"expires"`  // Expiration date.
}

CopyRef represents the reply of CopyRef.

type Cursor

type Cursor struct {
	Cursor string `json:"cursor"`
}

Cursor represents the tag of a server state at a given moment.

type DBTime

type DBTime time.Time

DBTime allow marshalling and unmarshalling of time.

func (DBTime) MarshalJSON

func (dbt DBTime) MarshalJSON() ([]byte, error)

MarshalJSON marshals a time according to the Dropbox format.

func (*DBTime) UnmarshalJSON

func (dbt *DBTime) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshals a time according to the Dropbox format.

type Datastore

type Datastore struct {
	// contains filtered or unexported fields
}

Datastore represents a datastore.

func (*Datastore) AwaitDeltas

func (ds *Datastore) AwaitDeltas() error

AwaitDeltas awaits for deltas and applies them.

func (*Datastore) Close

func (ds *Datastore) Close()

Close closes the datastore.

func (*Datastore) Commit

func (ds *Datastore) Commit() error

Commit commits the changes registered by sending them to the server.

func (*Datastore) Delete

func (ds *Datastore) Delete() error

Delete deletes the datastore.

func (*Datastore) GetTable

func (ds *Datastore) GetTable(tableID string) (*Table, error)

GetTable returns the requested table.

func (*Datastore) LoadSnapshot

func (ds *Datastore) LoadSnapshot() error

LoadSnapshot updates the state of the datastore from the server.

func (*Datastore) Rollback

func (ds *Datastore) Rollback() error

Rollback reverts all local changes and discards them.

func (*Datastore) SetMTime

func (ds *Datastore) SetMTime(t time.Time) error

SetMTime sets the datastore mtime to the given time.

func (*Datastore) SetTitle

func (ds *Datastore) SetTitle(t string) error

SetTitle sets the datastore title to the given string.

type DatastoreInfo

type DatastoreInfo struct {
	ID string
	// contains filtered or unexported fields
}

DatastoreInfo represents the information about a datastore.

type DatastoreManager

type DatastoreManager struct {
	// contains filtered or unexported fields
}

DatastoreManager represents all datastores linked to the current account.

func (*DatastoreManager) CreateDatastore

func (dmgr *DatastoreManager) CreateDatastore(dsID string) (*Datastore, error)

CreateDatastore creates a global datastore with a unique ID, empty string for a random key.

func (*DatastoreManager) DeleteDatastore

func (dmgr *DatastoreManager) DeleteDatastore(dsID string) error

DeleteDatastore deletes a datastore.

func (*DatastoreManager) ListDatastores

func (dmgr *DatastoreManager) ListDatastores() ([]DatastoreInfo, error)

ListDatastores lists all datastores.

func (*DatastoreManager) OpenDatastore

func (dmgr *DatastoreManager) OpenDatastore(dsID string) (*Datastore, error)

OpenDatastore opens or creates a datastore.

func (*DatastoreManager) OpenDefaultDatastore

func (dmgr *DatastoreManager) OpenDefaultDatastore() (*Datastore, error)

OpenDefaultDatastore opens the default datastore.

type DeltaEntry

type DeltaEntry struct {
	Path  string // Path of this entry in lowercase.
	Entry *Entry // nil when this entry does not exists.
}

DeltaEntry represents the list of changes for a given path.

type DeltaPage

type DeltaPage struct {
	Reset   bool         // if true the local state must be cleared.
	HasMore bool         // if true an other call to delta should be made.
	Cursor               // Tag of the current state.
	Entries []DeltaEntry // List of changed entries.
}

DeltaPage represents the reply of delta.

type DeltaPoll

type DeltaPoll struct {
	Changes bool `json:"changes"` // true if the polled path has changed.
	Backoff int  `json:"backoff"` // time in second before calling poll again.
}

DeltaPoll represents the reply of longpoll_delta.

type Dropbox

type Dropbox struct {
	RootDirectory string // dropbox or sandbox.
	Locale        string // Locale sent to the API to translate/format messages.
	APIURL        string // Normal API URL.
	APIContentURL string // URL for transferring files.
	APINotifyURL  string // URL for realtime notification.
	// contains filtered or unexported fields
}

Dropbox client.

func NewDropbox

func NewDropbox() *Dropbox

NewDropbox returns a new Dropbox configured.

func (*Dropbox) AccessToken

func (db *Dropbox) AccessToken() string

AccessToken returns the OAuth access token.

func (*Dropbox) Auth

func (db *Dropbox) Auth() error

Auth displays the URL to authorize this application to connect to your account.

func (*Dropbox) AuthCode

func (db *Dropbox) AuthCode(code string) error

AuthCode gets the token associated with the given code.

func (*Dropbox) ChunkedUpload

func (db *Dropbox) ChunkedUpload(session *ChunkUploadResponse, input io.ReadCloser, chunksize int) (*ChunkUploadResponse, error)

ChunkedUpload sends a chunk with a maximum size of chunksize, if there is no session a new one is created.

func (*Dropbox) CommitChunkedUpload

func (db *Dropbox) CommitChunkedUpload(uploadid, dst string, overwrite bool, parentRev string) (*Entry, error)

CommitChunkedUpload ends the chunked upload by giving a name to the UploadID.

func (*Dropbox) Copy

func (db *Dropbox) Copy(src, dst string, isRef bool) (*Entry, error)

Copy copies a file. If isRef is true src must be a reference from CopyRef instead of a path.

func (*Dropbox) CopyRef

func (db *Dropbox) CopyRef(src string) (*CopyRef, error)

CopyRef gets a reference to a file. This reference can be used to copy this file to another user's Dropbox by passing it to the Copy method.

func (*Dropbox) CreateFolder

func (db *Dropbox) CreateFolder(path string) (*Entry, error)

CreateFolder creates a new directory.

func (*Dropbox) Delete

func (db *Dropbox) Delete(path string) (*Entry, error)

Delete removes a file or directory (it is a recursive delete).

func (*Dropbox) Delta

func (db *Dropbox) Delta(cursor, pathPrefix string) (*DeltaPage, error)

Delta gets modifications since the cursor.

func (*Dropbox) Download

func (db *Dropbox) Download(src, rev string, offset int64) (io.ReadCloser, int64, error)

Download requests the file located at src, the specific revision may be given. offset is used in case the download was interrupted. A io.ReadCloser and the file size is returned.

func (*Dropbox) DownloadAES

func (db *Dropbox) DownloadAES(key []byte, src, rev string, offset int) (io.ReadCloser, error)

DownloadAES downloads and decrypts the file located in the src path on Dropbox and returns a io.ReadCloser.

func (*Dropbox) DownloadToFile

func (db *Dropbox) DownloadToFile(src, dst, rev string) error

DownloadToFile downloads the file located in the src path on the Dropbox to the dst file on the local disk. If the destination file exists it will be truncated.

func (*Dropbox) DownloadToFileAES

func (db *Dropbox) DownloadToFileAES(key []byte, src, dst, rev string) error

DownloadToFileAES downloads and decrypts the file located in the src path on Dropbox to the dst file on the local disk.

func (*Dropbox) DownloadToFileResume

func (db *Dropbox) DownloadToFileResume(src, dst, rev string) error

DownloadToFileResume resumes the download of the file located in the src path on the Dropbox to the dst file on the local disk.

func (*Dropbox) FilesPut

func (db *Dropbox) FilesPut(input io.ReadCloser, size int64, dst string, overwrite bool, parentRev string) (*Entry, error)

FilesPut uploads size bytes from the input reader to the dst path on Dropbox.

func (*Dropbox) FilesPutAES

func (db *Dropbox) FilesPutAES(key []byte, input io.ReadCloser, size int64, dst string, overwrite bool, parentRev string) (*Entry, error)

FilesPutAES uploads and encrypts size bytes from the input reader to the dst path on Dropbox.

func (*Dropbox) GetAccountInfo

func (db *Dropbox) GetAccountInfo() (*Account, error)

GetAccountInfo gets account information for the user currently authenticated.

func (*Dropbox) LatestCursor

func (db *Dropbox) LatestCursor(prefix string, mediaInfo bool) (*Cursor, error)

LatestCursor returns the latest cursor without fetching any data.

func (*Dropbox) LongPollDelta

func (db *Dropbox) LongPollDelta(cursor string, timeout int) (*DeltaPoll, error)

LongPollDelta waits for a notification to happen.

func (*Dropbox) Media

func (db *Dropbox) Media(path string) (*Link, error)

Media shares a file for streaming (direct access).

func (*Dropbox) Metadata

func (db *Dropbox) Metadata(src string, list bool, includeDeleted bool, hash, rev string, limit int) (*Entry, error)

Metadata gets the metadata for a file or a directory. If list is true and src is a directory, immediate child will be sent in the Contents field. If include_deleted is true, entries deleted will be sent. hash is the hash of the contents of a directory, it is used to avoid sending data when directory did not change. rev is the specific revision to get the metadata from. limit is the maximum number of entries requested.

func (*Dropbox) Move

func (db *Dropbox) Move(src, dst string) (*Entry, error)

Move moves a file or directory.

func (*Dropbox) NewDatastoreManager

func (db *Dropbox) NewDatastoreManager() *DatastoreManager

NewDatastoreManager returns a new DatastoreManager linked to the current account.

func (*Dropbox) Restore

func (db *Dropbox) Restore(src string, rev string) (*Entry, error)

Restore restores a deleted file at the corresponding revision.

func (*Dropbox) Revisions

func (db *Dropbox) Revisions(src string, revLimit int) ([]Entry, error)

Revisions gets the list of revisions for a file.

func (*Dropbox) Search

func (db *Dropbox) Search(path, query string, fileLimit int, includeDeleted bool) ([]Entry, error)

Search searches the entries matching all the words contained in query in the given path. The maximum number of entries and whether to consider deleted file may be given.

func (*Dropbox) SetAccessToken

func (db *Dropbox) SetAccessToken(accesstoken string)

SetAccessToken sets access token to avoid calling Auth method.

func (*Dropbox) SetAppInfo

func (db *Dropbox) SetAppInfo(clientid, clientsecret string) error

SetAppInfo sets the clientid (app_key) and clientsecret (app_secret). You have to register an application on https://www.dropbox.com/developers/apps.

func (*Dropbox) SetContext

func (db *Dropbox) SetContext(ctx context.Context)

SetContext allow to set a custom context.

func (*Dropbox) SetRedirectURL

func (db *Dropbox) SetRedirectURL(url string)

SetRedirectURL updates the configuration with the given redirection URL.

func (*Dropbox) SharedFolders

func (db *Dropbox) SharedFolders(sharedFolderID string) ([]SharedFolder, error)

SharedFolders returns the list of allowed shared folders.

func (*Dropbox) Shares

func (db *Dropbox) Shares(path string, shortURL bool) (*Link, error)

Shares shares a file.

func (*Dropbox) Thumbnails

func (db *Dropbox) Thumbnails(src, format, size string) (io.ReadCloser, int64, *Entry, error)

Thumbnails gets a thumbnail for an image.

func (*Dropbox) ThumbnailsToFile

func (db *Dropbox) ThumbnailsToFile(src, dst, format, size string) (*Entry, error)

ThumbnailsToFile downloads the file located in the src path on the Dropbox to the dst file on the local disk.

func (*Dropbox) UploadByChunk

func (db *Dropbox) UploadByChunk(input io.ReadCloser, chunksize int, dst string, overwrite bool, parentRev string) (*Entry, error)

UploadByChunk uploads data from the input reader to the dst path on Dropbox by sending chunks of chunksize.

func (*Dropbox) UploadFile

func (db *Dropbox) UploadFile(src, dst string, overwrite bool, parentRev string) (*Entry, error)

UploadFile uploads the file located in the src path on the local disk to the dst path on Dropbox.

func (*Dropbox) UploadFileAES

func (db *Dropbox) UploadFileAES(key []byte, src, dst string, overwrite bool, parentRev string) (*Entry, error)

UploadFileAES uploads and encrypts the file located in the src path on the local disk to the dst path on Dropbox.

type Entry

type Entry struct {
	Bytes                int64     `json:"bytes,omitempty"`        // Size of the file in bytes.
	ClientMtime          DBTime    `json:"client_mtime,omitempty"` // Modification time set by the client when added.
	Contents             []Entry   `json:"contents,omitempty"`     // List of children for a directory.
	Hash                 string    `json:"hash,omitempty"`         // Hash of this entry.
	Icon                 string    `json:"icon,omitempty"`         // Name of the icon displayed for this entry.
	IsDeleted            bool      `json:"is_deleted,omitempty"`   // true if this entry was deleted.
	IsDir                bool      `json:"is_dir,omitempty"`       // true if this entry is a directory.
	MimeType             string    `json:"mime_type,omitempty"`    // MimeType of this entry.
	Modified             DBTime    `json:"modified,omitempty"`     // Date of last modification.
	Path                 string    `json:"path,omitempty"`         // Absolute path of this entry.
	Revision             string    `json:"rev,omitempty"`          // Unique ID for this file revision.
	Root                 string    `json:"root,omitempty"`         // dropbox or sandbox.
	Size                 string    `json:"size,omitempty"`         // Size of the file humanized/localized.
	ThumbExists          bool      `json:"thumb_exists,omitempty"` // true if a thumbnail is available for this entry.
	Modifier             *Modifier `json:"modifier"`               // last user to edit the file if in a shared folder
	ParentSharedFolderID string    `json:"parent_shared_folder_id,omitempty"`
}

Entry represents the metadata of a file or folder.

type Error

type Error struct {
	StatusCode int // HTTP status code
	Text       string
}

Error - all errors generated by HTTP transactions are of this type. Other error may be passed on from library functions though.

func (*Error) Error

func (e *Error) Error() string

Error satisfy the error interface.

type Fields

type Fields map[string]value

Fields represents a record.

type Link struct {
	Expires DBTime `json:"expires"` // Expiration date of this link.
	URL     string `json:"url"`     // URL to share.
}

Link for sharing a file.

type List

type List struct {
	// contains filtered or unexported fields
}

List represents a value of type list.

func (*List) Add

func (l *List) Add(i interface{}) error

Add adds the item at the end of the list.

func (*List) AddAtPos

func (l *List) AddAtPos(n int, i interface{}) error

AddAtPos inserts the item at the n-th position in the list.

func (*List) Get

func (l *List) Get(n int) (interface{}, error)

Get gets the n-th element in the list.

func (*List) GetType

func (l *List) GetType(n int) (AtomType, error)

GetType gets the type of the n-th element in the list.

func (*List) IsEmpty

func (l *List) IsEmpty() bool

IsEmpty returns whether the list contains an element.

func (*List) Move

func (l *List) Move(from, to int) error

Move moves the element from the from-th position to the to-th.

func (*List) Remove

func (l *List) Remove(n int) error

Remove removes the n-th element of the list.

func (*List) Set

func (l *List) Set(n int, i interface{}) error

Set sets the value of the n-th element of the list.

func (*List) Size

func (l *List) Size() int

Size returns the number of elements in the list.

type Modifier

type Modifier struct {
	UID         int64  `json:"uid"`
	DisplayName string `json:"display_name"`
}

Modifier represents the user who made a change on a particular file

type Record

type Record struct {
	// contains filtered or unexported fields
}

Record represents an entry in a table.

func (*Record) DeleteField

func (r *Record) DeleteField(field string) error

DeleteField deletes the given field from this record.

func (*Record) DeleteRecord

func (r *Record) DeleteRecord()

DeleteRecord deletes this record.

func (*Record) FieldNames

func (r *Record) FieldNames() []string

FieldNames returns a list of fields names.

func (*Record) Get

func (r *Record) Get(field string) (interface{}, bool, error)

Get gets the current value of this field.

func (*Record) GetFieldType

func (r *Record) GetFieldType(field string) (AtomType, error)

GetFieldType returns the type of the given field.

func (*Record) GetID

func (r *Record) GetID() string

GetID returns the ID of this record.

func (*Record) GetOrCreateList

func (r *Record) GetOrCreateList(field string) (*List, error)

GetOrCreateList gets the current value of this field.

func (*Record) GetTable

func (r *Record) GetTable() *Table

GetTable returns the table associated with this record.

func (*Record) HasField

func (r *Record) HasField(field string) (bool, error)

HasField returns whether this field exists.

func (*Record) IsDeleted

func (r *Record) IsDeleted() bool

IsDeleted returns whether this record was deleted.

func (*Record) Set

func (r *Record) Set(field string, value interface{}) error

Set sets the value of a field.

type SharedFolder

type SharedFolder struct {
	SharedFolderID   string               `json:"shared_folder_id"`
	SharedFolderName string               `json:"shared_folder_name"`
	Path             string               `json:"path"`
	AccessType       string               `json:"access_type"`
	SharedLinkPolicy string               `json:"shared_link_policy"`
	Owner            User                 `json:"owner"`
	Membership       []SharedFolderMember `json:"membership"`
}

SharedFolder reprensents a directory with a specific sharing policy.

type SharedFolderMember

type SharedFolderMember struct {
	User       User   `json:"user"`
	Active     bool   `json:"active"`
	AccessType string `json:"access_type"`
}

SharedFolderMember represents access right associated with a Dropbox user.

type Table

type Table struct {
	// contains filtered or unexported fields
}

Table represents a list of records.

func (*Table) Get

func (t *Table) Get(recordID string) (*Record, error)

Get returns the record with this ID.

func (*Table) GetDatastore

func (t *Table) GetDatastore() *Datastore

GetDatastore returns the datastore associated with this table.

func (*Table) GetID

func (t *Table) GetID() string

GetID returns the ID of this table.

func (*Table) GetOrInsert

func (t *Table) GetOrInsert(recordID string) (*Record, error)

GetOrInsert gets the requested record.

func (*Table) GetOrInsertWithFields

func (t *Table) GetOrInsertWithFields(recordID string, fields Fields) (*Record, error)

GetOrInsertWithFields gets the requested table.

func (*Table) Query

func (t *Table) Query(fields Fields) ([]*Record, error)

Query returns a list of records matching all the given fields.

type User

type User struct {
	UID         int64  `json:"uid"`
	DisplayName string `json:"display_name"`
}

User represents a Dropbox user.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL