forked from TrueCloudLab/rclone
vendor: switch to using go1.11 modules
This commit is contained in:
parent
5c75453aba
commit
da1682a30e
6142 changed files with 390 additions and 5155875 deletions
12
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/.gitignore
generated
vendored
12
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/.gitignore
generated
vendored
|
@ -1,12 +0,0 @@
|
|||
# jetbrains
|
||||
.idea
|
||||
|
||||
# swap
|
||||
[._]*.s[a-w][a-z]
|
||||
[._]s[a-w][a-z]
|
||||
|
||||
# emacs backups
|
||||
*~
|
||||
|
||||
.pyc
|
||||
__pycache__
|
3
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/.gitmodules
generated
vendored
3
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/.gitmodules
generated
vendored
|
@ -1,3 +0,0 @@
|
|||
[submodule "generator/dropbox-api-spec"]
|
||||
path = generator/dropbox-api-spec
|
||||
url = https://github.com/dropbox/dropbox-api-spec
|
22
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/.travis.yml
generated
vendored
22
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/.travis.yml
generated
vendored
|
@ -1,22 +0,0 @@
|
|||
language: go
|
||||
|
||||
go:
|
||||
- 1.8.x
|
||||
- 1.9.x
|
||||
- 1.10.x
|
||||
|
||||
install: go get -u golang.org/x/oauth2
|
||||
|
||||
script:
|
||||
- set -e
|
||||
- GOOS=linux GOARCH=amd64 go install ./dropbox/...
|
||||
- GOOS=darwin GOARCH=amd64 go install ./dropbox/...
|
||||
- GOOS=windows GOARCH=amd64 go install ./dropbox/...
|
||||
- set +e
|
||||
|
||||
jobs:
|
||||
include:
|
||||
- stage: run tests
|
||||
go: 1.9.x
|
||||
install: go get -u golang.org/x/oauth2
|
||||
script: go test ./dropbox/...
|
98
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/README.md
generated
vendored
98
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/README.md
generated
vendored
|
@ -1,98 +0,0 @@
|
|||
# Dropbox SDK for Go [UNOFFICIAL] [](https://godoc.org/github.com/dropbox/dropbox-sdk-go-unofficial/dropbox) [](https://travis-ci.org/dropbox/dropbox-sdk-go-unofficial) [](https://goreportcard.com/report/github.com/dropbox/dropbox-sdk-go-unofficial)
|
||||
|
||||
An **UNOFFICIAL** Go SDK for integrating with the Dropbox API v2. Tested with Go 1.5+
|
||||
|
||||
:warning: WARNING: This SDK is **NOT yet official**. What does this mean?
|
||||
|
||||
* There is no formal Dropbox [support](https://www.dropbox.com/developers/support) for this SDK at this point
|
||||
* Bugs may or may not get fixed
|
||||
* Not all SDK features may be implemented and implemented features may be buggy or incorrect
|
||||
|
||||
|
||||
### Uh OK, so why are you releasing this?
|
||||
|
||||
* the SDK, while unofficial, _is_ usable. See [dbxcli](https://github.com/dropbox/dbxcli) for an example application built using the SDK
|
||||
* we would like to get feedback from the community and evaluate the level of interest/enthusiasm before investing into official supporting one more SDK
|
||||
|
||||
## Installation
|
||||
|
||||
```sh
|
||||
$ go get github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/...
|
||||
```
|
||||
|
||||
For most applications, you should just import the relevant namespace(s) only. The SDK exports the following sub-packages:
|
||||
|
||||
* `github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/auth`
|
||||
* `github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/files`
|
||||
* `github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/sharing`
|
||||
* `github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/team`
|
||||
* `github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/users`
|
||||
|
||||
Additionally, the base `github.com/dropbox/dropbox-sdk-go-unofficial/dropbox` package exports some configuration and helper methods.
|
||||
|
||||
## Usage
|
||||
|
||||
First, you need to [register a new "app"](https://dropbox.com/developers/apps) to start making API requests. Once you have created an app, you can either use the SDK via an access token (useful for testing) or via the regular OAuth2 flow (recommended for production).
|
||||
|
||||
### Using OAuth token
|
||||
|
||||
Once you've created an app, you can get an access token from the app's console. Note that this token will only work for the Dropbox account the token is associated with.
|
||||
|
||||
```go
|
||||
import "github.com/dropbox/dropbox-sdk-go-unofficial/dropbox"
|
||||
import "github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/users"
|
||||
|
||||
func main() {
|
||||
config := dropbox.Config{
|
||||
Token: token,
|
||||
LogLevel: dropbox.LogInfo, // if needed, set the desired logging level. Default is off
|
||||
}
|
||||
dbx := users.New(config)
|
||||
// start making API calls
|
||||
}
|
||||
```
|
||||
|
||||
### Using OAuth2 flow
|
||||
|
||||
For this, you will need your `APP_KEY` and `APP_SECRET` from the developers console. Your app will then have to take users though the oauth flow, as part of which users will explicitly grant permissions to your app. At the end of this process, users will get a token that the app can then use for subsequent authentication. See [this](https://godoc.org/golang.org/x/oauth2#example-Config) for an example of oauth2 flow in Go.
|
||||
|
||||
Once you have the token, usage is same as above.
|
||||
|
||||
### Making API calls
|
||||
|
||||
Each Dropbox API takes in a request type and returns a response type. For instance, [/users/get_account](https://www.dropbox.com/developers/documentation/http/documentation#users-get_account) takes as input a `GetAccountArg` and returns a `BasicAccount`. The typical pattern for making API calls is:
|
||||
|
||||
* Instantiate the argument via the `New*` convenience functions in the SDK
|
||||
* Invoke the API
|
||||
* Process the response (or handle error, as below)
|
||||
|
||||
Here's an example:
|
||||
|
||||
```go
|
||||
arg := users.NewGetAccountArg(accountId)
|
||||
if resp, err := dbx.GetAccount(arg); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("Name: %v", resp.Name)
|
||||
```
|
||||
|
||||
### Error Handling
|
||||
|
||||
As described in the [API docs](https://www.dropbox.com/developers/documentation/http/documentation#error-handling), all HTTP errors _except_ 409 are returned as-is to the client (with a helpful text message where possible). In case of a 409, the SDK will return an endpoint-specific error as described in the API. This will be made available as `EndpointError` member in the error.
|
||||
|
||||
## Note on using the Teams API
|
||||
|
||||
To use the Team API, you will need to create a Dropbox Business App. The OAuth token from this app will _only_ work for the Team API.
|
||||
|
||||
Please read the [API docs](https://www.dropbox.com/developers/documentation/http/teams) carefully to appropriate secure your apps and tokens when using the Team API.
|
||||
|
||||
## Code Generation
|
||||
|
||||
This SDK is automatically generated using the public [Dropbox API spec](https://github.com/dropbox/dropbox-api-spec) and [Stone](https://github.com/dropbox/stone). See this [README](https://github.com/dropbox/dropbox-sdk-go-unofficial/blob/master/generator/README.md)
|
||||
for more details on how code is generated.
|
||||
|
||||
## Caveats
|
||||
|
||||
* To re-iterate, this is an **UNOFFICIAL** SDK and thus has no official support from Dropbox
|
||||
* Only supports the v2 API. Parts of the v2 API are still in beta, and thus subject to change
|
||||
* This SDK itself is in beta, and so interfaces may change at any point
|
178
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/auth/client.go
generated
vendored
178
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/auth/client.go
generated
vendored
|
@ -1,178 +0,0 @@
|
|||
// Copyright (c) Dropbox, Inc.
|
||||
//
|
||||
// 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.
|
||||
|
||||
package auth
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
|
||||
"github.com/dropbox/dropbox-sdk-go-unofficial/dropbox"
|
||||
)
|
||||
|
||||
// Client interface describes all routes in this namespace
|
||||
type Client interface {
|
||||
// TokenFromOauth1 : Creates an OAuth 2.0 access token from the supplied
|
||||
// OAuth 1.0 access token.
|
||||
TokenFromOauth1(arg *TokenFromOAuth1Arg) (res *TokenFromOAuth1Result, err error)
|
||||
// TokenRevoke : Disables the access token used to authenticate the call.
|
||||
TokenRevoke() (err error)
|
||||
}
|
||||
|
||||
type apiImpl dropbox.Context
|
||||
|
||||
//TokenFromOauth1APIError is an error-wrapper for the token/from_oauth1 route
|
||||
type TokenFromOauth1APIError struct {
|
||||
dropbox.APIError
|
||||
EndpointError *TokenFromOAuth1Error `json:"error"`
|
||||
}
|
||||
|
||||
func (dbx *apiImpl) TokenFromOauth1(arg *TokenFromOAuth1Arg) (res *TokenFromOAuth1Result, err error) {
|
||||
cli := dbx.Client
|
||||
|
||||
dbx.Config.LogDebug("arg: %v", arg)
|
||||
b, err := json.Marshal(arg)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
headers := map[string]string{
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
if dbx.Config.AsMemberID != "" {
|
||||
headers["Dropbox-API-Select-User"] = dbx.Config.AsMemberID
|
||||
}
|
||||
|
||||
req, err := (*dropbox.Context)(dbx).NewRequest("api", "rpc", true, "auth", "token/from_oauth1", headers, bytes.NewReader(b))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
dbx.Config.LogInfo("req: %v", req)
|
||||
|
||||
resp, err := cli.Do(req)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
dbx.Config.LogInfo("resp: %v", resp)
|
||||
defer resp.Body.Close()
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
dbx.Config.LogDebug("body: %v", body)
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
err = json.Unmarshal(body, &res)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
if resp.StatusCode == http.StatusConflict {
|
||||
var apiError TokenFromOauth1APIError
|
||||
err = json.Unmarshal(body, &apiError)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = apiError
|
||||
return
|
||||
}
|
||||
var apiError dropbox.APIError
|
||||
if resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusInternalServerError {
|
||||
apiError.ErrorSummary = string(body)
|
||||
err = apiError
|
||||
return
|
||||
}
|
||||
err = json.Unmarshal(body, &apiError)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = apiError
|
||||
return
|
||||
}
|
||||
|
||||
//TokenRevokeAPIError is an error-wrapper for the token/revoke route
|
||||
type TokenRevokeAPIError struct {
|
||||
dropbox.APIError
|
||||
EndpointError struct{} `json:"error"`
|
||||
}
|
||||
|
||||
func (dbx *apiImpl) TokenRevoke() (err error) {
|
||||
cli := dbx.Client
|
||||
|
||||
headers := map[string]string{}
|
||||
if dbx.Config.AsMemberID != "" {
|
||||
headers["Dropbox-API-Select-User"] = dbx.Config.AsMemberID
|
||||
}
|
||||
|
||||
req, err := (*dropbox.Context)(dbx).NewRequest("api", "rpc", true, "auth", "token/revoke", headers, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
dbx.Config.LogInfo("req: %v", req)
|
||||
|
||||
resp, err := cli.Do(req)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
dbx.Config.LogInfo("resp: %v", resp)
|
||||
defer resp.Body.Close()
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
dbx.Config.LogDebug("body: %v", body)
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
return
|
||||
}
|
||||
if resp.StatusCode == http.StatusConflict {
|
||||
var apiError TokenRevokeAPIError
|
||||
err = json.Unmarshal(body, &apiError)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = apiError
|
||||
return
|
||||
}
|
||||
var apiError dropbox.APIError
|
||||
if resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusInternalServerError {
|
||||
apiError.ErrorSummary = string(body)
|
||||
err = apiError
|
||||
return
|
||||
}
|
||||
err = json.Unmarshal(body, &apiError)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = apiError
|
||||
return
|
||||
}
|
||||
|
||||
// New returns a Client implementation for this namespace
|
||||
func New(c dropbox.Config) Client {
|
||||
ctx := apiImpl(dropbox.NewContext(c))
|
||||
return &ctx
|
||||
}
|
187
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/auth/types.go
generated
vendored
187
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/auth/types.go
generated
vendored
|
@ -1,187 +0,0 @@
|
|||
// Copyright (c) Dropbox, Inc.
|
||||
//
|
||||
// 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.
|
||||
|
||||
// Package auth : has no documentation (yet)
|
||||
package auth
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/dropbox/dropbox-sdk-go-unofficial/dropbox"
|
||||
)
|
||||
|
||||
// AccessError : Error occurred because the account doesn't have permission to
|
||||
// access the resource.
|
||||
type AccessError struct {
|
||||
dropbox.Tagged
|
||||
// InvalidAccountType : Current account type cannot access the resource.
|
||||
InvalidAccountType *InvalidAccountTypeError `json:"invalid_account_type,omitempty"`
|
||||
// PaperAccessDenied : Current account cannot access Paper.
|
||||
PaperAccessDenied *PaperAccessError `json:"paper_access_denied,omitempty"`
|
||||
}
|
||||
|
||||
// Valid tag values for AccessError
|
||||
const (
|
||||
AccessErrorInvalidAccountType = "invalid_account_type"
|
||||
AccessErrorPaperAccessDenied = "paper_access_denied"
|
||||
AccessErrorOther = "other"
|
||||
)
|
||||
|
||||
// UnmarshalJSON deserializes into a AccessError instance
|
||||
func (u *AccessError) UnmarshalJSON(body []byte) error {
|
||||
type wrap struct {
|
||||
dropbox.Tagged
|
||||
// InvalidAccountType : Current account type cannot access the resource.
|
||||
InvalidAccountType json.RawMessage `json:"invalid_account_type,omitempty"`
|
||||
// PaperAccessDenied : Current account cannot access Paper.
|
||||
PaperAccessDenied json.RawMessage `json:"paper_access_denied,omitempty"`
|
||||
}
|
||||
var w wrap
|
||||
var err error
|
||||
if err = json.Unmarshal(body, &w); err != nil {
|
||||
return err
|
||||
}
|
||||
u.Tag = w.Tag
|
||||
switch u.Tag {
|
||||
case "invalid_account_type":
|
||||
err = json.Unmarshal(w.InvalidAccountType, &u.InvalidAccountType)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
case "paper_access_denied":
|
||||
err = json.Unmarshal(w.PaperAccessDenied, &u.PaperAccessDenied)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// AuthError : Errors occurred during authentication.
|
||||
type AuthError struct {
|
||||
dropbox.Tagged
|
||||
}
|
||||
|
||||
// Valid tag values for AuthError
|
||||
const (
|
||||
AuthErrorInvalidAccessToken = "invalid_access_token"
|
||||
AuthErrorInvalidSelectUser = "invalid_select_user"
|
||||
AuthErrorInvalidSelectAdmin = "invalid_select_admin"
|
||||
AuthErrorUserSuspended = "user_suspended"
|
||||
AuthErrorOther = "other"
|
||||
)
|
||||
|
||||
// InvalidAccountTypeError : has no documentation (yet)
|
||||
type InvalidAccountTypeError struct {
|
||||
dropbox.Tagged
|
||||
}
|
||||
|
||||
// Valid tag values for InvalidAccountTypeError
|
||||
const (
|
||||
InvalidAccountTypeErrorEndpoint = "endpoint"
|
||||
InvalidAccountTypeErrorFeature = "feature"
|
||||
InvalidAccountTypeErrorOther = "other"
|
||||
)
|
||||
|
||||
// PaperAccessError : has no documentation (yet)
|
||||
type PaperAccessError struct {
|
||||
dropbox.Tagged
|
||||
}
|
||||
|
||||
// Valid tag values for PaperAccessError
|
||||
const (
|
||||
PaperAccessErrorPaperDisabled = "paper_disabled"
|
||||
PaperAccessErrorNotPaperUser = "not_paper_user"
|
||||
PaperAccessErrorOther = "other"
|
||||
)
|
||||
|
||||
// RateLimitError : Error occurred because the app is being rate limited.
|
||||
type RateLimitError struct {
|
||||
// Reason : The reason why the app is being rate limited.
|
||||
Reason *RateLimitReason `json:"reason"`
|
||||
// RetryAfter : The number of seconds that the app should wait before making
|
||||
// another request.
|
||||
RetryAfter uint64 `json:"retry_after"`
|
||||
}
|
||||
|
||||
// NewRateLimitError returns a new RateLimitError instance
|
||||
func NewRateLimitError(Reason *RateLimitReason) *RateLimitError {
|
||||
s := new(RateLimitError)
|
||||
s.Reason = Reason
|
||||
s.RetryAfter = 1
|
||||
return s
|
||||
}
|
||||
|
||||
// RateLimitReason : has no documentation (yet)
|
||||
type RateLimitReason struct {
|
||||
dropbox.Tagged
|
||||
}
|
||||
|
||||
// Valid tag values for RateLimitReason
|
||||
const (
|
||||
RateLimitReasonTooManyRequests = "too_many_requests"
|
||||
RateLimitReasonTooManyWriteOperations = "too_many_write_operations"
|
||||
RateLimitReasonOther = "other"
|
||||
)
|
||||
|
||||
// TokenFromOAuth1Arg : has no documentation (yet)
|
||||
type TokenFromOAuth1Arg struct {
|
||||
// Oauth1Token : The supplied OAuth 1.0 access token.
|
||||
Oauth1Token string `json:"oauth1_token"`
|
||||
// Oauth1TokenSecret : The token secret associated with the supplied access
|
||||
// token.
|
||||
Oauth1TokenSecret string `json:"oauth1_token_secret"`
|
||||
}
|
||||
|
||||
// NewTokenFromOAuth1Arg returns a new TokenFromOAuth1Arg instance
|
||||
func NewTokenFromOAuth1Arg(Oauth1Token string, Oauth1TokenSecret string) *TokenFromOAuth1Arg {
|
||||
s := new(TokenFromOAuth1Arg)
|
||||
s.Oauth1Token = Oauth1Token
|
||||
s.Oauth1TokenSecret = Oauth1TokenSecret
|
||||
return s
|
||||
}
|
||||
|
||||
// TokenFromOAuth1Error : has no documentation (yet)
|
||||
type TokenFromOAuth1Error struct {
|
||||
dropbox.Tagged
|
||||
}
|
||||
|
||||
// Valid tag values for TokenFromOAuth1Error
|
||||
const (
|
||||
TokenFromOAuth1ErrorInvalidOauth1TokenInfo = "invalid_oauth1_token_info"
|
||||
TokenFromOAuth1ErrorAppIdMismatch = "app_id_mismatch"
|
||||
TokenFromOAuth1ErrorOther = "other"
|
||||
)
|
||||
|
||||
// TokenFromOAuth1Result : has no documentation (yet)
|
||||
type TokenFromOAuth1Result struct {
|
||||
// Oauth2Token : The OAuth 2.0 token generated from the supplied OAuth 1.0
|
||||
// token.
|
||||
Oauth2Token string `json:"oauth2_token"`
|
||||
}
|
||||
|
||||
// NewTokenFromOAuth1Result returns a new TokenFromOAuth1Result instance
|
||||
func NewTokenFromOAuth1Result(Oauth2Token string) *TokenFromOAuth1Result {
|
||||
s := new(TokenFromOAuth1Result)
|
||||
s.Oauth2Token = Oauth2Token
|
||||
return s
|
||||
}
|
332
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/file_requests/client.go
generated
vendored
332
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/file_requests/client.go
generated
vendored
|
@ -1,332 +0,0 @@
|
|||
// Copyright (c) Dropbox, Inc.
|
||||
//
|
||||
// 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.
|
||||
|
||||
package file_requests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
|
||||
"github.com/dropbox/dropbox-sdk-go-unofficial/dropbox"
|
||||
)
|
||||
|
||||
// Client interface describes all routes in this namespace
|
||||
type Client interface {
|
||||
// Create : Creates a file request for this user.
|
||||
Create(arg *CreateFileRequestArgs) (res *FileRequest, err error)
|
||||
// Get : Returns the specified file request.
|
||||
Get(arg *GetFileRequestArgs) (res *FileRequest, err error)
|
||||
// List : Returns a list of file requests owned by this user. For apps with
|
||||
// the app folder permission, this will only return file requests with
|
||||
// destinations in the app folder.
|
||||
List() (res *ListFileRequestsResult, err error)
|
||||
// Update : Update a file request.
|
||||
Update(arg *UpdateFileRequestArgs) (res *FileRequest, err error)
|
||||
}
|
||||
|
||||
type apiImpl dropbox.Context
|
||||
|
||||
//CreateAPIError is an error-wrapper for the create route
|
||||
type CreateAPIError struct {
|
||||
dropbox.APIError
|
||||
EndpointError *CreateFileRequestError `json:"error"`
|
||||
}
|
||||
|
||||
func (dbx *apiImpl) Create(arg *CreateFileRequestArgs) (res *FileRequest, err error) {
|
||||
cli := dbx.Client
|
||||
|
||||
dbx.Config.LogDebug("arg: %v", arg)
|
||||
b, err := json.Marshal(arg)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
headers := map[string]string{
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
if dbx.Config.AsMemberID != "" {
|
||||
headers["Dropbox-API-Select-User"] = dbx.Config.AsMemberID
|
||||
}
|
||||
|
||||
req, err := (*dropbox.Context)(dbx).NewRequest("api", "rpc", true, "file_requests", "create", headers, bytes.NewReader(b))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
dbx.Config.LogInfo("req: %v", req)
|
||||
|
||||
resp, err := cli.Do(req)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
dbx.Config.LogInfo("resp: %v", resp)
|
||||
defer resp.Body.Close()
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
dbx.Config.LogDebug("body: %v", body)
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
err = json.Unmarshal(body, &res)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
if resp.StatusCode == http.StatusConflict {
|
||||
var apiError CreateAPIError
|
||||
err = json.Unmarshal(body, &apiError)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = apiError
|
||||
return
|
||||
}
|
||||
var apiError dropbox.APIError
|
||||
if resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusInternalServerError {
|
||||
apiError.ErrorSummary = string(body)
|
||||
err = apiError
|
||||
return
|
||||
}
|
||||
err = json.Unmarshal(body, &apiError)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = apiError
|
||||
return
|
||||
}
|
||||
|
||||
//GetAPIError is an error-wrapper for the get route
|
||||
type GetAPIError struct {
|
||||
dropbox.APIError
|
||||
EndpointError *GetFileRequestError `json:"error"`
|
||||
}
|
||||
|
||||
func (dbx *apiImpl) Get(arg *GetFileRequestArgs) (res *FileRequest, err error) {
|
||||
cli := dbx.Client
|
||||
|
||||
dbx.Config.LogDebug("arg: %v", arg)
|
||||
b, err := json.Marshal(arg)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
headers := map[string]string{
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
if dbx.Config.AsMemberID != "" {
|
||||
headers["Dropbox-API-Select-User"] = dbx.Config.AsMemberID
|
||||
}
|
||||
|
||||
req, err := (*dropbox.Context)(dbx).NewRequest("api", "rpc", true, "file_requests", "get", headers, bytes.NewReader(b))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
dbx.Config.LogInfo("req: %v", req)
|
||||
|
||||
resp, err := cli.Do(req)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
dbx.Config.LogInfo("resp: %v", resp)
|
||||
defer resp.Body.Close()
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
dbx.Config.LogDebug("body: %v", body)
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
err = json.Unmarshal(body, &res)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
if resp.StatusCode == http.StatusConflict {
|
||||
var apiError GetAPIError
|
||||
err = json.Unmarshal(body, &apiError)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = apiError
|
||||
return
|
||||
}
|
||||
var apiError dropbox.APIError
|
||||
if resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusInternalServerError {
|
||||
apiError.ErrorSummary = string(body)
|
||||
err = apiError
|
||||
return
|
||||
}
|
||||
err = json.Unmarshal(body, &apiError)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = apiError
|
||||
return
|
||||
}
|
||||
|
||||
//ListAPIError is an error-wrapper for the list route
|
||||
type ListAPIError struct {
|
||||
dropbox.APIError
|
||||
EndpointError *ListFileRequestsError `json:"error"`
|
||||
}
|
||||
|
||||
func (dbx *apiImpl) List() (res *ListFileRequestsResult, err error) {
|
||||
cli := dbx.Client
|
||||
|
||||
headers := map[string]string{}
|
||||
if dbx.Config.AsMemberID != "" {
|
||||
headers["Dropbox-API-Select-User"] = dbx.Config.AsMemberID
|
||||
}
|
||||
|
||||
req, err := (*dropbox.Context)(dbx).NewRequest("api", "rpc", true, "file_requests", "list", headers, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
dbx.Config.LogInfo("req: %v", req)
|
||||
|
||||
resp, err := cli.Do(req)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
dbx.Config.LogInfo("resp: %v", resp)
|
||||
defer resp.Body.Close()
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
dbx.Config.LogDebug("body: %v", body)
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
err = json.Unmarshal(body, &res)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
if resp.StatusCode == http.StatusConflict {
|
||||
var apiError ListAPIError
|
||||
err = json.Unmarshal(body, &apiError)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = apiError
|
||||
return
|
||||
}
|
||||
var apiError dropbox.APIError
|
||||
if resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusInternalServerError {
|
||||
apiError.ErrorSummary = string(body)
|
||||
err = apiError
|
||||
return
|
||||
}
|
||||
err = json.Unmarshal(body, &apiError)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = apiError
|
||||
return
|
||||
}
|
||||
|
||||
//UpdateAPIError is an error-wrapper for the update route
|
||||
type UpdateAPIError struct {
|
||||
dropbox.APIError
|
||||
EndpointError *UpdateFileRequestError `json:"error"`
|
||||
}
|
||||
|
||||
func (dbx *apiImpl) Update(arg *UpdateFileRequestArgs) (res *FileRequest, err error) {
|
||||
cli := dbx.Client
|
||||
|
||||
dbx.Config.LogDebug("arg: %v", arg)
|
||||
b, err := json.Marshal(arg)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
headers := map[string]string{
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
if dbx.Config.AsMemberID != "" {
|
||||
headers["Dropbox-API-Select-User"] = dbx.Config.AsMemberID
|
||||
}
|
||||
|
||||
req, err := (*dropbox.Context)(dbx).NewRequest("api", "rpc", true, "file_requests", "update", headers, bytes.NewReader(b))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
dbx.Config.LogInfo("req: %v", req)
|
||||
|
||||
resp, err := cli.Do(req)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
dbx.Config.LogInfo("resp: %v", resp)
|
||||
defer resp.Body.Close()
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
dbx.Config.LogDebug("body: %v", body)
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
err = json.Unmarshal(body, &res)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
if resp.StatusCode == http.StatusConflict {
|
||||
var apiError UpdateAPIError
|
||||
err = json.Unmarshal(body, &apiError)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = apiError
|
||||
return
|
||||
}
|
||||
var apiError dropbox.APIError
|
||||
if resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusInternalServerError {
|
||||
apiError.ErrorSummary = string(body)
|
||||
err = apiError
|
||||
return
|
||||
}
|
||||
err = json.Unmarshal(body, &apiError)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = apiError
|
||||
return
|
||||
}
|
||||
|
||||
// New returns a Client implementation for this namespace
|
||||
func New(c dropbox.Config) Client {
|
||||
ctx := apiImpl(dropbox.NewContext(c))
|
||||
return &ctx
|
||||
}
|
307
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/file_requests/types.go
generated
vendored
307
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/file_requests/types.go
generated
vendored
|
@ -1,307 +0,0 @@
|
|||
// Copyright (c) Dropbox, Inc.
|
||||
//
|
||||
// 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.
|
||||
|
||||
// Package file_requests : This namespace contains endpoints and data types for
|
||||
// file request operations.
|
||||
package file_requests
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/dropbox/dropbox-sdk-go-unofficial/dropbox"
|
||||
)
|
||||
|
||||
// CreateFileRequestArgs : Arguments for `create`.
|
||||
type CreateFileRequestArgs struct {
|
||||
// Title : The title of the file request. Must not be empty.
|
||||
Title string `json:"title"`
|
||||
// Destination : The path of the folder in the Dropbox where uploaded files
|
||||
// will be sent. For apps with the app folder permission, this will be
|
||||
// relative to the app folder.
|
||||
Destination string `json:"destination"`
|
||||
// Deadline : The deadline for the file request. Deadlines can only be set
|
||||
// by Pro and Business accounts.
|
||||
Deadline *FileRequestDeadline `json:"deadline,omitempty"`
|
||||
// Open : Whether or not the file request should be open. If the file
|
||||
// request is closed, it will not accept any file submissions, but it can be
|
||||
// opened later.
|
||||
Open bool `json:"open"`
|
||||
}
|
||||
|
||||
// NewCreateFileRequestArgs returns a new CreateFileRequestArgs instance
|
||||
func NewCreateFileRequestArgs(Title string, Destination string) *CreateFileRequestArgs {
|
||||
s := new(CreateFileRequestArgs)
|
||||
s.Title = Title
|
||||
s.Destination = Destination
|
||||
s.Open = true
|
||||
return s
|
||||
}
|
||||
|
||||
// GeneralFileRequestsError : There is an error accessing the file requests
|
||||
// functionality.
|
||||
type GeneralFileRequestsError struct {
|
||||
dropbox.Tagged
|
||||
}
|
||||
|
||||
// Valid tag values for GeneralFileRequestsError
|
||||
const (
|
||||
GeneralFileRequestsErrorDisabledForTeam = "disabled_for_team"
|
||||
GeneralFileRequestsErrorOther = "other"
|
||||
)
|
||||
|
||||
// FileRequestError : There is an error with the file request.
|
||||
type FileRequestError struct {
|
||||
dropbox.Tagged
|
||||
}
|
||||
|
||||
// Valid tag values for FileRequestError
|
||||
const (
|
||||
FileRequestErrorDisabledForTeam = "disabled_for_team"
|
||||
FileRequestErrorOther = "other"
|
||||
FileRequestErrorNotFound = "not_found"
|
||||
FileRequestErrorNotAFolder = "not_a_folder"
|
||||
FileRequestErrorAppLacksAccess = "app_lacks_access"
|
||||
FileRequestErrorNoPermission = "no_permission"
|
||||
FileRequestErrorEmailUnverified = "email_unverified"
|
||||
FileRequestErrorValidationError = "validation_error"
|
||||
)
|
||||
|
||||
// CreateFileRequestError : There was an error creating the file request.
|
||||
type CreateFileRequestError struct {
|
||||
dropbox.Tagged
|
||||
}
|
||||
|
||||
// Valid tag values for CreateFileRequestError
|
||||
const (
|
||||
CreateFileRequestErrorDisabledForTeam = "disabled_for_team"
|
||||
CreateFileRequestErrorOther = "other"
|
||||
CreateFileRequestErrorNotFound = "not_found"
|
||||
CreateFileRequestErrorNotAFolder = "not_a_folder"
|
||||
CreateFileRequestErrorAppLacksAccess = "app_lacks_access"
|
||||
CreateFileRequestErrorNoPermission = "no_permission"
|
||||
CreateFileRequestErrorEmailUnverified = "email_unverified"
|
||||
CreateFileRequestErrorValidationError = "validation_error"
|
||||
CreateFileRequestErrorInvalidLocation = "invalid_location"
|
||||
CreateFileRequestErrorRateLimit = "rate_limit"
|
||||
)
|
||||
|
||||
// FileRequest : A `file request` <https://www.dropbox.com/help/9090> for
|
||||
// receiving files into the user's Dropbox account.
|
||||
type FileRequest struct {
|
||||
// Id : The ID of the file request.
|
||||
Id string `json:"id"`
|
||||
// Url : The URL of the file request.
|
||||
Url string `json:"url"`
|
||||
// Title : The title of the file request.
|
||||
Title string `json:"title"`
|
||||
// Destination : The path of the folder in the Dropbox where uploaded files
|
||||
// will be sent. This can be nil if the destination was removed. For apps
|
||||
// with the app folder permission, this will be relative to the app folder.
|
||||
Destination string `json:"destination,omitempty"`
|
||||
// Created : When this file request was created.
|
||||
Created time.Time `json:"created"`
|
||||
// Deadline : The deadline for this file request. Only set if the request
|
||||
// has a deadline.
|
||||
Deadline *FileRequestDeadline `json:"deadline,omitempty"`
|
||||
// IsOpen : Whether or not the file request is open. If the file request is
|
||||
// closed, it will not accept any more file submissions.
|
||||
IsOpen bool `json:"is_open"`
|
||||
// FileCount : The number of files this file request has received.
|
||||
FileCount int64 `json:"file_count"`
|
||||
}
|
||||
|
||||
// NewFileRequest returns a new FileRequest instance
|
||||
func NewFileRequest(Id string, Url string, Title string, Created time.Time, IsOpen bool, FileCount int64) *FileRequest {
|
||||
s := new(FileRequest)
|
||||
s.Id = Id
|
||||
s.Url = Url
|
||||
s.Title = Title
|
||||
s.Created = Created
|
||||
s.IsOpen = IsOpen
|
||||
s.FileCount = FileCount
|
||||
return s
|
||||
}
|
||||
|
||||
// FileRequestDeadline : has no documentation (yet)
|
||||
type FileRequestDeadline struct {
|
||||
// Deadline : The deadline for this file request.
|
||||
Deadline time.Time `json:"deadline"`
|
||||
// AllowLateUploads : If set, allow uploads after the deadline has passed.
|
||||
// These uploads will be marked overdue.
|
||||
AllowLateUploads *GracePeriod `json:"allow_late_uploads,omitempty"`
|
||||
}
|
||||
|
||||
// NewFileRequestDeadline returns a new FileRequestDeadline instance
|
||||
func NewFileRequestDeadline(Deadline time.Time) *FileRequestDeadline {
|
||||
s := new(FileRequestDeadline)
|
||||
s.Deadline = Deadline
|
||||
return s
|
||||
}
|
||||
|
||||
// GetFileRequestArgs : Arguments for `get`.
|
||||
type GetFileRequestArgs struct {
|
||||
// Id : The ID of the file request to retrieve.
|
||||
Id string `json:"id"`
|
||||
}
|
||||
|
||||
// NewGetFileRequestArgs returns a new GetFileRequestArgs instance
|
||||
func NewGetFileRequestArgs(Id string) *GetFileRequestArgs {
|
||||
s := new(GetFileRequestArgs)
|
||||
s.Id = Id
|
||||
return s
|
||||
}
|
||||
|
||||
// GetFileRequestError : There was an error retrieving the specified file
|
||||
// request.
|
||||
type GetFileRequestError struct {
|
||||
dropbox.Tagged
|
||||
}
|
||||
|
||||
// Valid tag values for GetFileRequestError
|
||||
const (
|
||||
GetFileRequestErrorDisabledForTeam = "disabled_for_team"
|
||||
GetFileRequestErrorOther = "other"
|
||||
GetFileRequestErrorNotFound = "not_found"
|
||||
GetFileRequestErrorNotAFolder = "not_a_folder"
|
||||
GetFileRequestErrorAppLacksAccess = "app_lacks_access"
|
||||
GetFileRequestErrorNoPermission = "no_permission"
|
||||
GetFileRequestErrorEmailUnverified = "email_unverified"
|
||||
GetFileRequestErrorValidationError = "validation_error"
|
||||
)
|
||||
|
||||
// GracePeriod : has no documentation (yet)
|
||||
type GracePeriod struct {
|
||||
dropbox.Tagged
|
||||
}
|
||||
|
||||
// Valid tag values for GracePeriod
|
||||
const (
|
||||
GracePeriodOneDay = "one_day"
|
||||
GracePeriodTwoDays = "two_days"
|
||||
GracePeriodSevenDays = "seven_days"
|
||||
GracePeriodThirtyDays = "thirty_days"
|
||||
GracePeriodAlways = "always"
|
||||
GracePeriodOther = "other"
|
||||
)
|
||||
|
||||
// ListFileRequestsError : There was an error retrieving the file requests.
|
||||
type ListFileRequestsError struct {
|
||||
dropbox.Tagged
|
||||
}
|
||||
|
||||
// Valid tag values for ListFileRequestsError
|
||||
const (
|
||||
ListFileRequestsErrorDisabledForTeam = "disabled_for_team"
|
||||
ListFileRequestsErrorOther = "other"
|
||||
)
|
||||
|
||||
// ListFileRequestsResult : Result for `list`.
|
||||
type ListFileRequestsResult struct {
|
||||
// FileRequests : The file requests owned by this user. Apps with the app
|
||||
// folder permission will only see file requests in their app folder.
|
||||
FileRequests []*FileRequest `json:"file_requests"`
|
||||
}
|
||||
|
||||
// NewListFileRequestsResult returns a new ListFileRequestsResult instance
|
||||
func NewListFileRequestsResult(FileRequests []*FileRequest) *ListFileRequestsResult {
|
||||
s := new(ListFileRequestsResult)
|
||||
s.FileRequests = FileRequests
|
||||
return s
|
||||
}
|
||||
|
||||
// UpdateFileRequestArgs : Arguments for `update`.
|
||||
type UpdateFileRequestArgs struct {
|
||||
// Id : The ID of the file request to update.
|
||||
Id string `json:"id"`
|
||||
// Title : The new title of the file request. Must not be empty.
|
||||
Title string `json:"title,omitempty"`
|
||||
// Destination : The new path of the folder in the Dropbox where uploaded
|
||||
// files will be sent. For apps with the app folder permission, this will be
|
||||
// relative to the app folder.
|
||||
Destination string `json:"destination,omitempty"`
|
||||
// Deadline : The new deadline for the file request.
|
||||
Deadline *UpdateFileRequestDeadline `json:"deadline"`
|
||||
// Open : Whether to set this file request as open or closed.
|
||||
Open bool `json:"open,omitempty"`
|
||||
}
|
||||
|
||||
// NewUpdateFileRequestArgs returns a new UpdateFileRequestArgs instance
|
||||
func NewUpdateFileRequestArgs(Id string) *UpdateFileRequestArgs {
|
||||
s := new(UpdateFileRequestArgs)
|
||||
s.Id = Id
|
||||
s.Deadline = &UpdateFileRequestDeadline{Tagged: dropbox.Tagged{"no_update"}}
|
||||
return s
|
||||
}
|
||||
|
||||
// UpdateFileRequestDeadline : has no documentation (yet)
|
||||
type UpdateFileRequestDeadline struct {
|
||||
dropbox.Tagged
|
||||
// Update : If nil, the file request's deadline is cleared.
|
||||
Update *FileRequestDeadline `json:"update,omitempty"`
|
||||
}
|
||||
|
||||
// Valid tag values for UpdateFileRequestDeadline
|
||||
const (
|
||||
UpdateFileRequestDeadlineNoUpdate = "no_update"
|
||||
UpdateFileRequestDeadlineUpdate = "update"
|
||||
UpdateFileRequestDeadlineOther = "other"
|
||||
)
|
||||
|
||||
// UnmarshalJSON deserializes into a UpdateFileRequestDeadline instance
|
||||
func (u *UpdateFileRequestDeadline) UnmarshalJSON(body []byte) error {
|
||||
type wrap struct {
|
||||
dropbox.Tagged
|
||||
// Update : If nil, the file request's deadline is cleared.
|
||||
Update json.RawMessage `json:"update,omitempty"`
|
||||
}
|
||||
var w wrap
|
||||
var err error
|
||||
if err = json.Unmarshal(body, &w); err != nil {
|
||||
return err
|
||||
}
|
||||
u.Tag = w.Tag
|
||||
switch u.Tag {
|
||||
case "update":
|
||||
err = json.Unmarshal(body, &u.Update)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateFileRequestError : There is an error updating the file request.
|
||||
type UpdateFileRequestError struct {
|
||||
dropbox.Tagged
|
||||
}
|
||||
|
||||
// Valid tag values for UpdateFileRequestError
|
||||
const (
|
||||
UpdateFileRequestErrorDisabledForTeam = "disabled_for_team"
|
||||
UpdateFileRequestErrorOther = "other"
|
||||
UpdateFileRequestErrorNotFound = "not_found"
|
||||
UpdateFileRequestErrorNotAFolder = "not_a_folder"
|
||||
UpdateFileRequestErrorAppLacksAccess = "app_lacks_access"
|
||||
UpdateFileRequestErrorNoPermission = "no_permission"
|
||||
UpdateFileRequestErrorEmailUnverified = "email_unverified"
|
||||
UpdateFileRequestErrorValidationError = "validation_error"
|
||||
)
|
1241
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/paper/client.go
generated
vendored
1241
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/paper/client.go
generated
vendored
File diff suppressed because it is too large
Load diff
854
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/paper/types.go
generated
vendored
854
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/paper/types.go
generated
vendored
|
@ -1,854 +0,0 @@
|
|||
// Copyright (c) Dropbox, Inc.
|
||||
//
|
||||
// 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.
|
||||
|
||||
// Package paper : This namespace contains endpoints and data types for managing
|
||||
// docs and folders in Dropbox Paper.
|
||||
package paper
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/dropbox/dropbox-sdk-go-unofficial/dropbox"
|
||||
"github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/sharing"
|
||||
)
|
||||
|
||||
// AddMember : has no documentation (yet)
|
||||
type AddMember struct {
|
||||
// PermissionLevel : Permission for the user.
|
||||
PermissionLevel *PaperDocPermissionLevel `json:"permission_level"`
|
||||
// Member : User which should be added to the Paper doc. Specify only email
|
||||
// address or Dropbox account ID.
|
||||
Member *sharing.MemberSelector `json:"member"`
|
||||
}
|
||||
|
||||
// NewAddMember returns a new AddMember instance
|
||||
func NewAddMember(Member *sharing.MemberSelector) *AddMember {
|
||||
s := new(AddMember)
|
||||
s.Member = Member
|
||||
s.PermissionLevel = &PaperDocPermissionLevel{Tagged: dropbox.Tagged{"edit"}}
|
||||
return s
|
||||
}
|
||||
|
||||
// RefPaperDoc : has no documentation (yet)
|
||||
type RefPaperDoc struct {
|
||||
// DocId : The Paper doc ID.
|
||||
DocId string `json:"doc_id"`
|
||||
}
|
||||
|
||||
// NewRefPaperDoc returns a new RefPaperDoc instance
|
||||
func NewRefPaperDoc(DocId string) *RefPaperDoc {
|
||||
s := new(RefPaperDoc)
|
||||
s.DocId = DocId
|
||||
return s
|
||||
}
|
||||
|
||||
// AddPaperDocUser : has no documentation (yet)
|
||||
type AddPaperDocUser struct {
|
||||
RefPaperDoc
|
||||
// Members : User which should be added to the Paper doc. Specify only email
|
||||
// address or Dropbox account ID.
|
||||
Members []*AddMember `json:"members"`
|
||||
// CustomMessage : A personal message that will be emailed to each
|
||||
// successfully added member.
|
||||
CustomMessage string `json:"custom_message,omitempty"`
|
||||
// Quiet : Clients should set this to true if no email message shall be sent
|
||||
// to added users.
|
||||
Quiet bool `json:"quiet"`
|
||||
}
|
||||
|
||||
// NewAddPaperDocUser returns a new AddPaperDocUser instance
|
||||
func NewAddPaperDocUser(DocId string, Members []*AddMember) *AddPaperDocUser {
|
||||
s := new(AddPaperDocUser)
|
||||
s.DocId = DocId
|
||||
s.Members = Members
|
||||
s.Quiet = false
|
||||
return s
|
||||
}
|
||||
|
||||
// AddPaperDocUserMemberResult : Per-member result for `docsUsersAdd`.
|
||||
type AddPaperDocUserMemberResult struct {
|
||||
// Member : One of specified input members.
|
||||
Member *sharing.MemberSelector `json:"member"`
|
||||
// Result : The outcome of the action on this member.
|
||||
Result *AddPaperDocUserResult `json:"result"`
|
||||
}
|
||||
|
||||
// NewAddPaperDocUserMemberResult returns a new AddPaperDocUserMemberResult instance
|
||||
func NewAddPaperDocUserMemberResult(Member *sharing.MemberSelector, Result *AddPaperDocUserResult) *AddPaperDocUserMemberResult {
|
||||
s := new(AddPaperDocUserMemberResult)
|
||||
s.Member = Member
|
||||
s.Result = Result
|
||||
return s
|
||||
}
|
||||
|
||||
// AddPaperDocUserResult : has no documentation (yet)
|
||||
type AddPaperDocUserResult struct {
|
||||
dropbox.Tagged
|
||||
}
|
||||
|
||||
// Valid tag values for AddPaperDocUserResult
|
||||
const (
|
||||
AddPaperDocUserResultSuccess = "success"
|
||||
AddPaperDocUserResultUnknownError = "unknown_error"
|
||||
AddPaperDocUserResultSharingOutsideTeamDisabled = "sharing_outside_team_disabled"
|
||||
AddPaperDocUserResultDailyLimitReached = "daily_limit_reached"
|
||||
AddPaperDocUserResultUserIsOwner = "user_is_owner"
|
||||
AddPaperDocUserResultFailedUserDataRetrieval = "failed_user_data_retrieval"
|
||||
AddPaperDocUserResultPermissionAlreadyGranted = "permission_already_granted"
|
||||
AddPaperDocUserResultOther = "other"
|
||||
)
|
||||
|
||||
// Cursor : has no documentation (yet)
|
||||
type Cursor struct {
|
||||
// Value : The actual cursor value.
|
||||
Value string `json:"value"`
|
||||
// Expiration : Expiration time of `value`. Some cursors might have
|
||||
// expiration time assigned. This is a UTC value after which the cursor is
|
||||
// no longer valid and the API starts returning an error. If cursor expires
|
||||
// a new one needs to be obtained and pagination needs to be restarted. Some
|
||||
// cursors might be short-lived some cursors might be long-lived. This
|
||||
// really depends on the sorting type and order, e.g.: 1. on one hand,
|
||||
// listing docs created by the user, sorted by the created time ascending
|
||||
// will have undefinite expiration because the results cannot change while
|
||||
// the iteration is happening. This cursor would be suitable for long term
|
||||
// polling. 2. on the other hand, listing docs sorted by the last modified
|
||||
// time will have a very short expiration as docs do get modified very often
|
||||
// and the modified time can be changed while the iteration is happening
|
||||
// thus altering the results.
|
||||
Expiration time.Time `json:"expiration,omitempty"`
|
||||
}
|
||||
|
||||
// NewCursor returns a new Cursor instance
|
||||
func NewCursor(Value string) *Cursor {
|
||||
s := new(Cursor)
|
||||
s.Value = Value
|
||||
return s
|
||||
}
|
||||
|
||||
// PaperApiBaseError : has no documentation (yet)
|
||||
type PaperApiBaseError struct {
|
||||
dropbox.Tagged
|
||||
}
|
||||
|
||||
// Valid tag values for PaperApiBaseError
|
||||
const (
|
||||
PaperApiBaseErrorInsufficientPermissions = "insufficient_permissions"
|
||||
PaperApiBaseErrorOther = "other"
|
||||
)
|
||||
|
||||
// DocLookupError : has no documentation (yet)
|
||||
type DocLookupError struct {
|
||||
dropbox.Tagged
|
||||
}
|
||||
|
||||
// Valid tag values for DocLookupError
|
||||
const (
|
||||
DocLookupErrorInsufficientPermissions = "insufficient_permissions"
|
||||
DocLookupErrorOther = "other"
|
||||
DocLookupErrorDocNotFound = "doc_not_found"
|
||||
)
|
||||
|
||||
// DocSubscriptionLevel : The subscription level of a Paper doc.
|
||||
type DocSubscriptionLevel struct {
|
||||
dropbox.Tagged
|
||||
}
|
||||
|
||||
// Valid tag values for DocSubscriptionLevel
|
||||
const (
|
||||
DocSubscriptionLevelDefault = "default"
|
||||
DocSubscriptionLevelIgnore = "ignore"
|
||||
DocSubscriptionLevelEvery = "every"
|
||||
DocSubscriptionLevelNoEmail = "no_email"
|
||||
)
|
||||
|
||||
// ExportFormat : The desired export format of the Paper doc.
|
||||
type ExportFormat struct {
|
||||
dropbox.Tagged
|
||||
}
|
||||
|
||||
// Valid tag values for ExportFormat
|
||||
const (
|
||||
ExportFormatHtml = "html"
|
||||
ExportFormatMarkdown = "markdown"
|
||||
ExportFormatOther = "other"
|
||||
)
|
||||
|
||||
// Folder : Data structure representing a Paper folder.
|
||||
type Folder struct {
|
||||
// Id : Paper folder ID. This ID uniquely identifies the folder.
|
||||
Id string `json:"id"`
|
||||
// Name : Paper folder name.
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
// NewFolder returns a new Folder instance
|
||||
func NewFolder(Id string, Name string) *Folder {
|
||||
s := new(Folder)
|
||||
s.Id = Id
|
||||
s.Name = Name
|
||||
return s
|
||||
}
|
||||
|
||||
// FolderSharingPolicyType : The sharing policy of a Paper folder. Note: The
|
||||
// sharing policy of subfolders is inherited from the root folder.
|
||||
type FolderSharingPolicyType struct {
|
||||
dropbox.Tagged
|
||||
}
|
||||
|
||||
// Valid tag values for FolderSharingPolicyType
|
||||
const (
|
||||
FolderSharingPolicyTypeTeam = "team"
|
||||
FolderSharingPolicyTypeInviteOnly = "invite_only"
|
||||
)
|
||||
|
||||
// FolderSubscriptionLevel : The subscription level of a Paper folder.
|
||||
type FolderSubscriptionLevel struct {
|
||||
dropbox.Tagged
|
||||
}
|
||||
|
||||
// Valid tag values for FolderSubscriptionLevel
|
||||
const (
|
||||
FolderSubscriptionLevelNone = "none"
|
||||
FolderSubscriptionLevelActivityOnly = "activity_only"
|
||||
FolderSubscriptionLevelDailyEmails = "daily_emails"
|
||||
FolderSubscriptionLevelWeeklyEmails = "weekly_emails"
|
||||
)
|
||||
|
||||
// FoldersContainingPaperDoc : Metadata about Paper folders containing the
|
||||
// specififed Paper doc.
|
||||
type FoldersContainingPaperDoc struct {
|
||||
// FolderSharingPolicyType : The sharing policy of the folder containing the
|
||||
// Paper doc.
|
||||
FolderSharingPolicyType *FolderSharingPolicyType `json:"folder_sharing_policy_type,omitempty"`
|
||||
// Folders : The folder path. If present the first folder is the root
|
||||
// folder.
|
||||
Folders []*Folder `json:"folders,omitempty"`
|
||||
}
|
||||
|
||||
// NewFoldersContainingPaperDoc returns a new FoldersContainingPaperDoc instance
|
||||
func NewFoldersContainingPaperDoc() *FoldersContainingPaperDoc {
|
||||
s := new(FoldersContainingPaperDoc)
|
||||
return s
|
||||
}
|
||||
|
||||
// ImportFormat : The import format of the incoming data.
|
||||
type ImportFormat struct {
|
||||
dropbox.Tagged
|
||||
}
|
||||
|
||||
// Valid tag values for ImportFormat
|
||||
const (
|
||||
ImportFormatHtml = "html"
|
||||
ImportFormatMarkdown = "markdown"
|
||||
ImportFormatPlainText = "plain_text"
|
||||
ImportFormatOther = "other"
|
||||
)
|
||||
|
||||
// InviteeInfoWithPermissionLevel : has no documentation (yet)
|
||||
type InviteeInfoWithPermissionLevel struct {
|
||||
// Invitee : Email address invited to the Paper doc.
|
||||
Invitee *sharing.InviteeInfo `json:"invitee"`
|
||||
// PermissionLevel : Permission level for the invitee.
|
||||
PermissionLevel *PaperDocPermissionLevel `json:"permission_level"`
|
||||
}
|
||||
|
||||
// NewInviteeInfoWithPermissionLevel returns a new InviteeInfoWithPermissionLevel instance
|
||||
func NewInviteeInfoWithPermissionLevel(Invitee *sharing.InviteeInfo, PermissionLevel *PaperDocPermissionLevel) *InviteeInfoWithPermissionLevel {
|
||||
s := new(InviteeInfoWithPermissionLevel)
|
||||
s.Invitee = Invitee
|
||||
s.PermissionLevel = PermissionLevel
|
||||
return s
|
||||
}
|
||||
|
||||
// ListDocsCursorError : has no documentation (yet)
|
||||
type ListDocsCursorError struct {
|
||||
dropbox.Tagged
|
||||
// CursorError : has no documentation (yet)
|
||||
CursorError *PaperApiCursorError `json:"cursor_error,omitempty"`
|
||||
}
|
||||
|
||||
// Valid tag values for ListDocsCursorError
|
||||
const (
|
||||
ListDocsCursorErrorCursorError = "cursor_error"
|
||||
ListDocsCursorErrorOther = "other"
|
||||
)
|
||||
|
||||
// UnmarshalJSON deserializes into a ListDocsCursorError instance
|
||||
func (u *ListDocsCursorError) UnmarshalJSON(body []byte) error {
|
||||
type wrap struct {
|
||||
dropbox.Tagged
|
||||
// CursorError : has no documentation (yet)
|
||||
CursorError json.RawMessage `json:"cursor_error,omitempty"`
|
||||
}
|
||||
var w wrap
|
||||
var err error
|
||||
if err = json.Unmarshal(body, &w); err != nil {
|
||||
return err
|
||||
}
|
||||
u.Tag = w.Tag
|
||||
switch u.Tag {
|
||||
case "cursor_error":
|
||||
err = json.Unmarshal(w.CursorError, &u.CursorError)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListPaperDocsArgs : has no documentation (yet)
|
||||
type ListPaperDocsArgs struct {
|
||||
// FilterBy : Allows user to specify how the Paper docs should be filtered.
|
||||
FilterBy *ListPaperDocsFilterBy `json:"filter_by"`
|
||||
// SortBy : Allows user to specify how the Paper docs should be sorted.
|
||||
SortBy *ListPaperDocsSortBy `json:"sort_by"`
|
||||
// SortOrder : Allows user to specify the sort order of the result.
|
||||
SortOrder *ListPaperDocsSortOrder `json:"sort_order"`
|
||||
// Limit : Size limit per batch. The maximum number of docs that can be
|
||||
// retrieved per batch is 1000. Higher value results in invalid arguments
|
||||
// error.
|
||||
Limit int32 `json:"limit"`
|
||||
}
|
||||
|
||||
// NewListPaperDocsArgs returns a new ListPaperDocsArgs instance
|
||||
func NewListPaperDocsArgs() *ListPaperDocsArgs {
|
||||
s := new(ListPaperDocsArgs)
|
||||
s.FilterBy = &ListPaperDocsFilterBy{Tagged: dropbox.Tagged{"docs_accessed"}}
|
||||
s.SortBy = &ListPaperDocsSortBy{Tagged: dropbox.Tagged{"accessed"}}
|
||||
s.SortOrder = &ListPaperDocsSortOrder{Tagged: dropbox.Tagged{"ascending"}}
|
||||
s.Limit = 1000
|
||||
return s
|
||||
}
|
||||
|
||||
// ListPaperDocsContinueArgs : has no documentation (yet)
|
||||
type ListPaperDocsContinueArgs struct {
|
||||
// Cursor : The cursor obtained from `docsList` or `docsListContinue`.
|
||||
// Allows for pagination.
|
||||
Cursor string `json:"cursor"`
|
||||
}
|
||||
|
||||
// NewListPaperDocsContinueArgs returns a new ListPaperDocsContinueArgs instance
|
||||
func NewListPaperDocsContinueArgs(Cursor string) *ListPaperDocsContinueArgs {
|
||||
s := new(ListPaperDocsContinueArgs)
|
||||
s.Cursor = Cursor
|
||||
return s
|
||||
}
|
||||
|
||||
// ListPaperDocsFilterBy : has no documentation (yet)
|
||||
type ListPaperDocsFilterBy struct {
|
||||
dropbox.Tagged
|
||||
}
|
||||
|
||||
// Valid tag values for ListPaperDocsFilterBy
|
||||
const (
|
||||
ListPaperDocsFilterByDocsAccessed = "docs_accessed"
|
||||
ListPaperDocsFilterByDocsCreated = "docs_created"
|
||||
ListPaperDocsFilterByOther = "other"
|
||||
)
|
||||
|
||||
// ListPaperDocsResponse : has no documentation (yet)
|
||||
type ListPaperDocsResponse struct {
|
||||
// DocIds : The list of Paper doc IDs that can be used to access the given
|
||||
// Paper docs or supplied to other API methods. The list is sorted in the
|
||||
// order specified by the initial call to `docsList`.
|
||||
DocIds []string `json:"doc_ids"`
|
||||
// Cursor : Pass the cursor into `docsListContinue` to paginate through all
|
||||
// files. The cursor preserves all properties as specified in the original
|
||||
// call to `docsList`.
|
||||
Cursor *Cursor `json:"cursor"`
|
||||
// HasMore : Will be set to True if a subsequent call with the provided
|
||||
// cursor to `docsListContinue` returns immediately with some results. If
|
||||
// set to False please allow some delay before making another call to
|
||||
// `docsListContinue`.
|
||||
HasMore bool `json:"has_more"`
|
||||
}
|
||||
|
||||
// NewListPaperDocsResponse returns a new ListPaperDocsResponse instance
|
||||
func NewListPaperDocsResponse(DocIds []string, Cursor *Cursor, HasMore bool) *ListPaperDocsResponse {
|
||||
s := new(ListPaperDocsResponse)
|
||||
s.DocIds = DocIds
|
||||
s.Cursor = Cursor
|
||||
s.HasMore = HasMore
|
||||
return s
|
||||
}
|
||||
|
||||
// ListPaperDocsSortBy : has no documentation (yet)
|
||||
type ListPaperDocsSortBy struct {
|
||||
dropbox.Tagged
|
||||
}
|
||||
|
||||
// Valid tag values for ListPaperDocsSortBy
|
||||
const (
|
||||
ListPaperDocsSortByAccessed = "accessed"
|
||||
ListPaperDocsSortByModified = "modified"
|
||||
ListPaperDocsSortByCreated = "created"
|
||||
ListPaperDocsSortByOther = "other"
|
||||
)
|
||||
|
||||
// ListPaperDocsSortOrder : has no documentation (yet)
|
||||
type ListPaperDocsSortOrder struct {
|
||||
dropbox.Tagged
|
||||
}
|
||||
|
||||
// Valid tag values for ListPaperDocsSortOrder
|
||||
const (
|
||||
ListPaperDocsSortOrderAscending = "ascending"
|
||||
ListPaperDocsSortOrderDescending = "descending"
|
||||
ListPaperDocsSortOrderOther = "other"
|
||||
)
|
||||
|
||||
// ListUsersCursorError : has no documentation (yet)
|
||||
type ListUsersCursorError struct {
|
||||
dropbox.Tagged
|
||||
// CursorError : has no documentation (yet)
|
||||
CursorError *PaperApiCursorError `json:"cursor_error,omitempty"`
|
||||
}
|
||||
|
||||
// Valid tag values for ListUsersCursorError
|
||||
const (
|
||||
ListUsersCursorErrorInsufficientPermissions = "insufficient_permissions"
|
||||
ListUsersCursorErrorOther = "other"
|
||||
ListUsersCursorErrorDocNotFound = "doc_not_found"
|
||||
ListUsersCursorErrorCursorError = "cursor_error"
|
||||
)
|
||||
|
||||
// UnmarshalJSON deserializes into a ListUsersCursorError instance
|
||||
func (u *ListUsersCursorError) UnmarshalJSON(body []byte) error {
|
||||
type wrap struct {
|
||||
dropbox.Tagged
|
||||
// CursorError : has no documentation (yet)
|
||||
CursorError json.RawMessage `json:"cursor_error,omitempty"`
|
||||
}
|
||||
var w wrap
|
||||
var err error
|
||||
if err = json.Unmarshal(body, &w); err != nil {
|
||||
return err
|
||||
}
|
||||
u.Tag = w.Tag
|
||||
switch u.Tag {
|
||||
case "cursor_error":
|
||||
err = json.Unmarshal(w.CursorError, &u.CursorError)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListUsersOnFolderArgs : has no documentation (yet)
|
||||
type ListUsersOnFolderArgs struct {
|
||||
RefPaperDoc
|
||||
// Limit : Size limit per batch. The maximum number of users that can be
|
||||
// retrieved per batch is 1000. Higher value results in invalid arguments
|
||||
// error.
|
||||
Limit int32 `json:"limit"`
|
||||
}
|
||||
|
||||
// NewListUsersOnFolderArgs returns a new ListUsersOnFolderArgs instance
|
||||
func NewListUsersOnFolderArgs(DocId string) *ListUsersOnFolderArgs {
|
||||
s := new(ListUsersOnFolderArgs)
|
||||
s.DocId = DocId
|
||||
s.Limit = 1000
|
||||
return s
|
||||
}
|
||||
|
||||
// ListUsersOnFolderContinueArgs : has no documentation (yet)
|
||||
type ListUsersOnFolderContinueArgs struct {
|
||||
RefPaperDoc
|
||||
// Cursor : The cursor obtained from `docsFolderUsersList` or
|
||||
// `docsFolderUsersListContinue`. Allows for pagination.
|
||||
Cursor string `json:"cursor"`
|
||||
}
|
||||
|
||||
// NewListUsersOnFolderContinueArgs returns a new ListUsersOnFolderContinueArgs instance
|
||||
func NewListUsersOnFolderContinueArgs(DocId string, Cursor string) *ListUsersOnFolderContinueArgs {
|
||||
s := new(ListUsersOnFolderContinueArgs)
|
||||
s.DocId = DocId
|
||||
s.Cursor = Cursor
|
||||
return s
|
||||
}
|
||||
|
||||
// ListUsersOnFolderResponse : has no documentation (yet)
|
||||
type ListUsersOnFolderResponse struct {
|
||||
// Invitees : List of email addresses that are invited on the Paper folder.
|
||||
Invitees []*sharing.InviteeInfo `json:"invitees"`
|
||||
// Users : List of users that are invited on the Paper folder.
|
||||
Users []*sharing.UserInfo `json:"users"`
|
||||
// Cursor : Pass the cursor into `docsFolderUsersListContinue` to paginate
|
||||
// through all users. The cursor preserves all properties as specified in
|
||||
// the original call to `docsFolderUsersList`.
|
||||
Cursor *Cursor `json:"cursor"`
|
||||
// HasMore : Will be set to True if a subsequent call with the provided
|
||||
// cursor to `docsFolderUsersListContinue` returns immediately with some
|
||||
// results. If set to False please allow some delay before making another
|
||||
// call to `docsFolderUsersListContinue`.
|
||||
HasMore bool `json:"has_more"`
|
||||
}
|
||||
|
||||
// NewListUsersOnFolderResponse returns a new ListUsersOnFolderResponse instance
|
||||
func NewListUsersOnFolderResponse(Invitees []*sharing.InviteeInfo, Users []*sharing.UserInfo, Cursor *Cursor, HasMore bool) *ListUsersOnFolderResponse {
|
||||
s := new(ListUsersOnFolderResponse)
|
||||
s.Invitees = Invitees
|
||||
s.Users = Users
|
||||
s.Cursor = Cursor
|
||||
s.HasMore = HasMore
|
||||
return s
|
||||
}
|
||||
|
||||
// ListUsersOnPaperDocArgs : has no documentation (yet)
|
||||
type ListUsersOnPaperDocArgs struct {
|
||||
RefPaperDoc
|
||||
// Limit : Size limit per batch. The maximum number of users that can be
|
||||
// retrieved per batch is 1000. Higher value results in invalid arguments
|
||||
// error.
|
||||
Limit int32 `json:"limit"`
|
||||
// FilterBy : Specify this attribute if you want to obtain users that have
|
||||
// already accessed the Paper doc.
|
||||
FilterBy *UserOnPaperDocFilter `json:"filter_by"`
|
||||
}
|
||||
|
||||
// NewListUsersOnPaperDocArgs returns a new ListUsersOnPaperDocArgs instance
|
||||
func NewListUsersOnPaperDocArgs(DocId string) *ListUsersOnPaperDocArgs {
|
||||
s := new(ListUsersOnPaperDocArgs)
|
||||
s.DocId = DocId
|
||||
s.Limit = 1000
|
||||
s.FilterBy = &UserOnPaperDocFilter{Tagged: dropbox.Tagged{"shared"}}
|
||||
return s
|
||||
}
|
||||
|
||||
// ListUsersOnPaperDocContinueArgs : has no documentation (yet)
|
||||
type ListUsersOnPaperDocContinueArgs struct {
|
||||
RefPaperDoc
|
||||
// Cursor : The cursor obtained from `docsUsersList` or
|
||||
// `docsUsersListContinue`. Allows for pagination.
|
||||
Cursor string `json:"cursor"`
|
||||
}
|
||||
|
||||
// NewListUsersOnPaperDocContinueArgs returns a new ListUsersOnPaperDocContinueArgs instance
|
||||
func NewListUsersOnPaperDocContinueArgs(DocId string, Cursor string) *ListUsersOnPaperDocContinueArgs {
|
||||
s := new(ListUsersOnPaperDocContinueArgs)
|
||||
s.DocId = DocId
|
||||
s.Cursor = Cursor
|
||||
return s
|
||||
}
|
||||
|
||||
// ListUsersOnPaperDocResponse : has no documentation (yet)
|
||||
type ListUsersOnPaperDocResponse struct {
|
||||
// Invitees : List of email addresses with their respective permission
|
||||
// levels that are invited on the Paper doc.
|
||||
Invitees []*InviteeInfoWithPermissionLevel `json:"invitees"`
|
||||
// Users : List of users with their respective permission levels that are
|
||||
// invited on the Paper folder.
|
||||
Users []*UserInfoWithPermissionLevel `json:"users"`
|
||||
// DocOwner : The Paper doc owner. This field is populated on every single
|
||||
// response.
|
||||
DocOwner *sharing.UserInfo `json:"doc_owner"`
|
||||
// Cursor : Pass the cursor into `docsUsersListContinue` to paginate through
|
||||
// all users. The cursor preserves all properties as specified in the
|
||||
// original call to `docsUsersList`.
|
||||
Cursor *Cursor `json:"cursor"`
|
||||
// HasMore : Will be set to True if a subsequent call with the provided
|
||||
// cursor to `docsUsersListContinue` returns immediately with some results.
|
||||
// If set to False please allow some delay before making another call to
|
||||
// `docsUsersListContinue`.
|
||||
HasMore bool `json:"has_more"`
|
||||
}
|
||||
|
||||
// NewListUsersOnPaperDocResponse returns a new ListUsersOnPaperDocResponse instance
|
||||
func NewListUsersOnPaperDocResponse(Invitees []*InviteeInfoWithPermissionLevel, Users []*UserInfoWithPermissionLevel, DocOwner *sharing.UserInfo, Cursor *Cursor, HasMore bool) *ListUsersOnPaperDocResponse {
|
||||
s := new(ListUsersOnPaperDocResponse)
|
||||
s.Invitees = Invitees
|
||||
s.Users = Users
|
||||
s.DocOwner = DocOwner
|
||||
s.Cursor = Cursor
|
||||
s.HasMore = HasMore
|
||||
return s
|
||||
}
|
||||
|
||||
// PaperApiCursorError : has no documentation (yet)
|
||||
type PaperApiCursorError struct {
|
||||
dropbox.Tagged
|
||||
}
|
||||
|
||||
// Valid tag values for PaperApiCursorError
|
||||
const (
|
||||
PaperApiCursorErrorExpiredCursor = "expired_cursor"
|
||||
PaperApiCursorErrorInvalidCursor = "invalid_cursor"
|
||||
PaperApiCursorErrorWrongUserInCursor = "wrong_user_in_cursor"
|
||||
PaperApiCursorErrorReset = "reset"
|
||||
PaperApiCursorErrorOther = "other"
|
||||
)
|
||||
|
||||
// PaperDocCreateArgs : has no documentation (yet)
|
||||
type PaperDocCreateArgs struct {
|
||||
// ParentFolderId : The Paper folder ID where the Paper document should be
|
||||
// created. The API user has to have write access to this folder or error is
|
||||
// thrown.
|
||||
ParentFolderId string `json:"parent_folder_id,omitempty"`
|
||||
// ImportFormat : The format of provided data.
|
||||
ImportFormat *ImportFormat `json:"import_format"`
|
||||
}
|
||||
|
||||
// NewPaperDocCreateArgs returns a new PaperDocCreateArgs instance
|
||||
func NewPaperDocCreateArgs(ImportFormat *ImportFormat) *PaperDocCreateArgs {
|
||||
s := new(PaperDocCreateArgs)
|
||||
s.ImportFormat = ImportFormat
|
||||
return s
|
||||
}
|
||||
|
||||
// PaperDocCreateError : has no documentation (yet)
|
||||
type PaperDocCreateError struct {
|
||||
dropbox.Tagged
|
||||
}
|
||||
|
||||
// Valid tag values for PaperDocCreateError
|
||||
const (
|
||||
PaperDocCreateErrorInsufficientPermissions = "insufficient_permissions"
|
||||
PaperDocCreateErrorOther = "other"
|
||||
PaperDocCreateErrorContentMalformed = "content_malformed"
|
||||
PaperDocCreateErrorFolderNotFound = "folder_not_found"
|
||||
PaperDocCreateErrorDocLengthExceeded = "doc_length_exceeded"
|
||||
PaperDocCreateErrorImageSizeExceeded = "image_size_exceeded"
|
||||
)
|
||||
|
||||
// PaperDocCreateUpdateResult : has no documentation (yet)
|
||||
type PaperDocCreateUpdateResult struct {
|
||||
// DocId : Doc ID of the newly created doc.
|
||||
DocId string `json:"doc_id"`
|
||||
// Revision : The Paper doc revision. Simply an ever increasing number.
|
||||
Revision int64 `json:"revision"`
|
||||
// Title : The Paper doc title.
|
||||
Title string `json:"title"`
|
||||
}
|
||||
|
||||
// NewPaperDocCreateUpdateResult returns a new PaperDocCreateUpdateResult instance
|
||||
func NewPaperDocCreateUpdateResult(DocId string, Revision int64, Title string) *PaperDocCreateUpdateResult {
|
||||
s := new(PaperDocCreateUpdateResult)
|
||||
s.DocId = DocId
|
||||
s.Revision = Revision
|
||||
s.Title = Title
|
||||
return s
|
||||
}
|
||||
|
||||
// PaperDocExport : has no documentation (yet)
|
||||
type PaperDocExport struct {
|
||||
RefPaperDoc
|
||||
// ExportFormat : has no documentation (yet)
|
||||
ExportFormat *ExportFormat `json:"export_format"`
|
||||
}
|
||||
|
||||
// NewPaperDocExport returns a new PaperDocExport instance
|
||||
func NewPaperDocExport(DocId string, ExportFormat *ExportFormat) *PaperDocExport {
|
||||
s := new(PaperDocExport)
|
||||
s.DocId = DocId
|
||||
s.ExportFormat = ExportFormat
|
||||
return s
|
||||
}
|
||||
|
||||
// PaperDocExportResult : has no documentation (yet)
|
||||
type PaperDocExportResult struct {
|
||||
// Owner : The Paper doc owner's email address.
|
||||
Owner string `json:"owner"`
|
||||
// Title : The Paper doc title.
|
||||
Title string `json:"title"`
|
||||
// Revision : The Paper doc revision. Simply an ever increasing number.
|
||||
Revision int64 `json:"revision"`
|
||||
// MimeType : MIME type of the export. This corresponds to `ExportFormat`
|
||||
// specified in the request.
|
||||
MimeType string `json:"mime_type"`
|
||||
}
|
||||
|
||||
// NewPaperDocExportResult returns a new PaperDocExportResult instance
|
||||
func NewPaperDocExportResult(Owner string, Title string, Revision int64, MimeType string) *PaperDocExportResult {
|
||||
s := new(PaperDocExportResult)
|
||||
s.Owner = Owner
|
||||
s.Title = Title
|
||||
s.Revision = Revision
|
||||
s.MimeType = MimeType
|
||||
return s
|
||||
}
|
||||
|
||||
// PaperDocPermissionLevel : has no documentation (yet)
|
||||
type PaperDocPermissionLevel struct {
|
||||
dropbox.Tagged
|
||||
}
|
||||
|
||||
// Valid tag values for PaperDocPermissionLevel
|
||||
const (
|
||||
PaperDocPermissionLevelEdit = "edit"
|
||||
PaperDocPermissionLevelViewAndComment = "view_and_comment"
|
||||
PaperDocPermissionLevelOther = "other"
|
||||
)
|
||||
|
||||
// PaperDocSharingPolicy : has no documentation (yet)
|
||||
type PaperDocSharingPolicy struct {
|
||||
RefPaperDoc
|
||||
// SharingPolicy : The default sharing policy to be set for the Paper doc.
|
||||
SharingPolicy *SharingPolicy `json:"sharing_policy"`
|
||||
}
|
||||
|
||||
// NewPaperDocSharingPolicy returns a new PaperDocSharingPolicy instance
|
||||
func NewPaperDocSharingPolicy(DocId string, SharingPolicy *SharingPolicy) *PaperDocSharingPolicy {
|
||||
s := new(PaperDocSharingPolicy)
|
||||
s.DocId = DocId
|
||||
s.SharingPolicy = SharingPolicy
|
||||
return s
|
||||
}
|
||||
|
||||
// PaperDocUpdateArgs : has no documentation (yet)
|
||||
type PaperDocUpdateArgs struct {
|
||||
RefPaperDoc
|
||||
// DocUpdatePolicy : The policy used for the current update call.
|
||||
DocUpdatePolicy *PaperDocUpdatePolicy `json:"doc_update_policy"`
|
||||
// Revision : The latest doc revision. This value must match the head
|
||||
// revision or an error code will be returned. This is to prevent colliding
|
||||
// writes.
|
||||
Revision int64 `json:"revision"`
|
||||
// ImportFormat : The format of provided data.
|
||||
ImportFormat *ImportFormat `json:"import_format"`
|
||||
}
|
||||
|
||||
// NewPaperDocUpdateArgs returns a new PaperDocUpdateArgs instance
|
||||
func NewPaperDocUpdateArgs(DocId string, DocUpdatePolicy *PaperDocUpdatePolicy, Revision int64, ImportFormat *ImportFormat) *PaperDocUpdateArgs {
|
||||
s := new(PaperDocUpdateArgs)
|
||||
s.DocId = DocId
|
||||
s.DocUpdatePolicy = DocUpdatePolicy
|
||||
s.Revision = Revision
|
||||
s.ImportFormat = ImportFormat
|
||||
return s
|
||||
}
|
||||
|
||||
// PaperDocUpdateError : has no documentation (yet)
|
||||
type PaperDocUpdateError struct {
|
||||
dropbox.Tagged
|
||||
}
|
||||
|
||||
// Valid tag values for PaperDocUpdateError
|
||||
const (
|
||||
PaperDocUpdateErrorInsufficientPermissions = "insufficient_permissions"
|
||||
PaperDocUpdateErrorOther = "other"
|
||||
PaperDocUpdateErrorDocNotFound = "doc_not_found"
|
||||
PaperDocUpdateErrorContentMalformed = "content_malformed"
|
||||
PaperDocUpdateErrorRevisionMismatch = "revision_mismatch"
|
||||
PaperDocUpdateErrorDocLengthExceeded = "doc_length_exceeded"
|
||||
PaperDocUpdateErrorImageSizeExceeded = "image_size_exceeded"
|
||||
PaperDocUpdateErrorDocArchived = "doc_archived"
|
||||
PaperDocUpdateErrorDocDeleted = "doc_deleted"
|
||||
)
|
||||
|
||||
// PaperDocUpdatePolicy : has no documentation (yet)
|
||||
type PaperDocUpdatePolicy struct {
|
||||
dropbox.Tagged
|
||||
}
|
||||
|
||||
// Valid tag values for PaperDocUpdatePolicy
|
||||
const (
|
||||
PaperDocUpdatePolicyAppend = "append"
|
||||
PaperDocUpdatePolicyPrepend = "prepend"
|
||||
PaperDocUpdatePolicyOverwriteAll = "overwrite_all"
|
||||
PaperDocUpdatePolicyOther = "other"
|
||||
)
|
||||
|
||||
// RemovePaperDocUser : has no documentation (yet)
|
||||
type RemovePaperDocUser struct {
|
||||
RefPaperDoc
|
||||
// Member : User which should be removed from the Paper doc. Specify only
|
||||
// email address or Dropbox account ID.
|
||||
Member *sharing.MemberSelector `json:"member"`
|
||||
}
|
||||
|
||||
// NewRemovePaperDocUser returns a new RemovePaperDocUser instance
|
||||
func NewRemovePaperDocUser(DocId string, Member *sharing.MemberSelector) *RemovePaperDocUser {
|
||||
s := new(RemovePaperDocUser)
|
||||
s.DocId = DocId
|
||||
s.Member = Member
|
||||
return s
|
||||
}
|
||||
|
||||
// SharingPolicy : Sharing policy of Paper doc.
|
||||
type SharingPolicy struct {
|
||||
// PublicSharingPolicy : This value applies to the non-team members.
|
||||
PublicSharingPolicy *SharingPublicPolicyType `json:"public_sharing_policy,omitempty"`
|
||||
// TeamSharingPolicy : This value applies to the team members only. The
|
||||
// value is null for all personal accounts.
|
||||
TeamSharingPolicy *SharingTeamPolicyType `json:"team_sharing_policy,omitempty"`
|
||||
}
|
||||
|
||||
// NewSharingPolicy returns a new SharingPolicy instance
|
||||
func NewSharingPolicy() *SharingPolicy {
|
||||
s := new(SharingPolicy)
|
||||
return s
|
||||
}
|
||||
|
||||
// SharingTeamPolicyType : The sharing policy type of the Paper doc.
|
||||
type SharingTeamPolicyType struct {
|
||||
dropbox.Tagged
|
||||
}
|
||||
|
||||
// Valid tag values for SharingTeamPolicyType
|
||||
const (
|
||||
SharingTeamPolicyTypePeopleWithLinkCanEdit = "people_with_link_can_edit"
|
||||
SharingTeamPolicyTypePeopleWithLinkCanViewAndComment = "people_with_link_can_view_and_comment"
|
||||
SharingTeamPolicyTypeInviteOnly = "invite_only"
|
||||
)
|
||||
|
||||
// SharingPublicPolicyType : has no documentation (yet)
|
||||
type SharingPublicPolicyType struct {
|
||||
dropbox.Tagged
|
||||
}
|
||||
|
||||
// Valid tag values for SharingPublicPolicyType
|
||||
const (
|
||||
SharingPublicPolicyTypePeopleWithLinkCanEdit = "people_with_link_can_edit"
|
||||
SharingPublicPolicyTypePeopleWithLinkCanViewAndComment = "people_with_link_can_view_and_comment"
|
||||
SharingPublicPolicyTypeInviteOnly = "invite_only"
|
||||
SharingPublicPolicyTypeDisabled = "disabled"
|
||||
)
|
||||
|
||||
// UserInfoWithPermissionLevel : has no documentation (yet)
|
||||
type UserInfoWithPermissionLevel struct {
|
||||
// User : User shared on the Paper doc.
|
||||
User *sharing.UserInfo `json:"user"`
|
||||
// PermissionLevel : Permission level for the user.
|
||||
PermissionLevel *PaperDocPermissionLevel `json:"permission_level"`
|
||||
}
|
||||
|
||||
// NewUserInfoWithPermissionLevel returns a new UserInfoWithPermissionLevel instance
|
||||
func NewUserInfoWithPermissionLevel(User *sharing.UserInfo, PermissionLevel *PaperDocPermissionLevel) *UserInfoWithPermissionLevel {
|
||||
s := new(UserInfoWithPermissionLevel)
|
||||
s.User = User
|
||||
s.PermissionLevel = PermissionLevel
|
||||
return s
|
||||
}
|
||||
|
||||
// UserOnPaperDocFilter : has no documentation (yet)
|
||||
type UserOnPaperDocFilter struct {
|
||||
dropbox.Tagged
|
||||
}
|
||||
|
||||
// Valid tag values for UserOnPaperDocFilter
|
||||
const (
|
||||
UserOnPaperDocFilterVisited = "visited"
|
||||
UserOnPaperDocFilterShared = "shared"
|
||||
UserOnPaperDocFilterOther = "other"
|
||||
)
|
55
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/sdk_test.go
generated
vendored
55
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/sdk_test.go
generated
vendored
|
@ -1,55 +0,0 @@
|
|||
// Copyright (c) Dropbox, Inc.
|
||||
//
|
||||
// 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.
|
||||
|
||||
package dropbox_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/dropbox/dropbox-sdk-go-unofficial/dropbox"
|
||||
"github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/users"
|
||||
)
|
||||
|
||||
func generateURL(base string, namespace string, route string) string {
|
||||
return fmt.Sprintf("%s/%s/%s", base, namespace, route)
|
||||
}
|
||||
|
||||
func TestInternalError(t *testing.T) {
|
||||
eString := "internal server error"
|
||||
ts := httptest.NewServer(http.HandlerFunc(
|
||||
func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, eString, http.StatusInternalServerError)
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
config := dropbox.Config{Client: ts.Client(), LogLevel: dropbox.LogDebug,
|
||||
URLGenerator: func(hostType string, style string, namespace string, route string) string {
|
||||
return generateURL(ts.URL, namespace, route)
|
||||
}}
|
||||
client := users.New(config)
|
||||
v, e := client.GetCurrentAccount()
|
||||
if v != nil || strings.Trim(e.Error(), "\n") != eString {
|
||||
t.Errorf("v: %v e: '%s'\n", v, e.Error())
|
||||
}
|
||||
}
|
4730
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/team/client.go
generated
vendored
4730
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/team/client.go
generated
vendored
File diff suppressed because it is too large
Load diff
4242
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/team/types.go
generated
vendored
4242
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/team/types.go
generated
vendored
File diff suppressed because it is too large
Load diff
192
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/team_log/client.go
generated
vendored
192
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/team_log/client.go
generated
vendored
|
@ -1,192 +0,0 @@
|
|||
// Copyright (c) Dropbox, Inc.
|
||||
//
|
||||
// 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.
|
||||
|
||||
package team_log
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
|
||||
"github.com/dropbox/dropbox-sdk-go-unofficial/dropbox"
|
||||
)
|
||||
|
||||
// Client interface describes all routes in this namespace
|
||||
type Client interface {
|
||||
// GetEvents : Retrieves team events. Events have a lifespan of two years.
|
||||
// Events older than two years will not be returned. Many attributes note
|
||||
// 'may be missing due to historical data gap'. Note that the
|
||||
// file_operations category and & analogous paper events are not available
|
||||
// on all Dropbox Business `plans` </business/plans-comparison>. Use
|
||||
// `features/get_values`
|
||||
// </developers/documentation/http/teams#team-features-get_values> to check
|
||||
// for this feature. Permission : Team Auditing.
|
||||
GetEvents(arg *GetTeamEventsArg) (res *GetTeamEventsResult, err error)
|
||||
// GetEventsContinue : Once a cursor has been retrieved from `getEvents`,
|
||||
// use this to paginate through all events. Permission : Team Auditing.
|
||||
GetEventsContinue(arg *GetTeamEventsContinueArg) (res *GetTeamEventsResult, err error)
|
||||
}
|
||||
|
||||
type apiImpl dropbox.Context
|
||||
|
||||
//GetEventsAPIError is an error-wrapper for the get_events route
|
||||
type GetEventsAPIError struct {
|
||||
dropbox.APIError
|
||||
EndpointError *GetTeamEventsError `json:"error"`
|
||||
}
|
||||
|
||||
func (dbx *apiImpl) GetEvents(arg *GetTeamEventsArg) (res *GetTeamEventsResult, err error) {
|
||||
cli := dbx.Client
|
||||
|
||||
dbx.Config.LogDebug("arg: %v", arg)
|
||||
b, err := json.Marshal(arg)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
headers := map[string]string{
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
req, err := (*dropbox.Context)(dbx).NewRequest("api", "rpc", true, "team_log", "get_events", headers, bytes.NewReader(b))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
dbx.Config.LogInfo("req: %v", req)
|
||||
|
||||
resp, err := cli.Do(req)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
dbx.Config.LogInfo("resp: %v", resp)
|
||||
defer resp.Body.Close()
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
dbx.Config.LogDebug("body: %v", body)
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
err = json.Unmarshal(body, &res)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
if resp.StatusCode == http.StatusConflict {
|
||||
var apiError GetEventsAPIError
|
||||
err = json.Unmarshal(body, &apiError)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = apiError
|
||||
return
|
||||
}
|
||||
var apiError dropbox.APIError
|
||||
if resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusInternalServerError {
|
||||
apiError.ErrorSummary = string(body)
|
||||
err = apiError
|
||||
return
|
||||
}
|
||||
err = json.Unmarshal(body, &apiError)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = apiError
|
||||
return
|
||||
}
|
||||
|
||||
//GetEventsContinueAPIError is an error-wrapper for the get_events/continue route
|
||||
type GetEventsContinueAPIError struct {
|
||||
dropbox.APIError
|
||||
EndpointError *GetTeamEventsContinueError `json:"error"`
|
||||
}
|
||||
|
||||
func (dbx *apiImpl) GetEventsContinue(arg *GetTeamEventsContinueArg) (res *GetTeamEventsResult, err error) {
|
||||
cli := dbx.Client
|
||||
|
||||
dbx.Config.LogDebug("arg: %v", arg)
|
||||
b, err := json.Marshal(arg)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
headers := map[string]string{
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
req, err := (*dropbox.Context)(dbx).NewRequest("api", "rpc", true, "team_log", "get_events/continue", headers, bytes.NewReader(b))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
dbx.Config.LogInfo("req: %v", req)
|
||||
|
||||
resp, err := cli.Do(req)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
dbx.Config.LogInfo("resp: %v", resp)
|
||||
defer resp.Body.Close()
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
dbx.Config.LogDebug("body: %v", body)
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
err = json.Unmarshal(body, &res)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
if resp.StatusCode == http.StatusConflict {
|
||||
var apiError GetEventsContinueAPIError
|
||||
err = json.Unmarshal(body, &apiError)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = apiError
|
||||
return
|
||||
}
|
||||
var apiError dropbox.APIError
|
||||
if resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusInternalServerError {
|
||||
apiError.ErrorSummary = string(body)
|
||||
err = apiError
|
||||
return
|
||||
}
|
||||
err = json.Unmarshal(body, &apiError)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = apiError
|
||||
return
|
||||
}
|
||||
|
||||
// New returns a Client implementation for this namespace
|
||||
func New(c dropbox.Config) Client {
|
||||
ctx := apiImpl(dropbox.NewContext(c))
|
||||
return &ctx
|
||||
}
|
17743
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/team_log/types.go
generated
vendored
17743
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/team_log/types.go
generated
vendored
File diff suppressed because it is too large
Load diff
237
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/generator/README.md
generated
vendored
237
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/generator/README.md
generated
vendored
|
@ -1,237 +0,0 @@
|
|||
# Dropbox Go SDK Generator
|
||||
|
||||
This directory contains the [Stone](https://github.com/dropbox/stone) code generators
|
||||
used to programmatically generate the [Dropbox Go SDK](https://github.com/dropbox/dropbox-sdk-go).
|
||||
|
||||
## Requirements
|
||||
|
||||
* While not a hard requirement, this repo currently assumes `python3` in the path.
|
||||
* Assumes you have already installed [Stone](https://github.com/dropbox/stone)
|
||||
* Requires [goimports](https://godoc.org/golang.org/x/tools/cmd/goimports) to fix up imports in the auto-generated code
|
||||
|
||||
## Basic Setup
|
||||
|
||||
. Clone this repo
|
||||
. Run `git submodule init` followed by `git submodule update`
|
||||
. Run `./generate-sdk.sh` to generate code under `../dropbox`
|
||||
|
||||
## Generated Code
|
||||
|
||||
### Basic Types
|
||||
|
||||
Here is how Stone [basic types](https://github.com/dropbox/stone/blob/master/doc/lang_ref.rst#basic-types) map to Go types:
|
||||
|
||||
Stone Type | Go Type
|
||||
---------- | -------
|
||||
Int32/Int64/UInt32/UInt64 | int32/int64/uint32/uint64
|
||||
Float32/Float64 | float32/float64
|
||||
Boolean | bool
|
||||
String | string
|
||||
Timestamp | time.Time
|
||||
Void | struct{}
|
||||
|
||||
### Structs
|
||||
|
||||
Stone [structs](https://github.com/dropbox/stone/blob/master/doc/lang_ref.rst#struct) are represented as Go [structs](https://gobyexample.com/structs) in a relatively straight-forward manner. Each struct member is exported and also gets assigned the correct json tag. The latter is used for serializing requests and deserializing responses. Non-primitive types are represented as pointers to the corresponding type.
|
||||
|
||||
```
|
||||
struct Account
|
||||
"The amount of detail revealed about an account depends on the user
|
||||
being queried and the user making the query."
|
||||
|
||||
account_id AccountId
|
||||
"The user's unique Dropbox ID."
|
||||
name Name
|
||||
"Details of a user's name."
|
||||
```
|
||||
|
||||
```go
|
||||
// The amount of detail revealed about an account depends on the user being
|
||||
// queried and the user making the query.
|
||||
type Account struct {
|
||||
// The user's unique Dropbox ID.
|
||||
AccountId string `json:"account_id"`
|
||||
// Details of a user's name.
|
||||
Name *Name `json:"name"`
|
||||
}
|
||||
```
|
||||
|
||||
#### Inheritance
|
||||
|
||||
Stone supports [struct inheritance](https://github.com/dropbox/stone/blob/master/doc/lang_ref.rst#inheritance). In Go, we support this via [embedding](https://golang.org/doc/effective_go.html#embedding)
|
||||
|
||||
```
|
||||
struct BasicAccount extends Account
|
||||
"Basic information about any account."
|
||||
|
||||
is_teammate Boolean
|
||||
"Whether this user is a teammate of the current user. If this account
|
||||
is the current user's account, then this will be :val:`true`."
|
||||
```
|
||||
|
||||
```go
|
||||
// Basic information about any account.
|
||||
type BasicAccount struct {
|
||||
Account
|
||||
// Whether this user is a teammate of the current user. If this account is
|
||||
// the current user's account, then this will be `True`.
|
||||
IsTeammate bool `json:"is_teammate"`
|
||||
```
|
||||
|
||||
### Unions
|
||||
|
||||
Stone https://github.com/dropbox/stone/blob/master/doc/lang_ref.rst#union[unions] are bit more complex as Go doesn't have native support for union types (tagged or otherwise). We declare a union as a Go struct with all the possible fields as pointer types, and then use the tag value to populate the correct field during deserialization. This necessitates the use of an intermediate wrapper struct for the deserialization to work correctly, see below for a concrete example.
|
||||
|
||||
```
|
||||
union SpaceAllocation
|
||||
"Space is allocated differently based on the type of account."
|
||||
|
||||
individual IndividualSpaceAllocation
|
||||
"The user's space allocation applies only to their individual account."
|
||||
team TeamSpaceAllocation
|
||||
"The user shares space with other members of their team."
|
||||
```
|
||||
|
||||
```go
|
||||
// Space is allocated differently based on the type of account.
|
||||
type SpaceAllocation struct {
|
||||
dropbox.Tagged
|
||||
// The user's space allocation applies only to their individual account.
|
||||
Individual *IndividualSpaceAllocation `json:"individual,omitempty"`
|
||||
// The user shares space with other members of their team.
|
||||
Team *TeamSpaceAllocation `json:"team,omitempty"`
|
||||
}
|
||||
|
||||
// Valid tag values for `SpaceAllocation`
|
||||
const (
|
||||
SpaceAllocation_Individual = "individual"
|
||||
SpaceAllocation_Team = "team"
|
||||
SpaceAllocation_Other = "other"
|
||||
)
|
||||
|
||||
func (u *SpaceAllocation) UnmarshalJSON(body []byte) error {
|
||||
type wrap struct {
|
||||
dropbox.Tagged
|
||||
// The user's space allocation applies only to their individual account.
|
||||
Individual json.RawMessage `json:"individual,omitempty"`
|
||||
// The user shares space with other members of their team.
|
||||
Team json.RawMessage `json:"team,omitempty"`
|
||||
}
|
||||
var w wrap
|
||||
if err := json.Unmarshal(body, &w); err != nil {
|
||||
return err
|
||||
}
|
||||
u.Tag = w.Tag
|
||||
switch u.Tag {
|
||||
case "individual":
|
||||
if err := json.Unmarshal(body, &u.Individual); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
case "team":
|
||||
if err := json.Unmarshal(body, &u.Team); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
}
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
### Struct with Enumerated Subtypes
|
||||
|
||||
Per the https://github.com/dropbox/stone/blob/master/doc/lang_ref.rst#struct-polymorphism[spec], structs with enumerated subtypes are a mechanism of inheritance:
|
||||
|
||||
> If a struct enumerates its subtypes, an instance of any subtype will satisfy the type constraint. This is useful when wanting to discriminate amongst types that are part of the same hierarchy while simultaneously being able to avoid discriminating when accessing common fields.
|
||||
|
||||
To represent structs with enumerated subtypes in Go, we use a combination of Go interface types and unions as implemented above. Considering the following:
|
||||
|
||||
```
|
||||
struct Metadata
|
||||
union
|
||||
file FileMetadata
|
||||
folder FolderMetadata
|
||||
deleted DeletedMetadata # Used by list_folder* and search
|
||||
|
||||
name String
|
||||
path_lower String?
|
||||
path_display String?
|
||||
parent_shared_folder_id common.SharedFolderId?
|
||||
|
||||
struct FileMetadata extends Metadata
|
||||
id Id
|
||||
client_modified common.DropboxTimestamp
|
||||
...
|
||||
```
|
||||
|
||||
In this case, `FileMetadata`, `FolderMetadata` etc are subtypes of `Metadata`. Specifically, any subtype can be used where a parent type is expected. Thus, if `list_folder` returns a list of `Metadata`s, we should be able to parse and "upcast" to one of the enumerated subtypes.
|
||||
|
||||
First, we define structs to represent the base and enumerated types as we did for inherited structs above:
|
||||
|
||||
```go
|
||||
type Metadata struct {
|
||||
Name string `json:"name"`
|
||||
PathLower string `json:"path_lower,omitempty"`
|
||||
PathDisplay string `json:"path_display,omitempty"`
|
||||
ParentSharedFolderId string `json:"parent_shared_folder_id,omitempty"`
|
||||
}
|
||||
|
||||
type FileMetadata struct {
|
||||
Metadata
|
||||
Id string `json:"id"`
|
||||
ClientModified time.Time `json:"client_modified"`
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
Next, we define an interface type with a dummy method and ensure that both the base and the subtypes implement the interface:
|
||||
|
||||
```go
|
||||
type IsMetadata interface {
|
||||
IsMetadata()
|
||||
}
|
||||
|
||||
func (u *Metadata) IsMetadata() {} // Subtypes get this for free due to embedding
|
||||
```
|
||||
|
||||
At this point, types or methods that accept/return a struct with enumerated subtypes can use the interface type instead. For instance:
|
||||
|
||||
```go
|
||||
func GetMetadata(arg *GetMetadataArg) (res IsMetadata, err error) {...}
|
||||
|
||||
type ListFolderResult struct {
|
||||
// The files and (direct) subfolders in the folder.
|
||||
Entries []IsMetadata `json:"entries"`
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
Finally, to actually deserialize a bag of bytes into the appropriate type or subtype, we use a trick similar to how we handle unions above.
|
||||
|
||||
```go
|
||||
type metadataUnion struct {
|
||||
dropbox.Tagged
|
||||
File *FileMetadata `json:"file,omitempty"`
|
||||
Folder *FolderMetadata `json:"folder,omitempty"`
|
||||
Deleted *DeletedMetadata `json:"deleted,omitempty"`
|
||||
}
|
||||
|
||||
func (u *metadataUnion) UnmarshalJSON(body []byte) error {...}
|
||||
|
||||
func (dbx *apiImpl) GetMetadata(arg *GetMetadataArg) (res IsMetadata, err error) {
|
||||
...
|
||||
var tmp metadataUnion
|
||||
err = json.Unmarshal(body, &tmp)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
switch tmp.Tag {
|
||||
case "file":
|
||||
res = tmp.File
|
||||
case "folder":
|
||||
res = tmp.Folder
|
||||
case "deleted":
|
||||
res = tmp.Deleted
|
||||
}
|
||||
}
|
||||
```
|
26
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/generator/generate-sdk.sh
generated
vendored
26
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/generator/generate-sdk.sh
generated
vendored
|
@ -1,26 +0,0 @@
|
|||
#! /usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
if [[ $# -gt 1 ]]; then
|
||||
echo "$0: Not expecting any command-line arguments, got $#." 1>&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
loc=$(realpath -e $0)
|
||||
base_dir=$(dirname "$loc")
|
||||
spec_dir="$base_dir/dropbox-api-spec"
|
||||
gen_dir=$(dirname ${base_dir})/dropbox
|
||||
|
||||
stone -v -a :all go_types.stoneg.py "$gen_dir" "$spec_dir"/*.stone
|
||||
stone -v -a :all go_client.stoneg.py "$gen_dir" "$spec_dir"/*.stone
|
||||
|
||||
# Update SDK and API spec versions
|
||||
sdk_version=${1:-"4.2.0"}
|
||||
pushd ${spec_dir}
|
||||
spec_version=$(git rev-parse --short HEAD)
|
||||
popd
|
||||
|
||||
sed -i.bak -e "s/UNKNOWN SDK VERSION/${sdk_version}/" \
|
||||
-e "s/UNKNOWN SPEC VERSION/${spec_version}/" ${gen_dir}/sdk.go
|
||||
rm ${gen_dir}/sdk.go.bak
|
||||
goimports -l -w ${gen_dir}
|
223
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/generator/go_client.stoneg.py
generated
vendored
223
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/generator/go_client.stoneg.py
generated
vendored
|
@ -1,223 +0,0 @@
|
|||
import os
|
||||
|
||||
from stone.backend import CodeBackend
|
||||
from stone.ir import (
|
||||
is_void_type,
|
||||
is_struct_type
|
||||
)
|
||||
|
||||
from go_helpers import (
|
||||
HEADER,
|
||||
fmt_type,
|
||||
fmt_var,
|
||||
generate_doc,
|
||||
)
|
||||
|
||||
|
||||
class GoClientBackend(CodeBackend):
|
||||
def generate(self, api):
|
||||
for namespace in api.namespaces.values():
|
||||
if len(namespace.routes) > 0:
|
||||
self._generate_client(namespace)
|
||||
|
||||
def _generate_client(self, namespace):
|
||||
file_name = os.path.join(self.target_folder_path, namespace.name,
|
||||
'client.go')
|
||||
with self.output_to_relative_path(file_name):
|
||||
self.emit_raw(HEADER)
|
||||
self.emit()
|
||||
self.emit('package %s' % namespace.name)
|
||||
self.emit()
|
||||
|
||||
self.emit('// Client interface describes all routes in this namespace')
|
||||
with self.block('type Client interface'):
|
||||
for route in namespace.routes:
|
||||
generate_doc(self, route)
|
||||
self.emit(self._generate_route_signature(namespace, route))
|
||||
self.emit()
|
||||
|
||||
self.emit('type apiImpl dropbox.Context')
|
||||
for route in namespace.routes:
|
||||
self._generate_route(namespace, route)
|
||||
self.emit('// New returns a Client implementation for this namespace')
|
||||
with self.block('func New(c dropbox.Config) Client'):
|
||||
self.emit('ctx := apiImpl(dropbox.NewContext(c))')
|
||||
self.emit('return &ctx')
|
||||
|
||||
def _generate_route_signature(self, namespace, route):
|
||||
req = fmt_type(route.arg_data_type, namespace)
|
||||
res = fmt_type(route.result_data_type, namespace, use_interface=True)
|
||||
fn = fmt_var(route.name)
|
||||
style = route.attrs.get('style', 'rpc')
|
||||
|
||||
arg = '' if is_void_type(route.arg_data_type) else 'arg {req}'
|
||||
ret = '(err error)' if is_void_type(route.result_data_type) else \
|
||||
'(res {res}, err error)'
|
||||
signature = '{fn}(' + arg + ') ' + ret
|
||||
if style == 'download':
|
||||
signature = '{fn}(' + arg + \
|
||||
') (res {res}, content io.ReadCloser, err error)'
|
||||
elif style == 'upload':
|
||||
signature = '{fn}(' + arg + ', content io.Reader) ' + ret
|
||||
if is_void_type(route.arg_data_type):
|
||||
signature = '{fn}(content io.Reader) ' + ret
|
||||
return signature.format(fn=fn, req=req, res=res)
|
||||
|
||||
|
||||
def _generate_route(self, namespace, route):
|
||||
out = self.emit
|
||||
fn = fmt_var(route.name)
|
||||
err = fmt_type(route.error_data_type, namespace)
|
||||
out('//%sAPIError is an error-wrapper for the %s route' %
|
||||
(fn, route.name))
|
||||
with self.block('type {fn}APIError struct'.format(fn=fn)):
|
||||
out('dropbox.APIError')
|
||||
out('EndpointError {err} `json:"error"`'.format(err=err))
|
||||
out()
|
||||
|
||||
signature = 'func (dbx *apiImpl) ' + self._generate_route_signature(
|
||||
namespace, route)
|
||||
with self.block(signature):
|
||||
if route.deprecated is not None:
|
||||
out('log.Printf("WARNING: API `%s` is deprecated")' % fn)
|
||||
if route.deprecated.by is not None:
|
||||
out('log.Printf("Use API `%s` instead")' % fmt_var(route.deprecated.by.name))
|
||||
out()
|
||||
|
||||
out('cli := dbx.Client')
|
||||
out()
|
||||
|
||||
self._generate_request(namespace, route)
|
||||
self._generate_post()
|
||||
self._generate_response(route)
|
||||
ok_check = 'if resp.StatusCode == http.StatusOK'
|
||||
if fn == "Download":
|
||||
ok_check += ' || resp.StatusCode == http.StatusPartialContent'
|
||||
with self.block(ok_check):
|
||||
self._generate_result(route)
|
||||
self._generate_error_handling(route)
|
||||
|
||||
out()
|
||||
|
||||
def _generate_request(self, namespace, route):
|
||||
out = self.emit
|
||||
auth = route.attrs.get('auth', '')
|
||||
host = route.attrs.get('host', 'api')
|
||||
style = route.attrs.get('style', 'rpc')
|
||||
|
||||
body = 'nil'
|
||||
if not is_void_type(route.arg_data_type):
|
||||
out('dbx.Config.LogDebug("arg: %v", arg)')
|
||||
|
||||
out('b, err := json.Marshal(arg)')
|
||||
with self.block('if err != nil'):
|
||||
out('return')
|
||||
out()
|
||||
if host != 'content':
|
||||
body = 'bytes.NewReader(b)'
|
||||
if style == 'upload':
|
||||
body = 'content'
|
||||
|
||||
headers = {}
|
||||
if not is_void_type(route.arg_data_type):
|
||||
if host == 'content' or style in ['upload', 'download']:
|
||||
headers["Dropbox-API-Arg"] = "string(b)"
|
||||
else:
|
||||
headers["Content-Type"] = '"application/json"'
|
||||
if style == 'upload':
|
||||
headers["Content-Type"] = '"application/octet-stream"'
|
||||
|
||||
out('headers := map[string]string{')
|
||||
for k, v in sorted(headers.items()):
|
||||
out('\t"{}": {},'.format(k, v))
|
||||
out('}')
|
||||
if fmt_var(route.name) == "Download":
|
||||
out('for k, v := range arg.ExtraHeaders { headers[k] = v }')
|
||||
if auth != 'noauth' and auth != 'team':
|
||||
with self.block('if dbx.Config.AsMemberID != ""'):
|
||||
out('headers["Dropbox-API-Select-User"] = dbx.Config.AsMemberID')
|
||||
out()
|
||||
|
||||
authed = 'false' if auth == 'noauth' else 'true'
|
||||
out('req, err := (*dropbox.Context)(dbx).NewRequest("{}", "{}", {}, "{}", "{}", headers, {})'.format(
|
||||
host, style, authed, namespace.name, route.name, body))
|
||||
with self.block('if err != nil'):
|
||||
out('return')
|
||||
|
||||
out('dbx.Config.LogInfo("req: %v", req)')
|
||||
|
||||
out()
|
||||
|
||||
def _generate_post(self):
|
||||
out = self.emit
|
||||
|
||||
out('resp, err := cli.Do(req)')
|
||||
|
||||
with self.block('if err != nil'):
|
||||
out('return')
|
||||
out()
|
||||
|
||||
out('dbx.Config.LogInfo("resp: %v", resp)')
|
||||
|
||||
def _generate_response(self, route):
|
||||
out = self.emit
|
||||
style = route.attrs.get('style', 'rpc')
|
||||
if style == 'download':
|
||||
out('body := []byte(resp.Header.Get("Dropbox-API-Result"))')
|
||||
out('content = resp.Body')
|
||||
else:
|
||||
out('defer resp.Body.Close()')
|
||||
with self.block('body, err := ioutil.ReadAll(resp.Body);'
|
||||
'if err != nil'):
|
||||
out('return')
|
||||
out()
|
||||
|
||||
out('dbx.Config.LogDebug("body: %v", body)')
|
||||
|
||||
def _generate_error_handling(self, route):
|
||||
out = self.emit
|
||||
style = route.attrs.get('style', 'rpc')
|
||||
with self.block('if resp.StatusCode == http.StatusConflict'):
|
||||
# If style was download, body was assigned to a header.
|
||||
# Need to re-read the response body to parse the error
|
||||
if style == 'download':
|
||||
out('defer resp.Body.Close()')
|
||||
with self.block('body, err = ioutil.ReadAll(resp.Body);'
|
||||
'if err != nil'):
|
||||
out('return')
|
||||
out('var apiError %sAPIError' % fmt_var(route.name))
|
||||
with self.block('err = json.Unmarshal(body, &apiError);'
|
||||
'if err != nil'):
|
||||
out('return')
|
||||
out('err = apiError')
|
||||
out('return')
|
||||
out('var apiError dropbox.APIError')
|
||||
with self.block("if resp.StatusCode == http.StatusBadRequest || "
|
||||
"resp.StatusCode == http.StatusInternalServerError"):
|
||||
out('apiError.ErrorSummary = string(body)')
|
||||
out('err = apiError')
|
||||
out('return')
|
||||
with self.block('err = json.Unmarshal(body, &apiError);'
|
||||
'if err != nil'):
|
||||
out('return')
|
||||
out('err = apiError')
|
||||
out('return')
|
||||
|
||||
def _generate_result(self, route):
|
||||
out = self.emit
|
||||
if is_struct_type(route.result_data_type) and \
|
||||
route.result_data_type.has_enumerated_subtypes():
|
||||
out('var tmp %sUnion' % fmt_var(route.result_data_type.name, export=False))
|
||||
with self.block('err = json.Unmarshal(body, &tmp);'
|
||||
'if err != nil'):
|
||||
out('return')
|
||||
with self.block('switch tmp.Tag'):
|
||||
for t in route.result_data_type.get_enumerated_subtypes():
|
||||
with self.block('case "%s":' % t.name, delim=(None, None)):
|
||||
self.emit('res = tmp.%s' % fmt_var(t.name))
|
||||
elif not is_void_type(route.result_data_type):
|
||||
with self.block('err = json.Unmarshal(body, &res);'
|
||||
'if err != nil'):
|
||||
out('return')
|
||||
out()
|
||||
out('return')
|
147
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/generator/go_helpers.py
generated
vendored
147
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/generator/go_helpers.py
generated
vendored
|
@ -1,147 +0,0 @@
|
|||
from stone.ir import (ApiNamespace, ApiRoute)
|
||||
from stone.ir import (
|
||||
Boolean,
|
||||
Float32,
|
||||
Float64,
|
||||
Int32,
|
||||
Int64,
|
||||
String,
|
||||
Timestamp,
|
||||
UInt32,
|
||||
UInt64,
|
||||
unwrap_nullable,
|
||||
is_composite_type,
|
||||
is_list_type,
|
||||
is_primitive_type,
|
||||
is_struct_type,
|
||||
Void,
|
||||
)
|
||||
from stone.backends import helpers
|
||||
|
||||
HEADER = """\
|
||||
// Copyright (c) Dropbox, Inc.
|
||||
//
|
||||
// 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.
|
||||
"""
|
||||
|
||||
_reserved_keywords = {
|
||||
'break', 'default', 'func', 'interface', 'select',
|
||||
'case', 'defer', 'go', 'map', 'struct',
|
||||
'chan', 'else', 'goto', 'package', 'switch',
|
||||
'const', 'fallthrough', 'if', 'range', 'type',
|
||||
'continue', 'for', 'import', 'return', 'var',
|
||||
}
|
||||
|
||||
_type_table = {
|
||||
UInt64: 'uint64',
|
||||
Int64: 'int64',
|
||||
UInt32: 'uint32',
|
||||
Int32: 'int32',
|
||||
Float64: 'float64',
|
||||
Float32: 'float32',
|
||||
Boolean: 'bool',
|
||||
String: 'string',
|
||||
Timestamp: 'time.Time',
|
||||
Void: 'struct{}',
|
||||
}
|
||||
|
||||
|
||||
def _rename_if_reserved(s):
|
||||
if s in _reserved_keywords:
|
||||
return s + '_'
|
||||
else:
|
||||
return s
|
||||
|
||||
|
||||
def fmt_type(data_type, namespace=None, use_interface=False, raw=False):
|
||||
data_type, nullable = unwrap_nullable(data_type)
|
||||
if is_list_type(data_type):
|
||||
if raw and is_primitive_type(data_type.data_type):
|
||||
return "json.RawMessage"
|
||||
return '[]%s' % fmt_type(data_type.data_type, namespace, use_interface, raw)
|
||||
if raw:
|
||||
return "json.RawMessage"
|
||||
type_name = data_type.name
|
||||
if use_interface and _needs_base_type(data_type):
|
||||
type_name = 'Is' + type_name
|
||||
if is_composite_type(data_type) and namespace is not None and \
|
||||
namespace.name != data_type.namespace.name:
|
||||
type_name = data_type.namespace.name + '.' + type_name
|
||||
if use_interface and _needs_base_type(data_type):
|
||||
return _type_table.get(data_type.__class__, type_name)
|
||||
else:
|
||||
return _type_table.get(data_type.__class__, '*' + type_name)
|
||||
|
||||
|
||||
def fmt_var(name, export=True, check_reserved=False):
|
||||
s = helpers.fmt_pascal(name) if export else helpers.fmt_camel(name)
|
||||
return _rename_if_reserved(s) if check_reserved else s
|
||||
|
||||
|
||||
def _doc_handler(tag, val):
|
||||
if tag == 'type':
|
||||
return '`{}`'.format(val)
|
||||
elif tag == 'route':
|
||||
return '`{}`'.format(helpers.fmt_camel(val))
|
||||
elif tag == 'link':
|
||||
anchor, link = val.rsplit(' ', 1)
|
||||
return '`{}` <{}>'.format(anchor, link)
|
||||
elif tag == 'val':
|
||||
if val == 'null':
|
||||
return 'nil'
|
||||
else:
|
||||
return val
|
||||
elif tag == 'field':
|
||||
return '`{}`'.format(val)
|
||||
else:
|
||||
raise RuntimeError('Unknown doc ref tag %r' % tag)
|
||||
|
||||
|
||||
def generate_doc(code_generator, t):
|
||||
doc = t.doc
|
||||
if doc is None:
|
||||
doc = 'has no documentation (yet)'
|
||||
doc = code_generator.process_doc(doc, _doc_handler)
|
||||
d = '%s : %s' % (fmt_var(t.name), doc)
|
||||
if isinstance(t, ApiNamespace):
|
||||
d = 'Package %s : %s' % (t.name, doc)
|
||||
code_generator.emit_wrapped_text(d, prefix='// ')
|
||||
|
||||
# Generate comment for deprecated routes
|
||||
if isinstance(t, ApiRoute):
|
||||
if t.deprecated is not None:
|
||||
d = 'Deprecated: '
|
||||
if t.deprecated.by is not None:
|
||||
d += 'Use `%s` instead' % fmt_var(t.deprecated.by.name)
|
||||
code_generator.emit_wrapped_text(d, prefix='// ')
|
||||
|
||||
|
||||
def _needs_base_type(data_type):
|
||||
if is_struct_type(data_type) and data_type.has_enumerated_subtypes():
|
||||
return True
|
||||
if is_list_type(data_type):
|
||||
return _needs_base_type(data_type.data_type)
|
||||
return False
|
||||
|
||||
|
||||
def needs_base_type(struct):
|
||||
for field in struct.fields:
|
||||
if _needs_base_type(field.data_type):
|
||||
return True
|
||||
return False
|
213
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/generator/go_rsrc/sdk.go
generated
vendored
213
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/generator/go_rsrc/sdk.go
generated
vendored
|
@ -1,213 +0,0 @@
|
|||
// Copyright (c) Dropbox, Inc.
|
||||
//
|
||||
// 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.
|
||||
|
||||
package dropbox
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"golang.org/x/net/context"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
const (
|
||||
apiVersion = 2
|
||||
defaultDomain = ".dropboxapi.com"
|
||||
hostAPI = "api"
|
||||
hostContent = "content"
|
||||
hostNotify = "notify"
|
||||
sdkVersion = "UNKNOWN SDK VERSION"
|
||||
specVersion = "UNKNOWN SPEC VERSION"
|
||||
)
|
||||
|
||||
// Version returns the current SDK version and API Spec version
|
||||
func Version() (string, string) {
|
||||
return sdkVersion, specVersion
|
||||
}
|
||||
|
||||
// Config contains parameters for configuring the SDK.
|
||||
type Config struct {
|
||||
// OAuth2 access token
|
||||
Token string
|
||||
// Logging level for SDK generated logs
|
||||
LogLevel LogLevel
|
||||
// Logging target for verbose SDK logging
|
||||
Logger *log.Logger
|
||||
// Used with APIs that support operations as another user
|
||||
AsMemberID string
|
||||
// No need to set -- for testing only
|
||||
Domain string
|
||||
// No need to set -- for testing only
|
||||
Client *http.Client
|
||||
// No need to set -- for testing only
|
||||
HeaderGenerator func(hostType string, style string, namespace string, route string) map[string]string
|
||||
// No need to set -- for testing only
|
||||
URLGenerator func(hostType string, style string, namespace string, route string) string
|
||||
}
|
||||
|
||||
// LogLevel defines a type that can set the desired level of logging the SDK will generate.
|
||||
type LogLevel uint
|
||||
|
||||
const (
|
||||
// LogOff will disable all SDK logging. This is the default log level
|
||||
LogOff LogLevel = iota * (1 << 8)
|
||||
// LogDebug will enable detailed SDK debug logs. It will log requests (including arguments),
|
||||
// response and body contents.
|
||||
LogDebug
|
||||
// LogInfo will log SDK request (not including arguments) and responses.
|
||||
LogInfo
|
||||
)
|
||||
|
||||
func (l LogLevel) shouldLog(v LogLevel) bool {
|
||||
return l > v || l&v == v
|
||||
}
|
||||
|
||||
func (c *Config) doLog(l LogLevel, format string, v ...interface{}) {
|
||||
if !c.LogLevel.shouldLog(l) {
|
||||
return
|
||||
}
|
||||
|
||||
if c.Logger != nil {
|
||||
c.Logger.Printf(format, v...)
|
||||
} else {
|
||||
log.Printf(format, v...)
|
||||
}
|
||||
}
|
||||
|
||||
// LogDebug emits a debug level SDK log if config's log level is at least LogDebug
|
||||
func (c *Config) LogDebug(format string, v ...interface{}) {
|
||||
c.doLog(LogDebug, format, v...)
|
||||
}
|
||||
|
||||
// LogInfo emits an info level SDK log if config's log level is at least LogInfo
|
||||
func (c *Config) LogInfo(format string, v ...interface{}) {
|
||||
c.doLog(LogInfo, format, v...)
|
||||
}
|
||||
|
||||
// Context is the base client context used to implement per-namespace clients.
|
||||
type Context struct {
|
||||
Config Config
|
||||
Client *http.Client
|
||||
HeaderGenerator func(hostType string, style string, namespace string, route string) map[string]string
|
||||
URLGenerator func(hostType string, style string, namespace string, route string) string
|
||||
}
|
||||
|
||||
// NewRequest returns an appropriate Request object for the given namespace/route.
|
||||
func (c *Context) NewRequest(
|
||||
hostType string,
|
||||
style string,
|
||||
authed bool,
|
||||
namespace string,
|
||||
route string,
|
||||
headers map[string]string,
|
||||
body io.Reader,
|
||||
) (*http.Request, error) {
|
||||
url := c.URLGenerator(hostType, style, namespace, route)
|
||||
req, err := http.NewRequest("POST", url, body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for k, v := range headers {
|
||||
req.Header.Add(k, v)
|
||||
}
|
||||
for k, v := range c.HeaderGenerator(hostType, style, namespace, route) {
|
||||
req.Header.Add(k, v)
|
||||
}
|
||||
if req.Header.Get("Host") != "" {
|
||||
req.Host = req.Header.Get("Host")
|
||||
}
|
||||
if !authed {
|
||||
req.Header.Del("Authorization")
|
||||
}
|
||||
return req, nil
|
||||
}
|
||||
|
||||
// NewContext returns a new Context with the given Config.
|
||||
func NewContext(c Config) Context {
|
||||
domain := c.Domain
|
||||
if domain == "" {
|
||||
domain = defaultDomain
|
||||
}
|
||||
|
||||
client := c.Client
|
||||
if client == nil {
|
||||
var conf = &oauth2.Config{Endpoint: OAuthEndpoint(domain)}
|
||||
tok := &oauth2.Token{AccessToken: c.Token}
|
||||
client = conf.Client(context.Background(), tok)
|
||||
}
|
||||
|
||||
headerGenerator := c.HeaderGenerator
|
||||
if headerGenerator == nil {
|
||||
headerGenerator = func(hostType string, style string, namespace string, route string) map[string]string {
|
||||
return map[string]string{}
|
||||
}
|
||||
}
|
||||
|
||||
urlGenerator := c.URLGenerator
|
||||
if urlGenerator == nil {
|
||||
hostMap := map[string]string{
|
||||
hostAPI: hostAPI + domain,
|
||||
hostContent: hostContent + domain,
|
||||
hostNotify: hostNotify + domain,
|
||||
}
|
||||
urlGenerator = func(hostType string, style string, namespace string, route string) string {
|
||||
fqHost := hostMap[hostType]
|
||||
return fmt.Sprintf("https://%s/%d/%s/%s", fqHost, apiVersion, namespace, route)
|
||||
}
|
||||
}
|
||||
|
||||
return Context{c, client, headerGenerator, urlGenerator}
|
||||
}
|
||||
|
||||
// OAuthEndpoint constructs an `oauth2.Endpoint` for the given domain
|
||||
func OAuthEndpoint(domain string) oauth2.Endpoint {
|
||||
if domain == "" {
|
||||
domain = defaultDomain
|
||||
}
|
||||
authURL := fmt.Sprintf("https://meta%s/1/oauth2/authorize", domain)
|
||||
tokenURL := fmt.Sprintf("https://api%s/1/oauth2/token", domain)
|
||||
if domain == defaultDomain {
|
||||
authURL = "https://www.dropbox.com/1/oauth2/authorize"
|
||||
}
|
||||
return oauth2.Endpoint{AuthURL: authURL, TokenURL: tokenURL}
|
||||
}
|
||||
|
||||
// Tagged is used for tagged unions.
|
||||
type Tagged struct {
|
||||
Tag string `json:".tag"`
|
||||
}
|
||||
|
||||
// APIError is the base type for endpoint-specific errors.
|
||||
type APIError struct {
|
||||
ErrorSummary string `json:"error_summary"`
|
||||
}
|
||||
|
||||
func (e APIError) Error() string {
|
||||
return e.ErrorSummary
|
||||
}
|
||||
|
||||
func init() {
|
||||
// These are not registered in the oauth library by default
|
||||
oauth2.RegisterBrokenAuthHeaderProvider("https://api.dropboxapi.com")
|
||||
oauth2.RegisterBrokenAuthHeaderProvider("https://api-dbdev.dev.corp.dropbox.com")
|
||||
}
|
228
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/generator/go_types.stoneg.py
generated
vendored
228
vendor/github.com/dropbox/dropbox-sdk-go-unofficial/generator/go_types.stoneg.py
generated
vendored
|
@ -1,228 +0,0 @@
|
|||
import os
|
||||
import shutil
|
||||
|
||||
from stone.backend import CodeBackend
|
||||
from stone.ir import (
|
||||
is_boolean_type,
|
||||
is_list_type,
|
||||
is_nullable_type,
|
||||
is_primitive_type,
|
||||
is_struct_type,
|
||||
is_union_type,
|
||||
is_void_type,
|
||||
)
|
||||
|
||||
from go_helpers import (
|
||||
HEADER,
|
||||
fmt_type,
|
||||
fmt_var,
|
||||
generate_doc,
|
||||
needs_base_type,
|
||||
_needs_base_type
|
||||
)
|
||||
|
||||
|
||||
class GoTypesBackend(CodeBackend):
|
||||
def generate(self, api):
|
||||
rsrc_folder = os.path.join(os.path.dirname(__file__), 'go_rsrc')
|
||||
shutil.copy(os.path.join(rsrc_folder, 'sdk.go'),
|
||||
self.target_folder_path)
|
||||
for namespace in api.namespaces.values():
|
||||
self._generate_namespace(namespace)
|
||||
|
||||
def _generate_namespace(self, namespace):
|
||||
file_name = os.path.join(self.target_folder_path, namespace.name,
|
||||
'types.go')
|
||||
with self.output_to_relative_path(file_name):
|
||||
self.emit_raw(HEADER)
|
||||
self.emit()
|
||||
generate_doc(self, namespace)
|
||||
self.emit('package %s' % namespace.name)
|
||||
self.emit()
|
||||
|
||||
for data_type in namespace.linearize_data_types():
|
||||
self._generate_data_type(data_type)
|
||||
|
||||
def _generate_data_type(self, data_type):
|
||||
generate_doc(self, data_type)
|
||||
if is_struct_type(data_type):
|
||||
self._generate_struct(data_type)
|
||||
if data_type.has_enumerated_subtypes():
|
||||
self._generate_base_type(data_type)
|
||||
elif is_union_type(data_type):
|
||||
self._generate_union(data_type)
|
||||
else:
|
||||
self.logger.info("Unhandled data type", data_type)
|
||||
|
||||
def _generate_base_type(self, base):
|
||||
t = fmt_type(base).lstrip('*')
|
||||
self.emit('// Is{0} is the interface type for {0} and its subtypes'.format(t))
|
||||
with self.block('type Is%s interface' % t):
|
||||
self.emit('Is%s()' % t)
|
||||
self.emit()
|
||||
self.emit('// Is{0} implements the Is{0} interface'.format(t))
|
||||
self.emit("func (u *{0}) Is{0}() {{}}".format(t))
|
||||
self.emit()
|
||||
self._generate_union_helper(base)
|
||||
|
||||
self.emit("// Is{0}FromJSON converts JSON to a concrete Is{0} instance".format(t))
|
||||
with self.block("func Is{0}FromJSON(data []byte) (Is{0}, error)".format(t)):
|
||||
name = fmt_var(t, export=False) + 'Union'
|
||||
self.emit("var t {0}".format(name))
|
||||
with self.block("if err := json.Unmarshal(data, &t); err != nil"):
|
||||
self.emit("return nil, err")
|
||||
with self.block("switch t.Tag"):
|
||||
fields = base.get_enumerated_subtypes()
|
||||
for field in fields:
|
||||
with self.block('case "%s":' % field.name, delim=(None, None)):
|
||||
self.emit("return t.{0}, nil".format(fmt_var(field.name)))
|
||||
# FIX THIS
|
||||
self.emit("return nil, nil")
|
||||
|
||||
def _generate_struct(self, struct):
|
||||
with self.block('type %s struct' % struct.name):
|
||||
if struct.parent_type:
|
||||
self.emit(fmt_type(struct.parent_type, struct.namespace).lstrip('*'))
|
||||
for field in struct.fields:
|
||||
self._generate_field(field, namespace=struct.namespace)
|
||||
if struct.name in ('DownloadArg',):
|
||||
self.emit('// ExtraHeaders can be used to pass Range, If-None-Match headers')
|
||||
self.emit('ExtraHeaders map[string]string `json:"-"`')
|
||||
self._generate_struct_builder(struct)
|
||||
self.emit()
|
||||
if needs_base_type(struct):
|
||||
self.emit('// UnmarshalJSON deserializes into a %s instance' % struct.name)
|
||||
with self.block('func (u *%s) UnmarshalJSON(b []byte) error' % struct.name):
|
||||
with self.block('type wrap struct'):
|
||||
for field in struct.all_fields:
|
||||
self._generate_field(field, namespace=struct.namespace,
|
||||
raw=_needs_base_type(field.data_type))
|
||||
self.emit('var w wrap')
|
||||
with self.block('if err := json.Unmarshal(b, &w); err != nil'):
|
||||
self.emit('return err')
|
||||
for field in struct.all_fields:
|
||||
dt = field.data_type
|
||||
fn = fmt_var(field.name)
|
||||
tn = fmt_type(dt, namespace=struct.namespace, use_interface=True)
|
||||
if _needs_base_type(dt):
|
||||
if is_list_type(dt):
|
||||
self.emit("u.{0} = make({1}, len(w.{0}))".format(fn, tn))
|
||||
# Grab the underlying type to get the correct Is...FromJSON method
|
||||
tn = fmt_type(dt.data_type, namespace=struct.namespace, use_interface=True)
|
||||
with self.block("for i, e := range w.{0}".format(fn)):
|
||||
self.emit("v, err := {1}FromJSON(e)".format(fn, tn))
|
||||
with self.block('if err != nil'):
|
||||
self.emit('return err')
|
||||
self.emit("u.{0}[i] = v".format(fn))
|
||||
else:
|
||||
self.emit("{0}, err := {1}FromJSON(w.{0})".format(fn, tn))
|
||||
with self.block('if err != nil'):
|
||||
self.emit('return err')
|
||||
self.emit("u.{0} = {0}".format(fn))
|
||||
else:
|
||||
self.emit("u.{0} = w.{0}".format(fn))
|
||||
self.emit('return nil')
|
||||
|
||||
def _generate_struct_builder(self, struct):
|
||||
fields = ["%s %s" % (fmt_var(field.name),
|
||||
fmt_type(field.data_type, struct.namespace,
|
||||
use_interface=True))
|
||||
for field in struct.all_required_fields]
|
||||
self.emit('// New{0} returns a new {0} instance'.format(struct.name))
|
||||
signature = "func New{0}({1}) *{0}".format(struct.name, ', '.join(fields))
|
||||
with self.block(signature):
|
||||
self.emit('s := new({0})'.format(struct.name))
|
||||
for field in struct.all_required_fields:
|
||||
field_name = fmt_var(field.name)
|
||||
self.emit("s.{0} = {0}".format(field_name))
|
||||
|
||||
for field in struct.all_optional_fields:
|
||||
if field.has_default:
|
||||
if is_primitive_type(field.data_type):
|
||||
default = field.default
|
||||
if is_boolean_type(field.data_type):
|
||||
default = str(default).lower()
|
||||
self.emit('s.{0} = {1}'.format(fmt_var(field.name), default))
|
||||
elif is_union_type(field.data_type):
|
||||
self.emit('s.%s = &%s{Tagged:dropbox.Tagged{"%s"}}' %
|
||||
(fmt_var(field.name),
|
||||
fmt_type(field.data_type, struct.namespace).lstrip('*'),
|
||||
field.default.tag_name))
|
||||
self.emit('return s')
|
||||
self.emit()
|
||||
|
||||
def _generate_field(self, field, union_field=False, namespace=None, raw=False):
|
||||
generate_doc(self, field)
|
||||
field_name = fmt_var(field.name)
|
||||
type_name = fmt_type(field.data_type, namespace, use_interface=True, raw=raw)
|
||||
json_tag = '`json:"%s"`' % field.name
|
||||
if is_nullable_type(field.data_type) or union_field:
|
||||
json_tag = '`json:"%s,omitempty"`' % field.name
|
||||
self.emit('%s %s %s' % (field_name, type_name, json_tag))
|
||||
|
||||
def _generate_union(self, union):
|
||||
self._generate_union_helper(union)
|
||||
|
||||
def _generate_union_helper(self, u):
|
||||
name = u.name
|
||||
namespace = u.namespace
|
||||
# Unions can be inherited, but don't need to be polymorphic.
|
||||
# So let's flatten out all the inherited fields.
|
||||
fields = u.all_fields
|
||||
if is_struct_type(u) and u.has_enumerated_subtypes():
|
||||
name = fmt_var(name, export=False) + 'Union'
|
||||
fields = u.get_enumerated_subtypes()
|
||||
|
||||
with self.block('type %s struct' % name):
|
||||
self.emit('dropbox.Tagged')
|
||||
for field in fields:
|
||||
if is_void_type(field.data_type):
|
||||
continue
|
||||
self._generate_field(field, union_field=True,
|
||||
namespace=namespace)
|
||||
self.emit()
|
||||
self.emit('// Valid tag values for %s' % fmt_var(u.name))
|
||||
with self.block('const', delim=('(', ')')):
|
||||
for field in fields:
|
||||
self.emit('%s%s = "%s"' % (fmt_var(u.name), fmt_var(field.name), field.name))
|
||||
self.emit()
|
||||
|
||||
num_void_fields = sum([is_void_type(f.data_type) for f in fields])
|
||||
# Simple structure, no need in UnmarshalJSON
|
||||
if len(fields) == num_void_fields:
|
||||
return
|
||||
|
||||
self.emit('// UnmarshalJSON deserializes into a %s instance' % name)
|
||||
with self.block('func (u *%s) UnmarshalJSON(body []byte) error' % name):
|
||||
with self.block('type wrap struct'):
|
||||
self.emit('dropbox.Tagged')
|
||||
for field in fields:
|
||||
if is_void_type(field.data_type) or \
|
||||
is_primitive_type(field.data_type):
|
||||
continue
|
||||
self._generate_field(field, union_field=True,
|
||||
namespace=namespace, raw=True)
|
||||
self.emit('var w wrap')
|
||||
self.emit('var err error')
|
||||
with self.block('if err = json.Unmarshal(body, &w); err != nil'):
|
||||
self.emit('return err')
|
||||
self.emit('u.Tag = w.Tag')
|
||||
with self.block('switch u.Tag'):
|
||||
for field in fields:
|
||||
if is_void_type(field.data_type):
|
||||
continue
|
||||
field_name = fmt_var(field.name)
|
||||
with self.block('case "%s":' % field.name, delim=(None, None)):
|
||||
if is_union_type(field.data_type):
|
||||
self.emit('err = json.Unmarshal(w.{0}, &u.{0})'
|
||||
.format(field_name))
|
||||
elif _needs_base_type(field.data_type):
|
||||
self.emit("u.{0}, err = Is{1}FromJSON(body)"
|
||||
.format(field_name, field.data_type.name))
|
||||
else:
|
||||
self.emit('err = json.Unmarshal(body, &u.{0})'
|
||||
.format(field_name))
|
||||
with self.block("if err != nil"):
|
||||
self.emit("return err")
|
||||
self.emit('return nil')
|
||||
self.emit()
|
Loading…
Add table
Add a link
Reference in a new issue