Repository: tj/go-dropbox Branch: master Commit: 42dd2be3662d Files: 14 Total size: 33.6 KB Directory structure: gitextract_owj5n0lq/ ├── LICENSE ├── Readme.md ├── client.go ├── client_test.go ├── config.go ├── doc.go ├── error.go ├── example_test.go ├── files.go ├── files_test.go ├── sharing.go ├── sharing_test.go ├── users.go └── users_test.go ================================================ FILE CONTENTS ================================================ ================================================ FILE: LICENSE ================================================ (The MIT License) Copyright (c) 2015 TJ Holowaychuk <tj@tjholowaychuk.coma> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: Readme.md ================================================ [![GoDoc](https://godoc.org/github.com/tj/go-dropbox?status.svg)](https://godoc.org/github.com/tj/go-dropbox) [![Build Status](https://semaphoreci.com/api/v1/projects/bc0bfd8b-73c9-45ba-b988-00f9e285e6ef/617305/badge.svg)](https://semaphoreci.com/tj/go-dropbox) # Dropbox Simple Dropbox v2 client for Go. For a higher level client take a look at [go-dropy](https://github.com/tj/go-dropy). ## About Modelled more or less 1:1 with the API for consistency and parity with the [official documentation](https://www.dropbox.com/developers/documentation/http). More sugar should be implemented on top. ## Testing To manually run tests use the test account access token: ``` $ export DROPBOX_ACCESS_TOKEN=oENFkq_oIVAAAAAAAAAAC8gE3wIUFMEraPBL-D71Aq2C4zuh1l4oDn5FiWSdVVlL $ go test -v ``` # License MIT ================================================ FILE: client.go ================================================ package dropbox import ( "bytes" "encoding/json" "io" "io/ioutil" "net/http" "strings" ) // Client implements a Dropbox client. You may use the Files and Users // clients directly if preferred, however Client exposes them both. type Client struct { *Config Users *Users Files *Files Sharing *Sharing } // New client. func New(config *Config) *Client { c := &Client{Config: config} c.Users = &Users{c} c.Files = &Files{c} c.Sharing = &Sharing{c} return c } // call rpc style endpoint. func (c *Client) call(path string, in interface{}) (io.ReadCloser, error) { url := "https://api.dropboxapi.com/2" + path body, err := json.Marshal(in) if err != nil { return nil, err } req, err := http.NewRequest("POST", url, bytes.NewReader(body)) if err != nil { return nil, err } req.Header.Set("Authorization", "Bearer "+c.AccessToken) req.Header.Set("Content-Type", "application/json") r, _, err := c.do(req) return r, err } // download style endpoint. func (c *Client) download(path string, in interface{}, r io.Reader) (io.ReadCloser, int64, error) { url := "https://content.dropboxapi.com/2" + path body, err := json.Marshal(in) if err != nil { return nil, 0, err } req, err := http.NewRequest("POST", url, r) if err != nil { return nil, 0, err } req.Header.Set("Authorization", "Bearer "+c.AccessToken) req.Header.Set("Dropbox-API-Arg", string(body)) if r != nil { req.Header.Set("Content-Type", "application/octet-stream") } return c.do(req) } // perform the request. func (c *Client) do(req *http.Request) (io.ReadCloser, int64, error) { res, err := c.HTTPClient.Do(req) if err != nil { return nil, 0, err } if res.StatusCode < 400 { return res.Body, res.ContentLength, err } defer res.Body.Close() e := &Error{ Status: http.StatusText(res.StatusCode), StatusCode: res.StatusCode, } kind := res.Header.Get("Content-Type") if strings.Contains(kind, "text/plain") { if b, err := ioutil.ReadAll(res.Body); err == nil { e.Summary = string(b) return nil, 0, e } return nil, 0, err } if err := json.NewDecoder(res.Body).Decode(e); err != nil { return nil, 0, err } return nil, 0, e } ================================================ FILE: client_test.go ================================================ package dropbox import ( "testing" "github.com/segmentio/go-env" "github.com/stretchr/testify/assert" ) func client() *Client { token := env.MustGet("DROPBOX_ACCESS_TOKEN") return New(NewConfig(token)) } func TestClient_error_text(t *testing.T) { c := client() _, err := c.Files.Download(&DownloadInput{ Path: "asdfasdfasdf", }) assert.Error(t, err) e := err.(*Error) assert.Contains(t, e.Error(), "Error in call") assert.Equal(t, "Bad Request", e.Status) assert.Equal(t, 400, e.StatusCode) } func TestClient_error_json(t *testing.T) { c := client() _, err := c.Files.Download(&DownloadInput{"/nothing"}) assert.Error(t, err) e := err.(*Error) assert.Contains(t, e.Error(), "path/not_found") assert.Equal(t, "Conflict", e.Status) assert.Equal(t, 409, e.StatusCode) } ================================================ FILE: config.go ================================================ package dropbox import ( "net/http" ) // Config for the Dropbox clients. type Config struct { HTTPClient *http.Client AccessToken string } // NewConfig with the given access token. func NewConfig(accessToken string) *Config { return &Config{ HTTPClient: http.DefaultClient, AccessToken: accessToken, } } ================================================ FILE: doc.go ================================================ // Package dropbox implements a simple v2 client. package dropbox ================================================ FILE: error.go ================================================ package dropbox // Error response. type Error struct { Status string StatusCode int Summary string `json:"error_summary"` } // Error string. func (e *Error) Error() string { return e.Summary } ================================================ FILE: example_test.go ================================================ package dropbox_test import ( "fmt" "io" "os" "github.com/tj/go-dropbox" ) // Example using the Client, which provides both User and File clients. func Example() { d := dropbox.New(dropbox.NewConfig("")) file, _ := os.Open("Readme.md") d.Files.Upload(&dropbox.UploadInput{ Path: "Readme.md", Reader: file, Mute: true, }) } // Example using the Files client directly. func Example_files() { files := dropbox.NewFiles(dropbox.NewConfig("")) out, _ := files.Download(&dropbox.DownloadInput{ Path: "Readme.md", }) io.Copy(os.Stdout, out.Body) } // Example using the Users client directly. func Example_users() { users := dropbox.NewUsers(dropbox.NewConfig("")) out, _ := users.GetCurrentAccount() fmt.Printf("%v\n", out) } ================================================ FILE: files.go ================================================ package dropbox import ( "crypto/sha256" "encoding/json" "fmt" "io" "os" "time" ) // Files client for files and folders. type Files struct { *Client } // NewFiles client. func NewFiles(config *Config) *Files { return &Files{ Client: &Client{ Config: config, }, } } // WriteMode determines what to do if the file already exists. type WriteMode string // Supported write modes. const ( WriteModeAdd WriteMode = "add" WriteModeOverwrite = "overwrite" ) // Dimensions specifies the dimensions of a photo or video. type Dimensions struct { Width uint64 `json:"width"` Height uint64 `json:"height"` } // GPSCoordinates specifies the GPS coordinate of a photo or video. type GPSCoordinates struct { Latitude float64 `json:"latitude"` Longitude float64 `json:"longitude"` } // PhotoMetadata specifies metadata for a photo. type PhotoMetadata struct { Dimensions *Dimensions `json:"dimensions,omitempty"` Location *GPSCoordinates `json:"location,omitempty"` TimeTaken time.Time `json:"time_taken,omitempty"` } // VideoMetadata specifies metadata for a video. type VideoMetadata struct { Dimensions *Dimensions `json:"dimensions,omitempty"` Location *GPSCoordinates `json:"location,omitempty"` TimeTaken time.Time `json:"time_taken,omitempty"` Duration uint64 `json:"duration,omitempty"` } // MediaMetadata provides metadata for a photo or video. type MediaMetadata struct { Photo *PhotoMetadata `json:"photo,omitempty"` Video *VideoMetadata `json:"video,omitempty"` } // MediaInfo provides additional information for a photo or video file. type MediaInfo struct { Pending bool `json:"pending"` Metadata *MediaMetadata `json:"metadata,omitempty"` } // FileSharingInfo for a file which is contained in a shared folder. type FileSharingInfo struct { ReadOnly bool `json:"read_only"` ParentSharedFolderID string `json:"parent_shared_folder_id"` ModifiedBy string `json:"modified_by,omitempty"` } // Metadata for a file or folder. type Metadata struct { Tag string `json:".tag"` Name string `json:"name"` PathLower string `json:"path_lower"` PathDisplay string `json:"path_display"` ClientModified time.Time `json:"client_modified"` ServerModified time.Time `json:"server_modified"` Rev string `json:"rev"` Size uint64 `json:"size"` ID string `json:"id"` MediaInfo *MediaInfo `json:"media_info,omitempty"` SharingInfo *FileSharingInfo `json:"sharing_info,omitempty"` ContentHash string `json:"content_hash,omitempty"` } // GetMetadataInput request input. type GetMetadataInput struct { Path string `json:"path"` IncludeMediaInfo bool `json:"include_media_info"` } // GetMetadataOutput request output. type GetMetadataOutput struct { Metadata } // GetMetadata returns the metadata for a file or folder. func (c *Files) GetMetadata(in *GetMetadataInput) (out *GetMetadataOutput, err error) { body, err := c.call("/files/get_metadata", in) if err != nil { return } defer body.Close() err = json.NewDecoder(body).Decode(&out) return } // CreateFolderInput request input. type CreateFolderInput struct { Path string `json:"path"` } // CreateFolderOutput request output. type CreateFolderOutput struct { Name string `json:"name"` PathLower string `json:"path_lower"` ID string `json:"id"` } // CreateFolder creates a folder. func (c *Files) CreateFolder(in *CreateFolderInput) (out *CreateFolderOutput, err error) { body, err := c.call("/files/create_folder", in) if err != nil { return } defer body.Close() err = json.NewDecoder(body).Decode(&out) return } // DeleteInput request input. type DeleteInput struct { Path string `json:"path"` } // DeleteOutput request output. type DeleteOutput struct { Metadata } // Delete a file or folder and its contents. func (c *Files) Delete(in *DeleteInput) (out *DeleteOutput, err error) { body, err := c.call("/files/delete", in) if err != nil { return } defer body.Close() err = json.NewDecoder(body).Decode(&out) return } // PermanentlyDeleteInput request input. type PermanentlyDeleteInput struct { Path string `json:"path"` } // PermanentlyDelete a file or folder and its contents. func (c *Files) PermanentlyDelete(in *PermanentlyDeleteInput) (err error) { body, err := c.call("/files/delete", in) if err != nil { return } defer body.Close() return } // CopyInput request input. type CopyInput struct { FromPath string `json:"from_path"` ToPath string `json:"to_path"` } // CopyOutput request output. type CopyOutput struct { Metadata } // Copy a file or folder to a different location. func (c *Files) Copy(in *CopyInput) (out *CopyOutput, err error) { body, err := c.call("/files/copy", in) if err != nil { return } defer body.Close() err = json.NewDecoder(body).Decode(&out) return } // MoveInput request input. type MoveInput struct { FromPath string `json:"from_path"` ToPath string `json:"to_path"` } // MoveOutput request output. type MoveOutput struct { Metadata } // Move a file or folder to a different location. func (c *Files) Move(in *MoveInput) (out *MoveOutput, err error) { body, err := c.call("/files/move", in) if err != nil { return } defer body.Close() err = json.NewDecoder(body).Decode(&out) return } // RestoreInput request input. type RestoreInput struct { Path string `json:"path"` Rev string `json:"rev"` } // RestoreOutput request output. type RestoreOutput struct { Metadata } // Restore a file to a specific revision. func (c *Files) Restore(in *RestoreInput) (out *RestoreOutput, err error) { body, err := c.call("/files/restore", in) if err != nil { return } defer body.Close() err = json.NewDecoder(body).Decode(&out) return } // ListFolderInput request input. type ListFolderInput struct { Path string `json:"path"` Recursive bool `json:"recursive"` IncludeMediaInfo bool `json:"include_media_info"` IncludeDeleted bool `json:"include_deleted"` } // ListFolderOutput request output. type ListFolderOutput struct { Cursor string `json:"cursor"` HasMore bool `json:"has_more"` Entries []*Metadata } // ListFolder returns the metadata for a file or folder. func (c *Files) ListFolder(in *ListFolderInput) (out *ListFolderOutput, err error) { in.Path = normalizePath(in.Path) body, err := c.call("/files/list_folder", in) if err != nil { return } defer body.Close() err = json.NewDecoder(body).Decode(&out) return } // ListFolderContinueInput request input. type ListFolderContinueInput struct { Cursor string `json:"cursor"` } // ListFolderContinue pagenates using the cursor from ListFolder. func (c *Files) ListFolderContinue(in *ListFolderContinueInput) (out *ListFolderOutput, err error) { body, err := c.call("/files/list_folder/continue", in) if err != nil { return } defer body.Close() err = json.NewDecoder(body).Decode(&out) return } // SearchMode determines how a search is performed. type SearchMode string // Supported search modes. const ( SearchModeFilename SearchMode = "filename" SearchModeFilenameAndContent = "filename_and_content" SearchModeDeletedFilename = "deleted_filename" ) // SearchMatchType represents the type of match made. type SearchMatchType string // Supported search match types. const ( SearchMatchFilename SearchMatchType = "filename" SearchMatchContent = "content" SearchMatchBoth = "both" ) // SearchMatch represents a matched file or folder. type SearchMatch struct { MatchType struct { Tag SearchMatchType `json:".tag"` } `json:"match_type"` Metadata *Metadata `json:"metadata"` } // SearchInput request input. type SearchInput struct { Path string `json:"path"` Query string `json:"query"` Start uint64 `json:"start,omitempty"` MaxResults uint64 `json:"max_results,omitempty"` Mode SearchMode `json:"mode"` } // SearchOutput request output. type SearchOutput struct { Matches []*SearchMatch `json:"matches"` More bool `json:"more"` Start uint64 `json:"start"` } // Search for files and folders. func (c *Files) Search(in *SearchInput) (out *SearchOutput, err error) { in.Path = normalizePath(in.Path) if in.Mode == "" { in.Mode = SearchModeFilename } body, err := c.call("/files/search", in) if err != nil { return } defer body.Close() err = json.NewDecoder(body).Decode(&out) return } // UploadInput request input. type UploadInput struct { Path string `json:"path"` Mode WriteMode `json:"mode"` AutoRename bool `json:"autorename"` Mute bool `json:"mute"` ClientModified string `json:"client_modified,omitempty"` Reader io.Reader `json:"-"` } // UploadOutput request output. type UploadOutput struct { Metadata } // Upload a file smaller than 150MB. func (c *Files) Upload(in *UploadInput) (out *UploadOutput, err error) { body, _, err := c.download("/files/upload", in, in.Reader) if err != nil { return } defer body.Close() err = json.NewDecoder(body).Decode(&out) return } // DownloadInput request input. type DownloadInput struct { Path string `json:"path"` } // DownloadOutput request output. type DownloadOutput struct { Body io.ReadCloser Length int64 } // Download a file. func (c *Files) Download(in *DownloadInput) (out *DownloadOutput, err error) { body, l, err := c.download("/files/download", in, nil) if err != nil { return } out = &DownloadOutput{body, l} return } // ThumbnailFormat determines the format of the thumbnail. type ThumbnailFormat string const ( // GetThumbnailFormatJPEG specifies a JPG thumbnail GetThumbnailFormatJPEG ThumbnailFormat = "jpeg" // GetThumbnailFormatPNG specifies a PNG thumbnail GetThumbnailFormatPNG = "png" ) // ThumbnailSize determines the size of the thumbnail. type ThumbnailSize string const ( // GetThumbnailSizeW32H32 specifies a size of 32 by 32 px GetThumbnailSizeW32H32 ThumbnailSize = "w32h32" // GetThumbnailSizeW64H64 specifies a size of 64 by 64 px GetThumbnailSizeW64H64 = "w64h64" // GetThumbnailSizeW128H128 specifies a size of 128 by 128 px GetThumbnailSizeW128H128 = "w128h128" // GetThumbnailSizeW640H480 specifies a size of 640 by 480 px GetThumbnailSizeW640H480 = "w640h480" // GetThumbnailSizeW1024H768 specifies a size of 1024 by 768 px GetThumbnailSizeW1024H768 = "w1024h768" ) // GetThumbnailInput request input. type GetThumbnailInput struct { Path string `json:"path"` Format ThumbnailFormat `json:"format"` Size ThumbnailSize `json:"size"` } // GetThumbnailOutput request output. type GetThumbnailOutput struct { Body io.ReadCloser Length int64 } // GetThumbnail a thumbnail for a file. Currently thumbnails are only generated for the // files with the following extensions: png, jpeg, png, tiff, tif, gif and bmp. func (c *Files) GetThumbnail(in *GetThumbnailInput) (out *GetThumbnailOutput, err error) { body, l, err := c.download("/files/get_thumbnail", in, nil) if err != nil { return } out = &GetThumbnailOutput{body, l} return } // GetPreviewInput request input. type GetPreviewInput struct { Path string `json:"path"` } // GetPreviewOutput request output. type GetPreviewOutput struct { Body io.ReadCloser Length int64 } // GetPreview a preview for a file. Currently previews are only generated for the // files with the following extensions: .doc, .docx, .docm, .ppt, .pps, .ppsx, // .ppsm, .pptx, .pptm, .xls, .xlsx, .xlsm, .rtf func (c *Files) GetPreview(in *GetPreviewInput) (out *GetPreviewOutput, err error) { body, l, err := c.download("/files/get_preview", in, nil) if err != nil { return } out = &GetPreviewOutput{body, l} return } // ListRevisionsInput request input. type ListRevisionsInput struct { Path string `json:"path"` Limit uint64 `json:"limit,omitempty"` } // ListRevisionsOutput request output. type ListRevisionsOutput struct { IsDeleted bool Entries []*Metadata } // ListRevisions gets the revisions of the specified file. func (c *Files) ListRevisions(in *ListRevisionsInput) (out *ListRevisionsOutput, err error) { body, err := c.call("/files/list_revisions", in) if err != nil { return } defer body.Close() err = json.NewDecoder(body).Decode(&out) return } // Normalize path so people can use "/" as they expect. func normalizePath(s string) string { if s == "/" { return "" } return s } const hashBlockSize = 4 * 1024 * 1024 // ContentHash returns the Dropbox content_hash for a io.Reader. // See https://www.dropbox.com/developers/reference/content-hash func ContentHash(r io.Reader) (string, error) { buf := make([]byte, hashBlockSize) resultHash := sha256.New() n, err := r.Read(buf) if err != nil && err != io.EOF { return "", err } if n > 0 { bufHash := sha256.Sum256(buf[:n]) resultHash.Write(bufHash[:]) } for n == hashBlockSize && err == nil { n, err = r.Read(buf) if err != nil && err != io.EOF { return "", err } if n > 0 { bufHash := sha256.Sum256(buf[:n]) resultHash.Write(bufHash[:]) } } return fmt.Sprintf("%x", resultHash.Sum(nil)), nil } // FileContentHash returns the Dropbox content_hash for a local file. // See https://www.dropbox.com/developers/reference/content-hash func FileContentHash(filename string) (string, error) { f, err := os.Open(filename) if err != nil { return "", err } defer f.Close() return ContentHash(f) } ================================================ FILE: files_test.go ================================================ package dropbox import ( "bytes" "io/ioutil" "os" "testing" "time" "github.com/stretchr/testify/assert" "github.com/ungerik/go-dry" ) func TestFiles_Upload(t *testing.T) { c := client() file, err := os.Open("Readme.md") assert.NoError(t, err, "error opening file") defer file.Close() out, err := c.Files.Upload(&UploadInput{ Mute: true, Mode: WriteModeOverwrite, Path: "/Readme.md", Reader: file, }) assert.NoError(t, err, "error uploading file") assert.Equal(t, "/readme.md", out.PathLower) } func TestFiles_Download(t *testing.T) { c := client() out, err := c.Files.Download(&DownloadInput{"/Readme.md"}) assert.NoError(t, err, "error downloading") defer out.Body.Close() fi, err := os.Lstat("Readme.md") assert.NoError(t, err, "error getting local file info") assert.Equal(t, fi.Size(), out.Length, "Readme.md length mismatch") remote, err := ioutil.ReadAll(out.Body) assert.NoError(t, err, "error reading remote") local, err := ioutil.ReadFile("Readme.md") assert.NoError(t, err, "error reading local") assert.Equal(t, local, remote, "Readme.md mismatch") } func TestFiles_GetMetadata(t *testing.T) { c := client() out, err := c.Files.GetMetadata(&GetMetadataInput{ Path: "/Readme.md", }) assert.NoError(t, err) assert.Equal(t, "file", out.Tag) } func TestFiles_ListFolder(t *testing.T) { t.Parallel() c := client() out, err := c.Files.ListFolder(&ListFolderInput{ Path: "/list", }) assert.NoError(t, err) assert.Equal(t, 2000, len(out.Entries)) assert.True(t, out.HasMore) } func TestFiles_ListFolder_root(t *testing.T) { t.Parallel() c := client() _, err := c.Files.ListFolder(&ListFolderInput{ Path: "/", }) assert.NoError(t, err) } func TestFiles_Search(t *testing.T) { c := client() out, err := c.Files.Search(&SearchInput{ Path: "/", Query: "hello", }) assert.NoError(t, err) assert.Equal(t, 2, len(out.Matches)) } func TestFiles_Delete(t *testing.T) { c := client() out, err := c.Files.Delete(&DeleteInput{ Path: "/Readme.md", }) assert.NoError(t, err) assert.Equal(t, "/readme.md", out.PathLower) } // A gray, 64 by 64 px PNG var grayPng = []byte{ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x40, 0x08, 0x02, 0x00, 0x00, 0x00, 0x25, 0x0b, 0xe6, 0x89, 0x00, 0x00, 0x00, 0x04, 0x67, 0x41, 0x4d, 0x41, 0x00, 0x00, 0xb1, 0x8f, 0x0b, 0xfc, 0x61, 0x05, 0x00, 0x00, 0x00, 0x01, 0x73, 0x52, 0x47, 0x42, 0x00, 0xae, 0xce, 0x1c, 0xe9, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0e, 0xc3, 0x00, 0x00, 0x0e, 0xc3, 0x01, 0xc7, 0x6f, 0xa8, 0x64, 0x00, 0x00, 0x00, 0x18, 0x74, 0x45, 0x58, 0x74, 0x53, 0x6f, 0x66, 0x74, 0x77, 0x61, 0x72, 0x65, 0x00, 0x70, 0x61, 0x69, 0x6e, 0x74, 0x2e, 0x6e, 0x65, 0x74, 0x20, 0x34, 0x2e, 0x30, 0x2e, 0x36, 0xfc, 0x8c, 0x63, 0xdf, 0x00, 0x00, 0x00, 0x4c, 0x49, 0x44, 0x41, 0x54, 0x68, 0xde, 0xed, 0xcf, 0x31, 0x0d, 0x00, 0x00, 0x08, 0x03, 0x30, 0xe6, 0x7e, 0xb2, 0x91, 0xc0, 0x4d, 0xd2, 0x3a, 0x68, 0xda, 0xce, 0x67, 0x11, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0xb8, 0x2c, 0x4a, 0x27, 0x66, 0x41, 0xb9, 0xd3, 0xef, 0xa3, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, } func TestFiles_GetThumbnail(t *testing.T) { c := client() // REVIEW(bg): This feels a bit sloppy... { buf := bytes.NewBuffer(grayPng) _, err := c.Files.Upload(&UploadInput{ Mute: true, Mode: WriteModeOverwrite, Path: "/gray.png", Reader: buf, }) assert.NoError(t, err, "error uploading file") } out, err := c.Files.GetThumbnail(&GetThumbnailInput{"/gray.png", GetThumbnailFormatJPEG, GetThumbnailSizeW32H32}) assert.NoError(t, err) if err != nil { return } defer out.Body.Close() assert.NotEmpty(t, out.Length, "length should not be 0") buf := make([]byte, 11) _, err = out.Body.Read(buf) assert.NoError(t, err) assert.Equal(t, []byte{ 0xff, 0xd8, // JPEG SOI marker 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, // JFIF tag }, buf, "should have jpeg header") } func TestFiles_GetPreview(t *testing.T) { c := client() out, err := c.Files.GetPreview(&GetPreviewInput{"/sample.ppt"}) defer out.Body.Close() assert.NoError(t, err) assert.NotEmpty(t, out.Length, "length should not be 0") buf := make([]byte, 4) _, err = out.Body.Read(buf) assert.NoError(t, err) assert.Equal(t, []byte{0x25, 0x50, 0x44, 0x46}, buf, "should have pdf magic number") } func TestFiles_ListRevisions(t *testing.T) { c := client() out, err := c.Files.ListRevisions(&ListRevisionsInput{Path: "/sample.ppt"}) assert.NoError(t, err) assert.NotEmpty(t, out.Entries) assert.False(t, out.IsDeleted) } func TestFiles_ContentHash(t *testing.T) { data, err := dry.FileGetBytes("https://www.dropbox.com/static/images/developers/milky-way-nasa.jpg", time.Second*5) assert.NoError(t, err) hash, err := ContentHash(bytes.NewBuffer(data)) assert.NoError(t, err) assert.Equal(t, "485291fa0ee50c016982abbfa943957bcd231aae0492ccbaa22c58e3997b35e0", hash) } ================================================ FILE: sharing.go ================================================ package dropbox import ( "encoding/json" "time" ) // Sharing client. type Sharing struct { *Client } // NewSharing client. func NewSharing(config *Config) *Sharing { return &Sharing{ Client: &Client{ Config: config, }, } } // CreateSharedLinkInput request input. type CreateSharedLinkInput struct { Path string `json:"path"` } // CreateSharedLinkOutput request output. type CreateSharedLinkOutput struct { URL string `json:"url"` Path string `json:"path"` VisibilityModel struct { Tag VisibilityType `json:".tag"` } `json:"visibility"` Expires time.Time `json:"expires,omitempty"` } // VisibilityType determines who can access the link. type VisibilityType string // Visibility types supported. const ( Public VisibilityType = "public" TeamOnly = "team_only" Password = "password" TeamAndPassword = "team_and_password" SharedFolderOnly = "shared_folder_only" ) // CreateSharedLink returns a shared link. func (c *Sharing) CreateSharedLink(in *CreateSharedLinkInput) (out *CreateSharedLinkOutput, err error) { body, err := c.call("/sharing/create_shared_link_with_settings", in) if err != nil { return } defer body.Close() err = json.NewDecoder(body).Decode(&out) return } // ListShareLinksInput request input. type ListShareLinksInput struct { Path string `json:"path"` } // SharedLinkOutput request output. type SharedLinkOutput struct { URL string `json:"url"` Path string `json:"path"` VisibilityModel struct { Tag VisibilityType `json:".tag"` } `json:"visibility"` Expires time.Time `json:"expires,omitempty"` } // ListShareLinksOutput request output. type ListShareLinksOutput struct { Links []SharedLinkOutput `json:"links"` } // ListSharedLinks gets shared links of input. func (c *Sharing) ListSharedLinks(in *ListShareLinksInput) (out *ListShareLinksOutput, err error) { endpoint := "/sharing/list_shared_links" body, err := c.call(endpoint, in) if err != nil { return } defer body.Close() err = json.NewDecoder(body).Decode(&out) return } // ListSharedFolderInput request input. type ListSharedFolderInput struct { Limit uint64 `json:"limit"` Actions []FolderAction `json:"actions,omitempty"` } // FolderAction defines actions that may be taken on shared folders. type FolderAction struct { ChangeOptions string } // ListSharedFolderOutput lists metadata about shared folders with a cursor to retrieve the next page. type ListSharedFolderOutput struct { Entries []SharedFolderMetadata `json:"entries"` Cursor string `json:"cursor"` } // ListSharedFolders returns the list of all shared folders the current user has access to. func (c *Sharing) ListSharedFolders(in *ListSharedFolderInput) (out *ListSharedFolderOutput, err error) { body, err := c.call("/sharing/list_folders", in) if err != nil { return } defer body.Close() err = json.NewDecoder(body).Decode(&out) return } // ListSharedFolderContinueInput request input. type ListSharedFolderContinueInput struct { Cursor string `json:"cursor"` } // ListSharedFoldersContinue returns the list of all shared folders the current user has access to. func (c *Sharing) ListSharedFoldersContinue(in *ListSharedFolderContinueInput) (out *ListSharedFolderOutput, err error) { body, err := c.call("/sharing/list_folders/continue", in) if err != nil { return } defer body.Close() err = json.NewDecoder(body).Decode(&out) return } // SharedFolderMetadata includes basic information about the shared folder. type SharedFolderMetadata struct { AccessType struct { Tag AccessType `json:".tag"` } `json:"access_type"` IsTeamFolder bool `json:"is_team_folder"` Policy FolderPolicy `json:"policy"` Name string `json:"name"` SharedFolderID string `json:"shared_folder_id"` TimeInvited time.Time `json:"time_invited"` OwnerTeam struct { ID string `json:"id"` Name string `json:"name"` } `json:"owner_team"` ParentSharedFolderID string `json:"parent_shared_folder_id"` PathLower string `json:"path_lower"` Permissions []string `json:"permissions"` } // FolderPolicy enumerates the policies governing this shared folder. type FolderPolicy struct { ACLUpdatePolicy struct { Tag ACLUpdatePolicy `json:".tag"` } `json:"acl_update_policy"` SharedLinkPolicy struct { Tag SharedLinkPolicy `json:".tag"` } `json:"shared_link_policy"` MemberPolicy struct { Tag MemberPolicy `json:".tag"` } `json:"member_policy"` ResolvedMemberPolicy struct { Tag MemberPolicy `json:".tag"` } `json:"resolved_member_policy"` } // AccessType determines the level of access to a shared folder. type AccessType string // Access types supported. const ( Owner AccessType = "owner" Editor = "editor" Viewer = "viewer" ViewerNoComment = "viewer_no_comment" ) // ACLUpdatePolicy determines who can add and remove members from this shared folder. type ACLUpdatePolicy string // ACLUpdatePolicy types supported. const ( ACLUpdatePolicyOwner ACLUpdatePolicy = "owner" ACLUpdatePolicyEditors = "editors" ) // SharedLinkPolicy governs who can view shared links. type SharedLinkPolicy string // SharedLinkPolicy types supported. const ( SharedLinkPolicyAnyone SharedLinkPolicy = "anyone" SharedLinkPolicyMembers = "members" ) // MemberPolicy determines who can be a member of this shared folder, as set on the folder itself. type MemberPolicy string // MemberPolicy types supported. const ( MemberPolicyTeam MemberPolicy = "team" MemberPolicyAnyone = "anyone" ) ================================================ FILE: sharing_test.go ================================================ package dropbox import ( "testing" "github.com/stretchr/testify/assert" ) func TestSharing_CreateSharedLink(t *testing.T) { c := client() out, err := c.Sharing.CreateSharedLink(&CreateSharedLinkInput{ Path: "/hello.txt", }) assert.NoError(t, err, "error sharing file") assert.Equal(t, "/hello.txt", out.Path) } func TestSharing_ListSharedFolder(t *testing.T) { c := client() out, err := c.Sharing.ListSharedFolders(&ListSharedFolderInput{ Limit: 1, }) assert.NoError(t, err, "listing shared folders") assert.NotEmpty(t, out.Entries, "output should be non-empty") for out.Cursor != "" { out, err = c.Sharing.ListSharedFoldersContinue(&ListSharedFolderContinueInput{ Cursor: out.Cursor, }) assert.NoError(t, err, "listing shared folders") assert.NotEmpty(t, out.Entries, "output should be non-empty") } } ================================================ FILE: users.go ================================================ package dropbox import ( "encoding/json" ) // Users client for user accounts. type Users struct { *Client } // NewUsers client. func NewUsers(config *Config) *Users { return &Users{ Client: &Client{ Config: config, }, } } // GetAccountInput request input. type GetAccountInput struct { AccountID string `json:"account_id"` } // GetAccountOutput request output. type GetAccountOutput struct { AccountID string `json:"account_id"` Name struct { GivenName string `json:"given_name"` Surname string `json:"surname"` FamiliarName string `json:"familiar_name"` DisplayName string `json:"display_name"` } `json:"name"` } // GetAccount returns information about a user's account. func (c *Users) GetAccount(in *GetAccountInput) (out *GetAccountOutput, err error) { body, err := c.call("/users/get_account", in) if err != nil { return } defer body.Close() err = json.NewDecoder(body).Decode(&out) return } // GetCurrentAccountOutput request output. type GetCurrentAccountOutput struct { AccountID string `json:"account_id"` Name struct { GivenName string `json:"given_name"` Surname string `json:"surname"` FamiliarName string `json:"familiar_name"` DisplayName string `json:"display_name"` } `json:"name"` Email string `json:"email"` Locale string `json:"locale"` ReferralLink string `json:"referral_link"` IsPaired bool `json:"is_paired"` AccountType struct { Tag string `json:".tag"` } `json:"account_type"` Country string `json:"country"` } // GetCurrentAccount returns information about the current user's account. func (c *Users) GetCurrentAccount() (out *GetCurrentAccountOutput, err error) { body, err := c.call("/users/get_current_account", nil) if err != nil { return } defer body.Close() err = json.NewDecoder(body).Decode(&out) return } // GetSpaceUsageOutput request output. type GetSpaceUsageOutput struct { Used uint64 `json:"used"` Allocation struct { Used uint64 `json:"used"` Allocated uint64 `json:"allocated"` } `json:"allocation"` } // GetSpaceUsage returns space usage information for the current user's account. func (c *Users) GetSpaceUsage() (out *GetSpaceUsageOutput, err error) { body, err := c.call("/users/get_space_usage", nil) if err != nil { return } defer body.Close() err = json.NewDecoder(body).Decode(&out) return } ================================================ FILE: users_test.go ================================================ package dropbox import ( "testing" "github.com/stretchr/testify/assert" ) func TestUsers_GetCurrentAccount(t *testing.T) { c := client() _, err := c.Users.GetCurrentAccount() assert.NoError(t, err) }