├── .github ├── ISSUE_TEMPLATE │ ├── config.yml │ ├── feature_request.md │ ├── question_help.md │ └── bug_report.md ├── workflows │ ├── lint.yml │ ├── test.yml │ └── codeql-analysis.yml └── dependabot.yml ├── v6 ├── go.mod ├── dropbox │ ├── users_common │ │ └── types.go │ ├── secondary_emails │ │ └── types.go │ ├── seen_state │ │ └── types.go │ ├── check │ │ ├── types.go │ │ └── client.go │ ├── auth │ │ ├── sdk.go │ │ ├── client.go │ │ └── types.go │ ├── account │ │ ├── client.go │ │ └── types.go │ ├── openid │ │ ├── client.go │ │ └── types.go │ ├── contacts │ │ ├── types.go │ │ └── client.go │ ├── team_common │ │ └── types.go │ ├── team_log │ │ └── client.go │ ├── async │ │ └── types.go │ ├── users │ │ └── client.go │ ├── common │ │ └── types.go │ ├── sdk_test.go │ ├── sdk.go │ ├── file_requests │ │ ├── client.go │ │ └── types.go │ ├── team_policies │ │ └── types.go │ └── file_properties │ │ └── client.go └── go.sum ├── .gitmodules ├── .gitignore ├── generator ├── generate-sdk.sh ├── go_helpers.py ├── go_client.stoneg.py ├── README.md ├── go_rsrc │ └── sdk.go └── go_types.stoneg.py ├── LICENSE └── README.md /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: false -------------------------------------------------------------------------------- /v6/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/dropbox/dropbox-sdk-go-unofficial/v6 2 | 3 | go 1.13 4 | 5 | require golang.org/x/oauth2 v0.7.0 6 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "generator/dropbox-api-spec"] 2 | path = generator/dropbox-api-spec 3 | url = https://github.com/dropbox/dropbox-api-spec 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # jetbrains 2 | .idea 3 | 4 | # swap 5 | [._]*.s[a-w][a-z] 6 | [._]s[a-w][a-z] 7 | 8 | # emacs backups 9 | *~ 10 | 11 | .pyc 12 | __pycache__ 13 | -------------------------------------------------------------------------------- /.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | name: Lint 2 | on: 3 | pull_request: 4 | jobs: 5 | golangci: 6 | name: lint 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v3 10 | - name: golangci-lint 11 | uses: golangci/golangci-lint-action@v3 12 | with: 13 | version: latest 14 | working-directory: ./v6 15 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | on: 3 | pull_request: 4 | env: 5 | GO111MODULE: "on" 6 | jobs: 7 | test: 8 | strategy: 9 | matrix: 10 | go-version: [1.11.x] 11 | os: [ubuntu-latest, macos-latest, windows-latest] 12 | runs-on: ${{ matrix.os }} 13 | steps: 14 | - name: Install Go 15 | uses: actions/setup-go@v4 16 | with: 17 | go-version: ${{ matrix.go-version }} 18 | - name: Checkout code 19 | uses: actions/checkout@v3 20 | - name: Test 21 | run: go test -race -v ./... 22 | working-directory: ./v6 23 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "gomod" # See documentation for possible values 9 | directory: "/v6" # Location of package manifests 10 | schedule: 11 | interval: "daily" 12 | 13 | - package-ecosystem: "github-actions" 14 | directory: "/" 15 | schedule: 16 | interval: "daily" 17 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: "\U0001F680 Feature Request" 3 | about: Suggest an idea for this SDK 4 | title: '' 5 | labels: enhancement 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Why is this feature valuable to you? Does it solve a problem you're having?** 11 | A clear and concise description of why this feature is valuable. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. (if applicable) 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/question_help.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: "\U0001F4AC Questions / Help" 3 | about: Get help with issues you are experiencing 4 | title: '' 5 | labels: help-wanted, question 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Before you start** 11 | Have you checked StackOverflow, previous issues, and Dropbox Developer Forums for help? 12 | 13 | **What is your question?** 14 | A clear and concise description of the question. 15 | 16 | **Screenshots** 17 | If applicable, add screenshots to help explain your question. 18 | 19 | **Versions** 20 | * What version of the SDK are you using? 21 | * What version of the language are you using? 22 | * What platform are you using? (if applicable) 23 | 24 | **Additional context** 25 | Add any other context about the question here. 26 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: "\U0001F41B Bug report" 3 | about: Create a report to help us improve the SDK 4 | title: '' 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of the bug. 12 | 13 | **To Reproduce** 14 | The steps to reproduce the behavior 15 | 16 | **Expected Behavior** 17 | A clear description of what you expected to happen. 18 | 19 | **Actual Behavior** 20 | A clear description of what actually happened 21 | 22 | **Screenshots** 23 | If applicable, add screenshots to help explain your problem. 24 | 25 | **Versions** 26 | * What version of the SDK are you using? 27 | * What version of the language are you using? 28 | * What platform are you using? (if applicable) 29 | 30 | **Additional context** 31 | Add any other context about the problem here. -------------------------------------------------------------------------------- /generator/generate-sdk.sh: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env bash 2 | set -euo pipefail 3 | 4 | if [[ $# -ne 1 ]]; then 5 | echo "$0: Expecting exactly one command-line argument, got $#." 1>&2 6 | exit 1 7 | fi 8 | 9 | version=$(echo $1 | cut -f1 -d'.') 10 | loc=$(realpath -e $0) 11 | base_dir=$(dirname "$loc") 12 | spec_dir="$base_dir/dropbox-api-spec" 13 | gen_dir=$(dirname ${base_dir})/v$version/dropbox 14 | 15 | stone -v -a :all go_types.stoneg.py "$gen_dir" "$spec_dir"/*.stone 16 | stone -v -a :all go_client.stoneg.py "$gen_dir" "$spec_dir"/*.stone 17 | 18 | # Update SDK and API spec versions 19 | sdk_version=${1} 20 | pushd ${spec_dir} 21 | spec_version=$(git rev-parse --short HEAD) 22 | popd 23 | 24 | sed -i.bak -e "s/UNKNOWN SDK VERSION/${sdk_version}/" \ 25 | -e "s/UNKNOWN SPEC VERSION/${spec_version}/" ${gen_dir}/sdk.go 26 | rm ${gen_dir}/sdk.go.bak 27 | pushd ${gen_dir} 28 | goimports -l -w ${gen_dir} 29 | popd 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2009-2016 Dropbox Inc., http://www.dropbox.com/ 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining 4 | a copy of this software and associated documentation files (the 5 | "Software"), to deal in the Software without restriction, including 6 | without limitation the rights to use, copy, modify, merge, publish, 7 | distribute, sublicense, and/or sell copies of the Software, and to 8 | permit persons to whom the Software is furnished to do so, subject to 9 | the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be 12 | included in all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 15 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 17 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 18 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 19 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 20 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /v6/dropbox/users_common/types.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) Dropbox, Inc. 2 | // 3 | // Permission is hereby granted, free of charge, to any person obtaining a copy 4 | // of this software and associated documentation files (the "Software"), to deal 5 | // in the Software without restriction, including without limitation the rights 6 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | // copies of the Software, and to permit persons to whom the Software is 8 | // furnished to do so, subject to the following conditions: 9 | // 10 | // The above copyright notice and this permission notice shall be included in 11 | // all copies or substantial portions of the Software. 12 | // 13 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | // THE SOFTWARE. 20 | 21 | // Package users_common : This namespace contains common data types used within 22 | // the users namespace. 23 | package users_common 24 | 25 | import "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox" 26 | 27 | // AccountType : What type of account this user has. 28 | type AccountType struct { 29 | dropbox.Tagged 30 | } 31 | 32 | // Valid tag values for AccountType 33 | const ( 34 | AccountTypeBasic = "basic" 35 | AccountTypePro = "pro" 36 | AccountTypeBusiness = "business" 37 | ) 38 | -------------------------------------------------------------------------------- /v6/dropbox/secondary_emails/types.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) Dropbox, Inc. 2 | // 3 | // Permission is hereby granted, free of charge, to any person obtaining a copy 4 | // of this software and associated documentation files (the "Software"), to deal 5 | // in the Software without restriction, including without limitation the rights 6 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | // copies of the Software, and to permit persons to whom the Software is 8 | // furnished to do so, subject to the following conditions: 9 | // 10 | // The above copyright notice and this permission notice shall be included in 11 | // all copies or substantial portions of the Software. 12 | // 13 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | // THE SOFTWARE. 20 | 21 | // Package secondary_emails : has no documentation (yet) 22 | package secondary_emails 23 | 24 | // SecondaryEmail : has no documentation (yet) 25 | type SecondaryEmail struct { 26 | // Email : Secondary email address. 27 | Email string `json:"email"` 28 | // IsVerified : Whether or not the secondary email address is verified to be 29 | // owned by a user. 30 | IsVerified bool `json:"is_verified"` 31 | } 32 | 33 | // NewSecondaryEmail returns a new SecondaryEmail instance 34 | func NewSecondaryEmail(Email string, IsVerified bool) *SecondaryEmail { 35 | s := new(SecondaryEmail) 36 | s.Email = Email 37 | s.IsVerified = IsVerified 38 | return s 39 | } 40 | -------------------------------------------------------------------------------- /v6/dropbox/seen_state/types.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) Dropbox, Inc. 2 | // 3 | // Permission is hereby granted, free of charge, to any person obtaining a copy 4 | // of this software and associated documentation files (the "Software"), to deal 5 | // in the Software without restriction, including without limitation the rights 6 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | // copies of the Software, and to permit persons to whom the Software is 8 | // furnished to do so, subject to the following conditions: 9 | // 10 | // The above copyright notice and this permission notice shall be included in 11 | // all copies or substantial portions of the Software. 12 | // 13 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | // THE SOFTWARE. 20 | 21 | // Package seen_state : has no documentation (yet) 22 | package seen_state 23 | 24 | import "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox" 25 | 26 | // PlatformType : Possible platforms on which a user may view content. 27 | type PlatformType struct { 28 | dropbox.Tagged 29 | } 30 | 31 | // Valid tag values for PlatformType 32 | const ( 33 | PlatformTypeWeb = "web" 34 | PlatformTypeDesktop = "desktop" 35 | PlatformTypeMobileIos = "mobile_ios" 36 | PlatformTypeMobileAndroid = "mobile_android" 37 | PlatformTypeApi = "api" 38 | PlatformTypeUnknown = "unknown" 39 | PlatformTypeMobile = "mobile" 40 | PlatformTypeOther = "other" 41 | ) 42 | -------------------------------------------------------------------------------- /v6/dropbox/check/types.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) Dropbox, Inc. 2 | // 3 | // Permission is hereby granted, free of charge, to any person obtaining a copy 4 | // of this software and associated documentation files (the "Software"), to deal 5 | // in the Software without restriction, including without limitation the rights 6 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | // copies of the Software, and to permit persons to whom the Software is 8 | // furnished to do so, subject to the following conditions: 9 | // 10 | // The above copyright notice and this permission notice shall be included in 11 | // all copies or substantial portions of the Software. 12 | // 13 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | // THE SOFTWARE. 20 | 21 | // Package check : has no documentation (yet) 22 | package check 23 | 24 | // EchoArg : EchoArg contains the arguments to be sent to the Dropbox servers. 25 | type EchoArg struct { 26 | // Query : The string that you'd like to be echoed back to you. 27 | Query string `json:"query"` 28 | } 29 | 30 | // NewEchoArg returns a new EchoArg instance 31 | func NewEchoArg() *EchoArg { 32 | s := new(EchoArg) 33 | s.Query = "" 34 | return s 35 | } 36 | 37 | // EchoResult : EchoResult contains the result returned from the Dropbox 38 | // servers. 39 | type EchoResult struct { 40 | // Result : If everything worked correctly, this would be the same as query. 41 | Result string `json:"result"` 42 | } 43 | 44 | // NewEchoResult returns a new EchoResult instance 45 | func NewEchoResult() *EchoResult { 46 | s := new(EchoResult) 47 | s.Result = "" 48 | return s 49 | } 50 | -------------------------------------------------------------------------------- /v6/dropbox/auth/sdk.go: -------------------------------------------------------------------------------- 1 | package auth 2 | 3 | import ( 4 | "encoding/json" 5 | "net/http" 6 | 7 | "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox" 8 | ) 9 | 10 | // AuthAPIError wraps AuthError 11 | type AuthAPIError struct { 12 | dropbox.APIError 13 | AuthError *AuthError `json:"error"` 14 | } 15 | 16 | // AccessAPIError wraps AccessError 17 | type AccessAPIError struct { 18 | dropbox.APIError 19 | AccessError *AccessError `json:"error"` 20 | } 21 | 22 | // RateLimitAPIError wraps RateLimitError 23 | type RateLimitAPIError struct { 24 | dropbox.APIError 25 | RateLimitError *RateLimitError `json:"error"` 26 | } 27 | 28 | // Bad input parameter. 29 | type BadRequest struct { 30 | dropbox.APIError 31 | } 32 | 33 | // An error occurred on the Dropbox servers. Check status.dropbox.com for announcements about 34 | // Dropbox service issues. 35 | type ServerError struct { 36 | dropbox.APIError 37 | StatusCode int 38 | } 39 | 40 | func ParseError(err error, appError error) error { 41 | sdkErr, ok := err.(dropbox.SDKInternalError) 42 | if !ok { 43 | return err 44 | } 45 | 46 | if sdkErr.StatusCode >= 500 && sdkErr.StatusCode <= 599 { 47 | return ServerError{ 48 | APIError: dropbox.APIError{ 49 | ErrorSummary: sdkErr.Content, 50 | }, 51 | } 52 | } 53 | 54 | switch sdkErr.StatusCode { 55 | case http.StatusBadRequest: 56 | return BadRequest{ 57 | APIError: dropbox.APIError{ 58 | ErrorSummary: sdkErr.Content, 59 | }, 60 | } 61 | case http.StatusUnauthorized: 62 | var apiError AuthAPIError 63 | if pErr := json.Unmarshal([]byte(sdkErr.Content), &apiError); pErr != nil { 64 | return pErr 65 | } 66 | 67 | return apiError 68 | case http.StatusForbidden: 69 | var apiError AccessAPIError 70 | if pErr := json.Unmarshal([]byte(sdkErr.Content), &apiError); pErr != nil { 71 | return pErr 72 | } 73 | 74 | return apiError 75 | case http.StatusTooManyRequests: 76 | var apiError RateLimitAPIError 77 | if pErr := json.Unmarshal([]byte(sdkErr.Content), &apiError); pErr != nil { 78 | return pErr 79 | } 80 | 81 | return apiError 82 | case http.StatusConflict: 83 | if pErr := json.Unmarshal([]byte(sdkErr.Content), appError); pErr != nil { 84 | return pErr 85 | } 86 | 87 | return appError 88 | } 89 | 90 | return err 91 | } 92 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | push: 16 | branches: [ master ] 17 | pull_request: 18 | # The branches below must be a subset of the branches above 19 | branches: [ master ] 20 | schedule: 21 | - cron: '18 6 * * 0' 22 | 23 | jobs: 24 | analyze: 25 | name: Analyze 26 | runs-on: ubuntu-latest 27 | 28 | strategy: 29 | fail-fast: false 30 | matrix: 31 | language: [ 'go' ] 32 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] 33 | # Learn more: 34 | # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed 35 | 36 | steps: 37 | - name: Checkout repository 38 | uses: actions/checkout@v3 39 | 40 | # Initializes the CodeQL tools for scanning. 41 | - name: Initialize CodeQL 42 | uses: github/codeql-action/init@v2 43 | with: 44 | languages: ${{ matrix.language }} 45 | # If you wish to specify custom queries, you can do so here or in a config file. 46 | # By default, queries listed here will override any specified in a config file. 47 | # Prefix the list here with "+" to use these queries and those in the config file. 48 | # queries: ./path/to/local/query, your-org/your-repo/queries@main 49 | 50 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 51 | # If this step fails, then you should remove it and run the build manually (see below) 52 | - name: Autobuild 53 | uses: github/codeql-action/autobuild@v2 54 | 55 | # ℹ️ Command-line programs to run using the OS shell. 56 | # 📚 https://git.io/JvXDl 57 | 58 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 59 | # and modify them (or add more) to build your code if your project 60 | # uses a compiled language 61 | 62 | #- run: | 63 | # make bootstrap 64 | # make release 65 | 66 | - name: Perform CodeQL Analysis 67 | uses: github/codeql-action/analyze@v2 68 | -------------------------------------------------------------------------------- /v6/dropbox/account/client.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) Dropbox, Inc. 2 | // 3 | // Permission is hereby granted, free of charge, to any person obtaining a copy 4 | // of this software and associated documentation files (the "Software"), to deal 5 | // in the Software without restriction, including without limitation the rights 6 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | // copies of the Software, and to permit persons to whom the Software is 8 | // furnished to do so, subject to the following conditions: 9 | // 10 | // The above copyright notice and this permission notice shall be included in 11 | // all copies or substantial portions of the Software. 12 | // 13 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | // THE SOFTWARE. 20 | 21 | package account 22 | 23 | import ( 24 | "encoding/json" 25 | "io" 26 | 27 | "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox" 28 | "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox/auth" 29 | ) 30 | 31 | // Client interface describes all routes in this namespace 32 | type Client interface { 33 | // SetProfilePhoto : Sets a user's profile photo. 34 | SetProfilePhoto(arg *SetProfilePhotoArg) (res *SetProfilePhotoResult, err error) 35 | } 36 | 37 | type apiImpl dropbox.Context 38 | 39 | //SetProfilePhotoAPIError is an error-wrapper for the set_profile_photo route 40 | type SetProfilePhotoAPIError struct { 41 | dropbox.APIError 42 | EndpointError *SetProfilePhotoError `json:"error"` 43 | } 44 | 45 | func (dbx *apiImpl) SetProfilePhoto(arg *SetProfilePhotoArg) (res *SetProfilePhotoResult, err error) { 46 | req := dropbox.Request{ 47 | Host: "api", 48 | Namespace: "account", 49 | Route: "set_profile_photo", 50 | Auth: "user", 51 | Style: "rpc", 52 | Arg: arg, 53 | ExtraHeaders: nil, 54 | } 55 | 56 | var resp []byte 57 | var respBody io.ReadCloser 58 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 59 | if err != nil { 60 | var appErr SetProfilePhotoAPIError 61 | err = auth.ParseError(err, &appErr) 62 | if err == &appErr { 63 | err = appErr 64 | } 65 | return 66 | } 67 | 68 | err = json.Unmarshal(resp, &res) 69 | if err != nil { 70 | return 71 | } 72 | 73 | _ = respBody 74 | return 75 | } 76 | 77 | // New returns a Client implementation for this namespace 78 | func New(c dropbox.Config) Client { 79 | ctx := apiImpl(dropbox.NewContext(c)) 80 | return &ctx 81 | } 82 | -------------------------------------------------------------------------------- /v6/dropbox/openid/client.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) Dropbox, Inc. 2 | // 3 | // Permission is hereby granted, free of charge, to any person obtaining a copy 4 | // of this software and associated documentation files (the "Software"), to deal 5 | // in the Software without restriction, including without limitation the rights 6 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | // copies of the Software, and to permit persons to whom the Software is 8 | // furnished to do so, subject to the following conditions: 9 | // 10 | // The above copyright notice and this permission notice shall be included in 11 | // all copies or substantial portions of the Software. 12 | // 13 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | // THE SOFTWARE. 20 | 21 | package openid 22 | 23 | import ( 24 | "encoding/json" 25 | "io" 26 | 27 | "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox" 28 | "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox/auth" 29 | ) 30 | 31 | // Client interface describes all routes in this namespace 32 | type Client interface { 33 | // Userinfo : This route is used for refreshing the info that is found in 34 | // the id_token during the OIDC flow. This route doesn't require any 35 | // arguments and will use the scopes approved for the given access token. 36 | Userinfo(arg *UserInfoArgs) (res *UserInfoResult, err error) 37 | } 38 | 39 | type apiImpl dropbox.Context 40 | 41 | //UserinfoAPIError is an error-wrapper for the userinfo route 42 | type UserinfoAPIError struct { 43 | dropbox.APIError 44 | EndpointError *UserInfoError `json:"error"` 45 | } 46 | 47 | func (dbx *apiImpl) Userinfo(arg *UserInfoArgs) (res *UserInfoResult, err error) { 48 | req := dropbox.Request{ 49 | Host: "api", 50 | Namespace: "openid", 51 | Route: "userinfo", 52 | Auth: "user", 53 | Style: "rpc", 54 | Arg: arg, 55 | ExtraHeaders: nil, 56 | } 57 | 58 | var resp []byte 59 | var respBody io.ReadCloser 60 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 61 | if err != nil { 62 | var appErr UserinfoAPIError 63 | err = auth.ParseError(err, &appErr) 64 | if err == &appErr { 65 | err = appErr 66 | } 67 | return 68 | } 69 | 70 | err = json.Unmarshal(resp, &res) 71 | if err != nil { 72 | return 73 | } 74 | 75 | _ = respBody 76 | return 77 | } 78 | 79 | // New returns a Client implementation for this namespace 80 | func New(c dropbox.Config) Client { 81 | ctx := apiImpl(dropbox.NewContext(c)) 82 | return &ctx 83 | } 84 | -------------------------------------------------------------------------------- /v6/dropbox/contacts/types.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) Dropbox, Inc. 2 | // 3 | // Permission is hereby granted, free of charge, to any person obtaining a copy 4 | // of this software and associated documentation files (the "Software"), to deal 5 | // in the Software without restriction, including without limitation the rights 6 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | // copies of the Software, and to permit persons to whom the Software is 8 | // furnished to do so, subject to the following conditions: 9 | // 10 | // The above copyright notice and this permission notice shall be included in 11 | // all copies or substantial portions of the Software. 12 | // 13 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | // THE SOFTWARE. 20 | 21 | // Package contacts : has no documentation (yet) 22 | package contacts 23 | 24 | import ( 25 | "encoding/json" 26 | 27 | "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox" 28 | ) 29 | 30 | // DeleteManualContactsArg : has no documentation (yet) 31 | type DeleteManualContactsArg struct { 32 | // EmailAddresses : List of manually added contacts to be deleted. 33 | EmailAddresses []string `json:"email_addresses"` 34 | } 35 | 36 | // NewDeleteManualContactsArg returns a new DeleteManualContactsArg instance 37 | func NewDeleteManualContactsArg(EmailAddresses []string) *DeleteManualContactsArg { 38 | s := new(DeleteManualContactsArg) 39 | s.EmailAddresses = EmailAddresses 40 | return s 41 | } 42 | 43 | // DeleteManualContactsError : has no documentation (yet) 44 | type DeleteManualContactsError struct { 45 | dropbox.Tagged 46 | // ContactsNotFound : Can't delete contacts from this list. Make sure the 47 | // list only has manually added contacts. The deletion was cancelled. 48 | ContactsNotFound []string `json:"contacts_not_found,omitempty"` 49 | } 50 | 51 | // Valid tag values for DeleteManualContactsError 52 | const ( 53 | DeleteManualContactsErrorContactsNotFound = "contacts_not_found" 54 | DeleteManualContactsErrorOther = "other" 55 | ) 56 | 57 | // UnmarshalJSON deserializes into a DeleteManualContactsError instance 58 | func (u *DeleteManualContactsError) UnmarshalJSON(body []byte) error { 59 | type wrap struct { 60 | dropbox.Tagged 61 | // ContactsNotFound : Can't delete contacts from this list. Make sure 62 | // the list only has manually added contacts. The deletion was 63 | // cancelled. 64 | ContactsNotFound []string `json:"contacts_not_found,omitempty"` 65 | } 66 | var w wrap 67 | var err error 68 | if err = json.Unmarshal(body, &w); err != nil { 69 | return err 70 | } 71 | u.Tag = w.Tag 72 | switch u.Tag { 73 | case "contacts_not_found": 74 | u.ContactsNotFound = w.ContactsNotFound 75 | 76 | } 77 | return nil 78 | } 79 | -------------------------------------------------------------------------------- /v6/dropbox/account/types.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) Dropbox, Inc. 2 | // 3 | // Permission is hereby granted, free of charge, to any person obtaining a copy 4 | // of this software and associated documentation files (the "Software"), to deal 5 | // in the Software without restriction, including without limitation the rights 6 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | // copies of the Software, and to permit persons to whom the Software is 8 | // furnished to do so, subject to the following conditions: 9 | // 10 | // The above copyright notice and this permission notice shall be included in 11 | // all copies or substantial portions of the Software. 12 | // 13 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | // THE SOFTWARE. 20 | 21 | // Package account : has no documentation (yet) 22 | package account 23 | 24 | import ( 25 | "encoding/json" 26 | 27 | "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox" 28 | ) 29 | 30 | // PhotoSourceArg : has no documentation (yet) 31 | type PhotoSourceArg struct { 32 | dropbox.Tagged 33 | // Base64Data : Image data in base64-encoded bytes. 34 | Base64Data string `json:"base64_data,omitempty"` 35 | } 36 | 37 | // Valid tag values for PhotoSourceArg 38 | const ( 39 | PhotoSourceArgBase64Data = "base64_data" 40 | PhotoSourceArgOther = "other" 41 | ) 42 | 43 | // UnmarshalJSON deserializes into a PhotoSourceArg instance 44 | func (u *PhotoSourceArg) UnmarshalJSON(body []byte) error { 45 | type wrap struct { 46 | dropbox.Tagged 47 | // Base64Data : Image data in base64-encoded bytes. 48 | Base64Data string `json:"base64_data,omitempty"` 49 | } 50 | var w wrap 51 | var err error 52 | if err = json.Unmarshal(body, &w); err != nil { 53 | return err 54 | } 55 | u.Tag = w.Tag 56 | switch u.Tag { 57 | case "base64_data": 58 | u.Base64Data = w.Base64Data 59 | 60 | } 61 | return nil 62 | } 63 | 64 | // SetProfilePhotoArg : has no documentation (yet) 65 | type SetProfilePhotoArg struct { 66 | // Photo : Image to set as the user's new profile photo. 67 | Photo *PhotoSourceArg `json:"photo"` 68 | } 69 | 70 | // NewSetProfilePhotoArg returns a new SetProfilePhotoArg instance 71 | func NewSetProfilePhotoArg(Photo *PhotoSourceArg) *SetProfilePhotoArg { 72 | s := new(SetProfilePhotoArg) 73 | s.Photo = Photo 74 | return s 75 | } 76 | 77 | // SetProfilePhotoError : has no documentation (yet) 78 | type SetProfilePhotoError struct { 79 | dropbox.Tagged 80 | } 81 | 82 | // Valid tag values for SetProfilePhotoError 83 | const ( 84 | SetProfilePhotoErrorFileTypeError = "file_type_error" 85 | SetProfilePhotoErrorFileSizeError = "file_size_error" 86 | SetProfilePhotoErrorDimensionError = "dimension_error" 87 | SetProfilePhotoErrorThumbnailError = "thumbnail_error" 88 | SetProfilePhotoErrorTransientError = "transient_error" 89 | SetProfilePhotoErrorOther = "other" 90 | ) 91 | 92 | // SetProfilePhotoResult : has no documentation (yet) 93 | type SetProfilePhotoResult struct { 94 | // ProfilePhotoUrl : URL for the photo representing the user, if one is set. 95 | ProfilePhotoUrl string `json:"profile_photo_url"` 96 | } 97 | 98 | // NewSetProfilePhotoResult returns a new SetProfilePhotoResult instance 99 | func NewSetProfilePhotoResult(ProfilePhotoUrl string) *SetProfilePhotoResult { 100 | s := new(SetProfilePhotoResult) 101 | s.ProfilePhotoUrl = ProfilePhotoUrl 102 | return s 103 | } 104 | -------------------------------------------------------------------------------- /v6/dropbox/auth/client.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) Dropbox, Inc. 2 | // 3 | // Permission is hereby granted, free of charge, to any person obtaining a copy 4 | // of this software and associated documentation files (the "Software"), to deal 5 | // in the Software without restriction, including without limitation the rights 6 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | // copies of the Software, and to permit persons to whom the Software is 8 | // furnished to do so, subject to the following conditions: 9 | // 10 | // The above copyright notice and this permission notice shall be included in 11 | // all copies or substantial portions of the Software. 12 | // 13 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | // THE SOFTWARE. 20 | 21 | package auth 22 | 23 | import ( 24 | "encoding/json" 25 | "io" 26 | 27 | "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox" 28 | ) 29 | 30 | // Client interface describes all routes in this namespace 31 | type Client interface { 32 | // TokenFromOauth1 : Creates an OAuth 2.0 access token from the supplied 33 | // OAuth 1.0 access token. 34 | TokenFromOauth1(arg *TokenFromOAuth1Arg) (res *TokenFromOAuth1Result, err error) 35 | // TokenRevoke : Disables the access token used to authenticate the call. If 36 | // there is a corresponding refresh token for the access token, this 37 | // disables that refresh token, as well as any other access tokens for that 38 | // refresh token. 39 | TokenRevoke() (err error) 40 | } 41 | 42 | type apiImpl dropbox.Context 43 | 44 | //TokenFromOauth1APIError is an error-wrapper for the token/from_oauth1 route 45 | type TokenFromOauth1APIError struct { 46 | dropbox.APIError 47 | EndpointError *TokenFromOAuth1Error `json:"error"` 48 | } 49 | 50 | func (dbx *apiImpl) TokenFromOauth1(arg *TokenFromOAuth1Arg) (res *TokenFromOAuth1Result, err error) { 51 | req := dropbox.Request{ 52 | Host: "api", 53 | Namespace: "auth", 54 | Route: "token/from_oauth1", 55 | Auth: "app", 56 | Style: "rpc", 57 | Arg: arg, 58 | ExtraHeaders: nil, 59 | } 60 | 61 | var resp []byte 62 | var respBody io.ReadCloser 63 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 64 | if err != nil { 65 | var appErr TokenFromOauth1APIError 66 | err = ParseError(err, &appErr) 67 | if err == &appErr { 68 | err = appErr 69 | } 70 | return 71 | } 72 | 73 | err = json.Unmarshal(resp, &res) 74 | if err != nil { 75 | return 76 | } 77 | 78 | _ = respBody 79 | return 80 | } 81 | 82 | //TokenRevokeAPIError is an error-wrapper for the token/revoke route 83 | type TokenRevokeAPIError struct { 84 | dropbox.APIError 85 | EndpointError struct{} `json:"error"` 86 | } 87 | 88 | func (dbx *apiImpl) TokenRevoke() (err error) { 89 | req := dropbox.Request{ 90 | Host: "api", 91 | Namespace: "auth", 92 | Route: "token/revoke", 93 | Auth: "user", 94 | Style: "rpc", 95 | Arg: nil, 96 | ExtraHeaders: nil, 97 | } 98 | 99 | var resp []byte 100 | var respBody io.ReadCloser 101 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 102 | if err != nil { 103 | var appErr TokenRevokeAPIError 104 | err = ParseError(err, &appErr) 105 | if err == &appErr { 106 | err = appErr 107 | } 108 | return 109 | } 110 | 111 | _ = resp 112 | _ = respBody 113 | return 114 | } 115 | 116 | // New returns a Client implementation for this namespace 117 | func New(c dropbox.Config) Client { 118 | ctx := apiImpl(dropbox.NewContext(c)) 119 | return &ctx 120 | } 121 | -------------------------------------------------------------------------------- /v6/dropbox/contacts/client.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) Dropbox, Inc. 2 | // 3 | // Permission is hereby granted, free of charge, to any person obtaining a copy 4 | // of this software and associated documentation files (the "Software"), to deal 5 | // in the Software without restriction, including without limitation the rights 6 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | // copies of the Software, and to permit persons to whom the Software is 8 | // furnished to do so, subject to the following conditions: 9 | // 10 | // The above copyright notice and this permission notice shall be included in 11 | // all copies or substantial portions of the Software. 12 | // 13 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | // THE SOFTWARE. 20 | 21 | package contacts 22 | 23 | import ( 24 | "io" 25 | 26 | "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox" 27 | "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox/auth" 28 | ) 29 | 30 | // Client interface describes all routes in this namespace 31 | type Client interface { 32 | // DeleteManualContacts : Removes all manually added contacts. You'll still 33 | // keep contacts who are on your team or who you imported. New contacts will 34 | // be added when you share. 35 | DeleteManualContacts() (err error) 36 | // DeleteManualContactsBatch : Removes manually added contacts from the 37 | // given list. 38 | DeleteManualContactsBatch(arg *DeleteManualContactsArg) (err error) 39 | } 40 | 41 | type apiImpl dropbox.Context 42 | 43 | //DeleteManualContactsAPIError is an error-wrapper for the delete_manual_contacts route 44 | type DeleteManualContactsAPIError struct { 45 | dropbox.APIError 46 | EndpointError struct{} `json:"error"` 47 | } 48 | 49 | func (dbx *apiImpl) DeleteManualContacts() (err error) { 50 | req := dropbox.Request{ 51 | Host: "api", 52 | Namespace: "contacts", 53 | Route: "delete_manual_contacts", 54 | Auth: "user", 55 | Style: "rpc", 56 | Arg: nil, 57 | ExtraHeaders: nil, 58 | } 59 | 60 | var resp []byte 61 | var respBody io.ReadCloser 62 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 63 | if err != nil { 64 | var appErr DeleteManualContactsAPIError 65 | err = auth.ParseError(err, &appErr) 66 | if err == &appErr { 67 | err = appErr 68 | } 69 | return 70 | } 71 | 72 | _ = resp 73 | _ = respBody 74 | return 75 | } 76 | 77 | //DeleteManualContactsBatchAPIError is an error-wrapper for the delete_manual_contacts_batch route 78 | type DeleteManualContactsBatchAPIError struct { 79 | dropbox.APIError 80 | EndpointError *DeleteManualContactsError `json:"error"` 81 | } 82 | 83 | func (dbx *apiImpl) DeleteManualContactsBatch(arg *DeleteManualContactsArg) (err error) { 84 | req := dropbox.Request{ 85 | Host: "api", 86 | Namespace: "contacts", 87 | Route: "delete_manual_contacts_batch", 88 | Auth: "user", 89 | Style: "rpc", 90 | Arg: arg, 91 | ExtraHeaders: nil, 92 | } 93 | 94 | var resp []byte 95 | var respBody io.ReadCloser 96 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 97 | if err != nil { 98 | var appErr DeleteManualContactsBatchAPIError 99 | err = auth.ParseError(err, &appErr) 100 | if err == &appErr { 101 | err = appErr 102 | } 103 | return 104 | } 105 | 106 | _ = resp 107 | _ = respBody 108 | return 109 | } 110 | 111 | // New returns a Client implementation for this namespace 112 | func New(c dropbox.Config) Client { 113 | ctx := apiImpl(dropbox.NewContext(c)) 114 | return &ctx 115 | } 116 | -------------------------------------------------------------------------------- /v6/dropbox/team_common/types.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) Dropbox, Inc. 2 | // 3 | // Permission is hereby granted, free of charge, to any person obtaining a copy 4 | // of this software and associated documentation files (the "Software"), to deal 5 | // in the Software without restriction, including without limitation the rights 6 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | // copies of the Software, and to permit persons to whom the Software is 8 | // furnished to do so, subject to the following conditions: 9 | // 10 | // The above copyright notice and this permission notice shall be included in 11 | // all copies or substantial portions of the Software. 12 | // 13 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | // THE SOFTWARE. 20 | 21 | // Package team_common : has no documentation (yet) 22 | package team_common 23 | 24 | import ( 25 | "time" 26 | 27 | "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox" 28 | ) 29 | 30 | // GroupManagementType : The group type determines how a group is managed. 31 | type GroupManagementType struct { 32 | dropbox.Tagged 33 | } 34 | 35 | // Valid tag values for GroupManagementType 36 | const ( 37 | GroupManagementTypeUserManaged = "user_managed" 38 | GroupManagementTypeCompanyManaged = "company_managed" 39 | GroupManagementTypeSystemManaged = "system_managed" 40 | GroupManagementTypeOther = "other" 41 | ) 42 | 43 | // GroupSummary : Information about a group. 44 | type GroupSummary struct { 45 | // GroupName : has no documentation (yet) 46 | GroupName string `json:"group_name"` 47 | // GroupId : has no documentation (yet) 48 | GroupId string `json:"group_id"` 49 | // GroupExternalId : External ID of group. This is an arbitrary ID that an 50 | // admin can attach to a group. 51 | GroupExternalId string `json:"group_external_id,omitempty"` 52 | // MemberCount : The number of members in the group. 53 | MemberCount uint32 `json:"member_count,omitempty"` 54 | // GroupManagementType : Who is allowed to manage the group. 55 | GroupManagementType *GroupManagementType `json:"group_management_type"` 56 | } 57 | 58 | // NewGroupSummary returns a new GroupSummary instance 59 | func NewGroupSummary(GroupName string, GroupId string, GroupManagementType *GroupManagementType) *GroupSummary { 60 | s := new(GroupSummary) 61 | s.GroupName = GroupName 62 | s.GroupId = GroupId 63 | s.GroupManagementType = GroupManagementType 64 | return s 65 | } 66 | 67 | // GroupType : The group type determines how a group is created and managed. 68 | type GroupType struct { 69 | dropbox.Tagged 70 | } 71 | 72 | // Valid tag values for GroupType 73 | const ( 74 | GroupTypeTeam = "team" 75 | GroupTypeUserManaged = "user_managed" 76 | GroupTypeOther = "other" 77 | ) 78 | 79 | // MemberSpaceLimitType : The type of the space limit imposed on a team member. 80 | type MemberSpaceLimitType struct { 81 | dropbox.Tagged 82 | } 83 | 84 | // Valid tag values for MemberSpaceLimitType 85 | const ( 86 | MemberSpaceLimitTypeOff = "off" 87 | MemberSpaceLimitTypeAlertOnly = "alert_only" 88 | MemberSpaceLimitTypeStopSync = "stop_sync" 89 | MemberSpaceLimitTypeOther = "other" 90 | ) 91 | 92 | // TimeRange : Time range. 93 | type TimeRange struct { 94 | // StartTime : Optional starting time (inclusive). 95 | StartTime *time.Time `json:"start_time,omitempty"` 96 | // EndTime : Optional ending time (exclusive). 97 | EndTime *time.Time `json:"end_time,omitempty"` 98 | } 99 | 100 | // NewTimeRange returns a new TimeRange instance 101 | func NewTimeRange() *TimeRange { 102 | s := new(TimeRange) 103 | return s 104 | } 105 | -------------------------------------------------------------------------------- /v6/dropbox/openid/types.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) Dropbox, Inc. 2 | // 3 | // Permission is hereby granted, free of charge, to any person obtaining a copy 4 | // of this software and associated documentation files (the "Software"), to deal 5 | // in the Software without restriction, including without limitation the rights 6 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | // copies of the Software, and to permit persons to whom the Software is 8 | // furnished to do so, subject to the following conditions: 9 | // 10 | // The above copyright notice and this permission notice shall be included in 11 | // all copies or substantial portions of the Software. 12 | // 13 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | // THE SOFTWARE. 20 | 21 | // Package openid : has no documentation (yet) 22 | package openid 23 | 24 | import ( 25 | "encoding/json" 26 | 27 | "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox" 28 | ) 29 | 30 | // AuthError : has no documentation (yet) 31 | type AuthError struct { 32 | dropbox.Tagged 33 | } 34 | 35 | // Valid tag values for AuthError 36 | const ( 37 | AuthErrorInvalidToken = "invalid_token" 38 | AuthErrorNoOpenidAuth = "no_openid_auth" 39 | AuthErrorOther = "other" 40 | ) 41 | 42 | // UserInfoArgs : This struct is empty. The comment here is intentionally 43 | // emitted to avoid indentation issues with Stone. 44 | type UserInfoArgs struct { 45 | } 46 | 47 | // NewUserInfoArgs returns a new UserInfoArgs instance 48 | func NewUserInfoArgs() *UserInfoArgs { 49 | s := new(UserInfoArgs) 50 | return s 51 | } 52 | 53 | // UserInfoError : has no documentation (yet) 54 | type UserInfoError struct { 55 | // Err : has no documentation (yet) 56 | Err *err_union `json:"err,omitempty"` 57 | // ErrorMessage : Brief explanation of the error. 58 | ErrorMessage string `json:"error_message"` 59 | } 60 | 61 | // NewUserInfoError returns a new UserInfoError instance 62 | func NewUserInfoError() *UserInfoError { 63 | s := new(UserInfoError) 64 | s.ErrorMessage = "" 65 | return s 66 | } 67 | 68 | // UserInfoResult : has no documentation (yet) 69 | type UserInfoResult struct { 70 | // FamilyName : Last name of user. 71 | FamilyName string `json:"family_name,omitempty"` 72 | // GivenName : First name of user. 73 | GivenName string `json:"given_name,omitempty"` 74 | // Email : Email address of user. 75 | Email string `json:"email,omitempty"` 76 | // EmailVerified : If user is email verified. 77 | EmailVerified bool `json:"email_verified,omitempty"` 78 | // Iss : Issuer of token (in this case Dropbox). 79 | Iss string `json:"iss"` 80 | // Sub : An identifier for the user. This is the Dropbox account_id, a 81 | // string value such as dbid:AAH4f99T0taONIb-OurWxbNQ6ywGRopQngc. 82 | Sub string `json:"sub"` 83 | } 84 | 85 | // NewUserInfoResult returns a new UserInfoResult instance 86 | func NewUserInfoResult() *UserInfoResult { 87 | s := new(UserInfoResult) 88 | s.Iss = "" 89 | s.Sub = "" 90 | return s 91 | } 92 | 93 | // ErrUnion : has no documentation (yet) 94 | type err_union struct { 95 | dropbox.Tagged 96 | // AuthError : has no documentation (yet) 97 | AuthError *AuthError `json:"auth_error,omitempty"` 98 | } 99 | 100 | // Valid tag values for ErrUnion 101 | const ( 102 | ErrUnionAuthError = "auth_error" 103 | ErrUnionOther = "other" 104 | ) 105 | 106 | // UnmarshalJSON deserializes into a err_union instance 107 | func (u *err_union) UnmarshalJSON(body []byte) error { 108 | type wrap struct { 109 | dropbox.Tagged 110 | // AuthError : has no documentation (yet) 111 | AuthError *AuthError `json:"auth_error,omitempty"` 112 | } 113 | var w wrap 114 | var err error 115 | if err = json.Unmarshal(body, &w); err != nil { 116 | return err 117 | } 118 | u.Tag = w.Tag 119 | switch u.Tag { 120 | case "auth_error": 121 | u.AuthError = w.AuthError 122 | 123 | } 124 | return nil 125 | } 126 | -------------------------------------------------------------------------------- /v6/dropbox/check/client.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) Dropbox, Inc. 2 | // 3 | // Permission is hereby granted, free of charge, to any person obtaining a copy 4 | // of this software and associated documentation files (the "Software"), to deal 5 | // in the Software without restriction, including without limitation the rights 6 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | // copies of the Software, and to permit persons to whom the Software is 8 | // furnished to do so, subject to the following conditions: 9 | // 10 | // The above copyright notice and this permission notice shall be included in 11 | // all copies or substantial portions of the Software. 12 | // 13 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | // THE SOFTWARE. 20 | 21 | package check 22 | 23 | import ( 24 | "encoding/json" 25 | "io" 26 | 27 | "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox" 28 | "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox/auth" 29 | ) 30 | 31 | // Client interface describes all routes in this namespace 32 | type Client interface { 33 | // App : This endpoint performs App Authentication, validating the supplied 34 | // app key and secret, and returns the supplied string, to allow you to test 35 | // your code and connection to the Dropbox API. It has no other effect. If 36 | // you receive an HTTP 200 response with the supplied query, it indicates at 37 | // least part of the Dropbox API infrastructure is working and that the app 38 | // key and secret valid. 39 | App(arg *EchoArg) (res *EchoResult, err error) 40 | // User : This endpoint performs User Authentication, validating the 41 | // supplied access token, and returns the supplied string, to allow you to 42 | // test your code and connection to the Dropbox API. It has no other effect. 43 | // If you receive an HTTP 200 response with the supplied query, it indicates 44 | // at least part of the Dropbox API infrastructure is working and that the 45 | // access token is valid. 46 | User(arg *EchoArg) (res *EchoResult, err error) 47 | } 48 | 49 | type apiImpl dropbox.Context 50 | 51 | //AppAPIError is an error-wrapper for the app route 52 | type AppAPIError struct { 53 | dropbox.APIError 54 | EndpointError struct{} `json:"error"` 55 | } 56 | 57 | func (dbx *apiImpl) App(arg *EchoArg) (res *EchoResult, err error) { 58 | req := dropbox.Request{ 59 | Host: "api", 60 | Namespace: "check", 61 | Route: "app", 62 | Auth: "app", 63 | Style: "rpc", 64 | Arg: arg, 65 | ExtraHeaders: nil, 66 | } 67 | 68 | var resp []byte 69 | var respBody io.ReadCloser 70 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 71 | if err != nil { 72 | var appErr AppAPIError 73 | err = auth.ParseError(err, &appErr) 74 | if err == &appErr { 75 | err = appErr 76 | } 77 | return 78 | } 79 | 80 | err = json.Unmarshal(resp, &res) 81 | if err != nil { 82 | return 83 | } 84 | 85 | _ = respBody 86 | return 87 | } 88 | 89 | //UserAPIError is an error-wrapper for the user route 90 | type UserAPIError struct { 91 | dropbox.APIError 92 | EndpointError struct{} `json:"error"` 93 | } 94 | 95 | func (dbx *apiImpl) User(arg *EchoArg) (res *EchoResult, err error) { 96 | req := dropbox.Request{ 97 | Host: "api", 98 | Namespace: "check", 99 | Route: "user", 100 | Auth: "user", 101 | Style: "rpc", 102 | Arg: arg, 103 | ExtraHeaders: nil, 104 | } 105 | 106 | var resp []byte 107 | var respBody io.ReadCloser 108 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 109 | if err != nil { 110 | var appErr UserAPIError 111 | err = auth.ParseError(err, &appErr) 112 | if err == &appErr { 113 | err = appErr 114 | } 115 | return 116 | } 117 | 118 | err = json.Unmarshal(resp, &res) 119 | if err != nil { 120 | return 121 | } 122 | 123 | _ = respBody 124 | return 125 | } 126 | 127 | // New returns a Client implementation for this namespace 128 | func New(c dropbox.Config) Client { 129 | ctx := apiImpl(dropbox.NewContext(c)) 130 | return &ctx 131 | } 132 | -------------------------------------------------------------------------------- /v6/dropbox/team_log/client.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) Dropbox, Inc. 2 | // 3 | // Permission is hereby granted, free of charge, to any person obtaining a copy 4 | // of this software and associated documentation files (the "Software"), to deal 5 | // in the Software without restriction, including without limitation the rights 6 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | // copies of the Software, and to permit persons to whom the Software is 8 | // furnished to do so, subject to the following conditions: 9 | // 10 | // The above copyright notice and this permission notice shall be included in 11 | // all copies or substantial portions of the Software. 12 | // 13 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | // THE SOFTWARE. 20 | 21 | package team_log 22 | 23 | import ( 24 | "encoding/json" 25 | "io" 26 | 27 | "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox" 28 | "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox/auth" 29 | ) 30 | 31 | // Client interface describes all routes in this namespace 32 | type Client interface { 33 | // GetEvents : Retrieves team events. If the result's 34 | // `GetTeamEventsResult.has_more` field is true, call `getEventsContinue` 35 | // with the returned cursor to retrieve more entries. If end_time is not 36 | // specified in your request, you may use the returned cursor to poll 37 | // `getEventsContinue` for new events. Many attributes note 'may be missing 38 | // due to historical data gap'. Note that the file_operations category and & 39 | // analogous paper events are not available on all Dropbox Business `plans` 40 | // . Use `features/get_values` 41 | // to check 42 | // for this feature. Permission : Team Auditing. 43 | GetEvents(arg *GetTeamEventsArg) (res *GetTeamEventsResult, err error) 44 | // GetEventsContinue : Once a cursor has been retrieved from `getEvents`, 45 | // use this to paginate through all events. Permission : Team Auditing. 46 | GetEventsContinue(arg *GetTeamEventsContinueArg) (res *GetTeamEventsResult, err error) 47 | } 48 | 49 | type apiImpl dropbox.Context 50 | 51 | //GetEventsAPIError is an error-wrapper for the get_events route 52 | type GetEventsAPIError struct { 53 | dropbox.APIError 54 | EndpointError *GetTeamEventsError `json:"error"` 55 | } 56 | 57 | func (dbx *apiImpl) GetEvents(arg *GetTeamEventsArg) (res *GetTeamEventsResult, err error) { 58 | req := dropbox.Request{ 59 | Host: "api", 60 | Namespace: "team_log", 61 | Route: "get_events", 62 | Auth: "team", 63 | Style: "rpc", 64 | Arg: arg, 65 | ExtraHeaders: nil, 66 | } 67 | 68 | var resp []byte 69 | var respBody io.ReadCloser 70 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 71 | if err != nil { 72 | var appErr GetEventsAPIError 73 | err = auth.ParseError(err, &appErr) 74 | if err == &appErr { 75 | err = appErr 76 | } 77 | return 78 | } 79 | 80 | err = json.Unmarshal(resp, &res) 81 | if err != nil { 82 | return 83 | } 84 | 85 | _ = respBody 86 | return 87 | } 88 | 89 | //GetEventsContinueAPIError is an error-wrapper for the get_events/continue route 90 | type GetEventsContinueAPIError struct { 91 | dropbox.APIError 92 | EndpointError *GetTeamEventsContinueError `json:"error"` 93 | } 94 | 95 | func (dbx *apiImpl) GetEventsContinue(arg *GetTeamEventsContinueArg) (res *GetTeamEventsResult, err error) { 96 | req := dropbox.Request{ 97 | Host: "api", 98 | Namespace: "team_log", 99 | Route: "get_events/continue", 100 | Auth: "team", 101 | Style: "rpc", 102 | Arg: arg, 103 | ExtraHeaders: nil, 104 | } 105 | 106 | var resp []byte 107 | var respBody io.ReadCloser 108 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 109 | if err != nil { 110 | var appErr GetEventsContinueAPIError 111 | err = auth.ParseError(err, &appErr) 112 | if err == &appErr { 113 | err = appErr 114 | } 115 | return 116 | } 117 | 118 | err = json.Unmarshal(resp, &res) 119 | if err != nil { 120 | return 121 | } 122 | 123 | _ = respBody 124 | return 125 | } 126 | 127 | // New returns a Client implementation for this namespace 128 | func New(c dropbox.Config) Client { 129 | ctx := apiImpl(dropbox.NewContext(c)) 130 | return &ctx 131 | } 132 | -------------------------------------------------------------------------------- /v6/go.sum: -------------------------------------------------------------------------------- 1 | cloud.google.com/go/compute/metadata v0.2.0/go.mod h1:zFmK7XCadkQkj6TtorcaGlCW1hT1fIilQDwofLpJ20k= 2 | github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 3 | github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= 4 | github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= 5 | github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= 6 | github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 7 | github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg= 8 | github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= 9 | github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= 10 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 11 | golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= 12 | golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= 13 | golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= 14 | golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= 15 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 16 | golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= 17 | golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= 18 | golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= 19 | golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM= 20 | golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= 21 | golang.org/x/oauth2 v0.7.0 h1:qe6s0zUXlPX80/dITx3440hWZ7GwMwgDDyrSGTPJG/g= 22 | golang.org/x/oauth2 v0.7.0/go.mod h1:hPLQkd9LyjfXTiRohC/41GhcFqxisoUQ99sCUOHO9x4= 23 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 24 | golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 25 | golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 26 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 27 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 28 | golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 29 | golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 30 | golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 31 | golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 32 | golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 33 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 34 | golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= 35 | golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= 36 | golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= 37 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 38 | golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= 39 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 40 | golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= 41 | golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= 42 | golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= 43 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 44 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= 45 | golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= 46 | golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= 47 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 48 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 49 | google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= 50 | google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= 51 | google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= 52 | google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= 53 | google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw= 54 | google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= 55 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Dropbox SDK for Go [UNOFFICIAL] [![GoDoc](https://pkg.go.dev/badge/github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox)](https://pkg.go.dev/github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox) [![Actions Status](https://github.com/dropbox/dropbox-sdk-go-unofficial/workflows/Test/badge.svg)](https://github.com/dropbox/dropbox-sdk-go-unofficial/actions) [![Actions Status](https://github.com/dropbox/dropbox-sdk-go-unofficial/workflows/Lint/badge.svg)](https://github.com/dropbox/dropbox-sdk-go-unofficial/actions) 2 | 3 | An **UNOFFICIAL** Go SDK for integrating with the Dropbox API v2. Tested with Go 1.11+ 4 | 5 | :warning: WARNING: This SDK is **NOT yet official**. What does this mean? 6 | 7 | * There is no formal Dropbox [support](https://www.dropbox.com/developers/support) for this SDK at this point 8 | * Bugs may or may not get fixed 9 | * Not all SDK features may be implemented and implemented features may be buggy or incorrect 10 | 11 | 12 | ### Uh OK, so why are you releasing this? 13 | 14 | * the SDK, while unofficial, _is_ usable. See [dbxcli](https://github.com/dropbox/dbxcli) for an example application built using the SDK 15 | * we would like to get feedback from the community and evaluate the level of interest/enthusiasm before investing into official supporting one more SDK 16 | 17 | ## Installation 18 | 19 | ```sh 20 | $ go get github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox/... 21 | ``` 22 | 23 | For most applications, you should just import the relevant namespace(s) only. The SDK exports the following sub-packages: 24 | 25 | * `github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox/auth` 26 | * `github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox/files` 27 | * `github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox/sharing` 28 | * `github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox/team` 29 | * `github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox/users` 30 | 31 | Additionally, the base `github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox` package exports some configuration and helper methods. 32 | 33 | ## Usage 34 | 35 | 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). 36 | 37 | ### Using OAuth token 38 | 39 | 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. 40 | 41 | ```go 42 | import "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox" 43 | import "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox/users" 44 | 45 | func main() { 46 | config := dropbox.Config{ 47 | Token: token, 48 | LogLevel: dropbox.LogInfo, // if needed, set the desired logging level. Default is off 49 | } 50 | dbx := users.New(config) 51 | // start making API calls 52 | } 53 | ``` 54 | 55 | ### Using OAuth2 flow 56 | 57 | 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://pkg.go.dev/golang.org/x/oauth2#example-Config) for an example of oauth2 flow in Go. 58 | 59 | Once you have the token, usage is same as above. 60 | 61 | ### Making API calls 62 | 63 | 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: 64 | 65 | * Instantiate the argument via the `New*` convenience functions in the SDK 66 | * Invoke the API 67 | * Process the response (or handle error, as below) 68 | 69 | Here's an example: 70 | 71 | ```go 72 | arg := users.NewGetAccountArg(accountId) 73 | if resp, err := dbx.GetAccount(arg); err != nil { 74 | return err 75 | } else { 76 | fmt.Printf("Name: %v", resp.Name) 77 | } 78 | ``` 79 | 80 | ### Error Handling 81 | 82 | 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. 83 | 84 | ## Note on using the Teams API 85 | 86 | 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. 87 | 88 | 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. 89 | 90 | ## Code Generation 91 | 92 | 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) 93 | for more details on how code is generated. 94 | 95 | ## Caveats 96 | 97 | * To re-iterate, this is an **UNOFFICIAL** SDK and thus has no official support from Dropbox 98 | * Only supports the v2 API. Parts of the v2 API are still in beta, and thus subject to change 99 | * This SDK itself is in beta, and so interfaces may change at any point 100 | -------------------------------------------------------------------------------- /v6/dropbox/async/types.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) Dropbox, Inc. 2 | // 3 | // Permission is hereby granted, free of charge, to any person obtaining a copy 4 | // of this software and associated documentation files (the "Software"), to deal 5 | // in the Software without restriction, including without limitation the rights 6 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | // copies of the Software, and to permit persons to whom the Software is 8 | // furnished to do so, subject to the following conditions: 9 | // 10 | // The above copyright notice and this permission notice shall be included in 11 | // all copies or substantial portions of the Software. 12 | // 13 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | // THE SOFTWARE. 20 | 21 | // Package async : has no documentation (yet) 22 | package async 23 | 24 | import ( 25 | "encoding/json" 26 | 27 | "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox" 28 | ) 29 | 30 | // LaunchResultBase : Result returned by methods that launch an asynchronous 31 | // job. A method who may either launch an asynchronous job, or complete the 32 | // request synchronously, can use this union by extending it, and adding a 33 | // 'complete' field with the type of the synchronous response. See 34 | // `LaunchEmptyResult` for an example. 35 | type LaunchResultBase struct { 36 | dropbox.Tagged 37 | // AsyncJobId : This response indicates that the processing is asynchronous. 38 | // The string is an id that can be used to obtain the status of the 39 | // asynchronous job. 40 | AsyncJobId string `json:"async_job_id,omitempty"` 41 | } 42 | 43 | // Valid tag values for LaunchResultBase 44 | const ( 45 | LaunchResultBaseAsyncJobId = "async_job_id" 46 | ) 47 | 48 | // UnmarshalJSON deserializes into a LaunchResultBase instance 49 | func (u *LaunchResultBase) UnmarshalJSON(body []byte) error { 50 | type wrap struct { 51 | dropbox.Tagged 52 | // AsyncJobId : This response indicates that the processing is 53 | // asynchronous. The string is an id that can be used to obtain the 54 | // status of the asynchronous job. 55 | AsyncJobId string `json:"async_job_id,omitempty"` 56 | } 57 | var w wrap 58 | var err error 59 | if err = json.Unmarshal(body, &w); err != nil { 60 | return err 61 | } 62 | u.Tag = w.Tag 63 | switch u.Tag { 64 | case "async_job_id": 65 | u.AsyncJobId = w.AsyncJobId 66 | 67 | } 68 | return nil 69 | } 70 | 71 | // LaunchEmptyResult : Result returned by methods that may either launch an 72 | // asynchronous job or complete synchronously. Upon synchronous completion of 73 | // the job, no additional information is returned. 74 | type LaunchEmptyResult struct { 75 | dropbox.Tagged 76 | // AsyncJobId : This response indicates that the processing is asynchronous. 77 | // The string is an id that can be used to obtain the status of the 78 | // asynchronous job. 79 | AsyncJobId string `json:"async_job_id,omitempty"` 80 | } 81 | 82 | // Valid tag values for LaunchEmptyResult 83 | const ( 84 | LaunchEmptyResultAsyncJobId = "async_job_id" 85 | LaunchEmptyResultComplete = "complete" 86 | ) 87 | 88 | // UnmarshalJSON deserializes into a LaunchEmptyResult instance 89 | func (u *LaunchEmptyResult) UnmarshalJSON(body []byte) error { 90 | type wrap struct { 91 | dropbox.Tagged 92 | // AsyncJobId : This response indicates that the processing is 93 | // asynchronous. The string is an id that can be used to obtain the 94 | // status of the asynchronous job. 95 | AsyncJobId string `json:"async_job_id,omitempty"` 96 | } 97 | var w wrap 98 | var err error 99 | if err = json.Unmarshal(body, &w); err != nil { 100 | return err 101 | } 102 | u.Tag = w.Tag 103 | switch u.Tag { 104 | case "async_job_id": 105 | u.AsyncJobId = w.AsyncJobId 106 | 107 | } 108 | return nil 109 | } 110 | 111 | // PollArg : Arguments for methods that poll the status of an asynchronous job. 112 | type PollArg struct { 113 | // AsyncJobId : Id of the asynchronous job. This is the value of a response 114 | // returned from the method that launched the job. 115 | AsyncJobId string `json:"async_job_id"` 116 | } 117 | 118 | // NewPollArg returns a new PollArg instance 119 | func NewPollArg(AsyncJobId string) *PollArg { 120 | s := new(PollArg) 121 | s.AsyncJobId = AsyncJobId 122 | return s 123 | } 124 | 125 | // PollResultBase : Result returned by methods that poll for the status of an 126 | // asynchronous job. Unions that extend this union should add a 'complete' field 127 | // with a type of the information returned upon job completion. See 128 | // `PollEmptyResult` for an example. 129 | type PollResultBase struct { 130 | dropbox.Tagged 131 | } 132 | 133 | // Valid tag values for PollResultBase 134 | const ( 135 | PollResultBaseInProgress = "in_progress" 136 | ) 137 | 138 | // PollEmptyResult : Result returned by methods that poll for the status of an 139 | // asynchronous job. Upon completion of the job, no additional information is 140 | // returned. 141 | type PollEmptyResult struct { 142 | dropbox.Tagged 143 | } 144 | 145 | // Valid tag values for PollEmptyResult 146 | const ( 147 | PollEmptyResultInProgress = "in_progress" 148 | PollEmptyResultComplete = "complete" 149 | ) 150 | 151 | // PollError : Error returned by methods for polling the status of asynchronous 152 | // job. 153 | type PollError struct { 154 | dropbox.Tagged 155 | } 156 | 157 | // Valid tag values for PollError 158 | const ( 159 | PollErrorInvalidAsyncJobId = "invalid_async_job_id" 160 | PollErrorInternalError = "internal_error" 161 | PollErrorOther = "other" 162 | ) 163 | -------------------------------------------------------------------------------- /generator/go_helpers.py: -------------------------------------------------------------------------------- 1 | from stone.ir import (ApiNamespace, ApiRoute) 2 | from stone.ir import ( 3 | Boolean, 4 | Float32, 5 | Float64, 6 | Int32, 7 | Int64, 8 | String, 9 | Timestamp, 10 | UInt32, 11 | UInt64, 12 | unwrap_nullable, 13 | is_composite_type, 14 | is_list_type, 15 | is_map_type, 16 | is_struct_type, 17 | Void, 18 | ) 19 | from stone.backends import helpers 20 | 21 | HEADER = """\ 22 | // Copyright (c) Dropbox, Inc. 23 | // 24 | // Permission is hereby granted, free of charge, to any person obtaining a copy 25 | // of this software and associated documentation files (the "Software"), to deal 26 | // in the Software without restriction, including without limitation the rights 27 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 28 | // copies of the Software, and to permit persons to whom the Software is 29 | // furnished to do so, subject to the following conditions: 30 | // 31 | // The above copyright notice and this permission notice shall be included in 32 | // all copies or substantial portions of the Software. 33 | // 34 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 35 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 36 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 37 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 38 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 39 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 40 | // THE SOFTWARE. 41 | """ 42 | 43 | _reserved_keywords = { 44 | 'break', 'default', 'func', 'interface', 'select', 45 | 'case', 'defer', 'go', 'map', 'struct', 46 | 'chan', 'else', 'goto', 'package', 'switch', 47 | 'const', 'fallthrough', 'if', 'range', 'type', 48 | 'continue', 'for', 'import', 'return', 'var', 49 | } 50 | 51 | _type_table = { 52 | UInt64: 'uint64', 53 | Int64: 'int64', 54 | UInt32: 'uint32', 55 | Int32: 'int32', 56 | Float64: 'float64', 57 | Float32: 'float32', 58 | Boolean: 'bool', 59 | String: 'string', 60 | Timestamp: 'time.Time', 61 | Void: 'struct{}', 62 | } 63 | 64 | 65 | def _rename_if_reserved(s): 66 | if s in _reserved_keywords: 67 | return s + '_' 68 | else: 69 | return s 70 | 71 | 72 | def fmt_type(data_type, namespace=None, use_interface=False, raw=False): 73 | data_type, nullable = unwrap_nullable(data_type) 74 | if is_list_type(data_type): 75 | if raw and not _needs_base_type(data_type.data_type): 76 | return "json.RawMessage" 77 | return '[]%s' % fmt_type(data_type.data_type, namespace, use_interface, raw) 78 | if is_map_type(data_type): 79 | if raw and not _needs_base_type(data_type.data_type): 80 | return "json.RawMessage" 81 | return 'map[string]%s' % fmt_type(data_type.value_data_type, namespace, use_interface, raw) 82 | if raw: 83 | return "json.RawMessage" 84 | type_name = data_type.name 85 | if use_interface and _needs_base_type(data_type): 86 | type_name = 'Is' + type_name 87 | if is_composite_type(data_type) and namespace is not None and \ 88 | namespace.name != data_type.namespace.name: 89 | type_name = data_type.namespace.name + '.' + type_name 90 | if use_interface and _needs_base_type(data_type): 91 | return _type_table.get(data_type.__class__, type_name) 92 | else: 93 | if data_type.__class__ not in _type_table: 94 | return '*' + type_name 95 | if data_type.__class__ == Timestamp: 96 | # For other primitive types, `omitempty` does the job. 97 | return ('*' if nullable else '') + _type_table[data_type.__class__] 98 | return _type_table[data_type.__class__] 99 | 100 | 101 | def fmt_var(name, export=True, check_reserved=False): 102 | s = helpers.fmt_pascal(name) if export else helpers.fmt_camel(name) 103 | return _rename_if_reserved(s) if check_reserved else s 104 | 105 | 106 | def _doc_handler(tag, val): 107 | if tag == 'type': 108 | return '`{}`'.format(val) 109 | elif tag == 'route': 110 | return '`{}`'.format(helpers.fmt_camel(val)) 111 | elif tag == 'link': 112 | anchor, link = val.rsplit(' ', 1) 113 | return '`{}` <{}>'.format(anchor, link) 114 | elif tag == 'val': 115 | if val == 'null': 116 | return 'nil' 117 | else: 118 | return val 119 | elif tag == 'field': 120 | return '`{}`'.format(val) 121 | else: 122 | raise RuntimeError('Unknown doc ref tag %r' % tag) 123 | 124 | 125 | def generate_doc(code_generator, t): 126 | doc = t.doc 127 | if doc is None: 128 | doc = 'has no documentation (yet)' 129 | doc = code_generator.process_doc(doc, _doc_handler) 130 | d = '%s : %s' % (fmt_var(t.name), doc) 131 | if isinstance(t, ApiNamespace): 132 | d = 'Package %s : %s' % (t.name, doc) 133 | code_generator.emit_wrapped_text(d, prefix='// ') 134 | 135 | # Generate comment for deprecated routes 136 | if isinstance(t, ApiRoute): 137 | if t.deprecated is not None: 138 | d = 'Deprecated: ' 139 | if t.deprecated.by is not None: 140 | deprecated_by = t.deprecated.by 141 | fn = fmt_var(deprecated_by.name) 142 | if deprecated_by.version != 1: 143 | fn += 'V%d' % deprecated_by.version 144 | d += 'Use `%s` instead' % fn 145 | code_generator.emit_wrapped_text(d, prefix='// ') 146 | 147 | 148 | def _needs_base_type(data_type): 149 | data_type, _ = unwrap_nullable(data_type) 150 | if is_struct_type(data_type) and data_type.has_enumerated_subtypes(): 151 | return True 152 | if is_list_type(data_type): 153 | return _needs_base_type(data_type.data_type) 154 | if is_map_type(data_type): 155 | return _needs_base_type(data_type.value_data_type) 156 | return False 157 | 158 | 159 | def needs_base_type(struct): 160 | for field in struct.fields: 161 | if _needs_base_type(field.data_type): 162 | return True 163 | return False 164 | -------------------------------------------------------------------------------- /generator/go_client.stoneg.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from stone.backend import CodeBackend 4 | from stone.ir import ( 5 | is_void_type, 6 | is_struct_type 7 | ) 8 | 9 | from go_helpers import ( 10 | HEADER, 11 | fmt_type, 12 | fmt_var, 13 | generate_doc, 14 | ) 15 | 16 | 17 | class GoClientBackend(CodeBackend): 18 | def generate(self, api): 19 | for namespace in api.namespaces.values(): 20 | if len(namespace.routes) > 0: 21 | self._generate_client(namespace) 22 | 23 | def _generate_client(self, namespace): 24 | file_name = os.path.join(self.target_folder_path, namespace.name, 25 | 'client.go') 26 | with self.output_to_relative_path(file_name): 27 | self.emit_raw(HEADER) 28 | self.emit() 29 | self.emit('package %s' % namespace.name) 30 | self.emit() 31 | 32 | self.emit('// Client interface describes all routes in this namespace') 33 | with self.block('type Client interface'): 34 | for route in namespace.routes: 35 | generate_doc(self, route) 36 | self.emit(self._generate_route_signature(namespace, route)) 37 | self.emit() 38 | 39 | self.emit('type apiImpl dropbox.Context') 40 | for route in namespace.routes: 41 | self._generate_route(namespace, route) 42 | self.emit('// New returns a Client implementation for this namespace') 43 | with self.block('func New(c dropbox.Config) Client'): 44 | self.emit('ctx := apiImpl(dropbox.NewContext(c))') 45 | self.emit('return &ctx') 46 | 47 | def _generate_route_signature(self, namespace, route): 48 | req = fmt_type(route.arg_data_type, namespace) 49 | res = fmt_type(route.result_data_type, namespace, use_interface=True) 50 | fn = fmt_var(route.name) 51 | if route.version != 1: 52 | fn += 'V%d' % route.version 53 | style = route.attrs.get('style', 'rpc') 54 | 55 | arg = '' if is_void_type(route.arg_data_type) else 'arg {req}' 56 | ret = '(err error)' if is_void_type(route.result_data_type) else \ 57 | '(res {res}, err error)' 58 | signature = '{fn}(' + arg + ') ' + ret 59 | if style == 'download': 60 | signature = '{fn}(' + arg + \ 61 | ') (res {res}, content io.ReadCloser, err error)' 62 | elif style == 'upload': 63 | signature = '{fn}(' + arg + ', content io.Reader) ' + ret 64 | if is_void_type(route.arg_data_type): 65 | signature = '{fn}(content io.Reader) ' + ret 66 | return signature.format(fn=fn, req=req, res=res) 67 | 68 | 69 | def _generate_route(self, namespace, route): 70 | out = self.emit 71 | 72 | route_name = route.name 73 | if route.version != 1: 74 | route_name += '_v%d' % route.version 75 | 76 | fn = fmt_var(route.name) 77 | if route.version != 1: 78 | fn += 'V%d' % route.version 79 | 80 | err = fmt_type(route.error_data_type, namespace) 81 | out('//%sAPIError is an error-wrapper for the %s route' % 82 | (fn, route_name)) 83 | with self.block('type {fn}APIError struct'.format(fn=fn)): 84 | out('dropbox.APIError') 85 | out('EndpointError {err} `json:"error"`'.format(err=err)) 86 | out() 87 | 88 | signature = 'func (dbx *apiImpl) ' + self._generate_route_signature( 89 | namespace, route) 90 | with self.block(signature): 91 | if route.deprecated is not None: 92 | out('log.Printf("WARNING: API `%s` is deprecated")' % fn) 93 | if route.deprecated.by is not None: 94 | replacement_fn = fmt_var(route.deprecated.by.name) 95 | if route.deprecated.by.version != 1: 96 | replacement_fn += "V%d" % route.deprecated.by.version 97 | out('log.Printf("Use API `%s` instead")' % replacement_fn) 98 | out() 99 | 100 | args = { 101 | "Host": route.attrs.get('host', 'api'), 102 | "Namespace": namespace.name, 103 | "Route": route_name, 104 | "Auth": route.attrs.get('auth', ''), 105 | "Style": route.attrs.get('style', 'rpc'), 106 | } 107 | 108 | with self.block('req := dropbox.Request'): 109 | for k, v in args.items(): 110 | out(k + ':"' + v + '",') 111 | 112 | out("Arg: {arg},".format(arg="arg" if not is_void_type(route.arg_data_type) else "nil")) 113 | out("ExtraHeaders: {headers},".format( 114 | headers="arg.ExtraHeaders" if fmt_var(route.name) == "Download" else "nil")) 115 | out() 116 | 117 | out("var resp []byte") 118 | out("var respBody io.ReadCloser") 119 | out("resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, {body})".format( 120 | body="content" if route.attrs.get('style', '') == 'upload' else "nil")) 121 | with self.block("if err != nil"): 122 | out("var appErr {fn}APIError".format(fn=fn)) 123 | out("err = {auth}ParseError(err, &appErr)".format( 124 | auth="auth." if namespace.name != "auth" else "")) 125 | with self.block("if err == &appErr"): 126 | out("err = appErr") 127 | out("return") 128 | out() 129 | 130 | if is_struct_type(route.result_data_type) and route.result_data_type.has_enumerated_subtypes(): 131 | out('var tmp %sUnion' % fmt_var(route.result_data_type.name, export=False)) 132 | with self.block('err = json.Unmarshal(resp, &tmp);' 133 | 'if err != nil'): 134 | out('return') 135 | with self.block('switch tmp.Tag'): 136 | for t in route.result_data_type.get_enumerated_subtypes(): 137 | with self.block('case "%s":' % t.name, delim=(None, None)): 138 | self.emit('res = tmp.%s' % fmt_var(t.name)) 139 | elif not is_void_type(route.result_data_type): 140 | with self.block('err = json.Unmarshal(resp, &res);' 141 | 'if err != nil'): 142 | out('return') 143 | out() 144 | else: 145 | out("_ = resp") 146 | 147 | if route.attrs.get('style', 'rpc') == "download": 148 | out("content = respBody") 149 | else: 150 | out("_ = respBody") 151 | out('return') 152 | out() 153 | -------------------------------------------------------------------------------- /v6/dropbox/users/client.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) Dropbox, Inc. 2 | // 3 | // Permission is hereby granted, free of charge, to any person obtaining a copy 4 | // of this software and associated documentation files (the "Software"), to deal 5 | // in the Software without restriction, including without limitation the rights 6 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | // copies of the Software, and to permit persons to whom the Software is 8 | // furnished to do so, subject to the following conditions: 9 | // 10 | // The above copyright notice and this permission notice shall be included in 11 | // all copies or substantial portions of the Software. 12 | // 13 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | // THE SOFTWARE. 20 | 21 | package users 22 | 23 | import ( 24 | "encoding/json" 25 | "io" 26 | 27 | "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox" 28 | "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox/auth" 29 | ) 30 | 31 | // Client interface describes all routes in this namespace 32 | type Client interface { 33 | // FeaturesGetValues : Get a list of feature values that may be configured 34 | // for the current account. 35 | FeaturesGetValues(arg *UserFeaturesGetValuesBatchArg) (res *UserFeaturesGetValuesBatchResult, err error) 36 | // GetAccount : Get information about a user's account. 37 | GetAccount(arg *GetAccountArg) (res *BasicAccount, err error) 38 | // GetAccountBatch : Get information about multiple user accounts. At most 39 | // 300 accounts may be queried per request. 40 | GetAccountBatch(arg *GetAccountBatchArg) (res []*BasicAccount, err error) 41 | // GetCurrentAccount : Get information about the current user's account. 42 | GetCurrentAccount() (res *FullAccount, err error) 43 | // GetSpaceUsage : Get the space usage information for the current user's 44 | // account. 45 | GetSpaceUsage() (res *SpaceUsage, err error) 46 | } 47 | 48 | type apiImpl dropbox.Context 49 | 50 | //FeaturesGetValuesAPIError is an error-wrapper for the features/get_values route 51 | type FeaturesGetValuesAPIError struct { 52 | dropbox.APIError 53 | EndpointError *UserFeaturesGetValuesBatchError `json:"error"` 54 | } 55 | 56 | func (dbx *apiImpl) FeaturesGetValues(arg *UserFeaturesGetValuesBatchArg) (res *UserFeaturesGetValuesBatchResult, err error) { 57 | req := dropbox.Request{ 58 | Host: "api", 59 | Namespace: "users", 60 | Route: "features/get_values", 61 | Auth: "user", 62 | Style: "rpc", 63 | Arg: arg, 64 | ExtraHeaders: nil, 65 | } 66 | 67 | var resp []byte 68 | var respBody io.ReadCloser 69 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 70 | if err != nil { 71 | var appErr FeaturesGetValuesAPIError 72 | err = auth.ParseError(err, &appErr) 73 | if err == &appErr { 74 | err = appErr 75 | } 76 | return 77 | } 78 | 79 | err = json.Unmarshal(resp, &res) 80 | if err != nil { 81 | return 82 | } 83 | 84 | _ = respBody 85 | return 86 | } 87 | 88 | //GetAccountAPIError is an error-wrapper for the get_account route 89 | type GetAccountAPIError struct { 90 | dropbox.APIError 91 | EndpointError *GetAccountError `json:"error"` 92 | } 93 | 94 | func (dbx *apiImpl) GetAccount(arg *GetAccountArg) (res *BasicAccount, err error) { 95 | req := dropbox.Request{ 96 | Host: "api", 97 | Namespace: "users", 98 | Route: "get_account", 99 | Auth: "user", 100 | Style: "rpc", 101 | Arg: arg, 102 | ExtraHeaders: nil, 103 | } 104 | 105 | var resp []byte 106 | var respBody io.ReadCloser 107 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 108 | if err != nil { 109 | var appErr GetAccountAPIError 110 | err = auth.ParseError(err, &appErr) 111 | if err == &appErr { 112 | err = appErr 113 | } 114 | return 115 | } 116 | 117 | err = json.Unmarshal(resp, &res) 118 | if err != nil { 119 | return 120 | } 121 | 122 | _ = respBody 123 | return 124 | } 125 | 126 | //GetAccountBatchAPIError is an error-wrapper for the get_account_batch route 127 | type GetAccountBatchAPIError struct { 128 | dropbox.APIError 129 | EndpointError *GetAccountBatchError `json:"error"` 130 | } 131 | 132 | func (dbx *apiImpl) GetAccountBatch(arg *GetAccountBatchArg) (res []*BasicAccount, err error) { 133 | req := dropbox.Request{ 134 | Host: "api", 135 | Namespace: "users", 136 | Route: "get_account_batch", 137 | Auth: "user", 138 | Style: "rpc", 139 | Arg: arg, 140 | ExtraHeaders: nil, 141 | } 142 | 143 | var resp []byte 144 | var respBody io.ReadCloser 145 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 146 | if err != nil { 147 | var appErr GetAccountBatchAPIError 148 | err = auth.ParseError(err, &appErr) 149 | if err == &appErr { 150 | err = appErr 151 | } 152 | return 153 | } 154 | 155 | err = json.Unmarshal(resp, &res) 156 | if err != nil { 157 | return 158 | } 159 | 160 | _ = respBody 161 | return 162 | } 163 | 164 | //GetCurrentAccountAPIError is an error-wrapper for the get_current_account route 165 | type GetCurrentAccountAPIError struct { 166 | dropbox.APIError 167 | EndpointError struct{} `json:"error"` 168 | } 169 | 170 | func (dbx *apiImpl) GetCurrentAccount() (res *FullAccount, err error) { 171 | req := dropbox.Request{ 172 | Host: "api", 173 | Namespace: "users", 174 | Route: "get_current_account", 175 | Auth: "user", 176 | Style: "rpc", 177 | Arg: nil, 178 | ExtraHeaders: nil, 179 | } 180 | 181 | var resp []byte 182 | var respBody io.ReadCloser 183 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 184 | if err != nil { 185 | var appErr GetCurrentAccountAPIError 186 | err = auth.ParseError(err, &appErr) 187 | if err == &appErr { 188 | err = appErr 189 | } 190 | return 191 | } 192 | 193 | err = json.Unmarshal(resp, &res) 194 | if err != nil { 195 | return 196 | } 197 | 198 | _ = respBody 199 | return 200 | } 201 | 202 | //GetSpaceUsageAPIError is an error-wrapper for the get_space_usage route 203 | type GetSpaceUsageAPIError struct { 204 | dropbox.APIError 205 | EndpointError struct{} `json:"error"` 206 | } 207 | 208 | func (dbx *apiImpl) GetSpaceUsage() (res *SpaceUsage, err error) { 209 | req := dropbox.Request{ 210 | Host: "api", 211 | Namespace: "users", 212 | Route: "get_space_usage", 213 | Auth: "user", 214 | Style: "rpc", 215 | Arg: nil, 216 | ExtraHeaders: nil, 217 | } 218 | 219 | var resp []byte 220 | var respBody io.ReadCloser 221 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 222 | if err != nil { 223 | var appErr GetSpaceUsageAPIError 224 | err = auth.ParseError(err, &appErr) 225 | if err == &appErr { 226 | err = appErr 227 | } 228 | return 229 | } 230 | 231 | err = json.Unmarshal(resp, &res) 232 | if err != nil { 233 | return 234 | } 235 | 236 | _ = respBody 237 | return 238 | } 239 | 240 | // New returns a Client implementation for this namespace 241 | func New(c dropbox.Config) Client { 242 | ctx := apiImpl(dropbox.NewContext(c)) 243 | return &ctx 244 | } 245 | -------------------------------------------------------------------------------- /v6/dropbox/common/types.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) Dropbox, Inc. 2 | // 3 | // Permission is hereby granted, free of charge, to any person obtaining a copy 4 | // of this software and associated documentation files (the "Software"), to deal 5 | // in the Software without restriction, including without limitation the rights 6 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | // copies of the Software, and to permit persons to whom the Software is 8 | // furnished to do so, subject to the following conditions: 9 | // 10 | // The above copyright notice and this permission notice shall be included in 11 | // all copies or substantial portions of the Software. 12 | // 13 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | // THE SOFTWARE. 20 | 21 | // Package common : has no documentation (yet) 22 | package common 23 | 24 | import ( 25 | "encoding/json" 26 | 27 | "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox" 28 | ) 29 | 30 | // PathRoot : has no documentation (yet) 31 | type PathRoot struct { 32 | dropbox.Tagged 33 | // Root : Paths are relative to the authenticating user's root namespace 34 | // (This results in `PathRootError.invalid_root` if the user's root 35 | // namespace has changed.). 36 | Root string `json:"root,omitempty"` 37 | // NamespaceId : Paths are relative to given namespace id (This results in 38 | // `PathRootError.no_permission` if you don't have access to this 39 | // namespace.). 40 | NamespaceId string `json:"namespace_id,omitempty"` 41 | } 42 | 43 | // Valid tag values for PathRoot 44 | const ( 45 | PathRootHome = "home" 46 | PathRootRoot = "root" 47 | PathRootNamespaceId = "namespace_id" 48 | PathRootOther = "other" 49 | ) 50 | 51 | // UnmarshalJSON deserializes into a PathRoot instance 52 | func (u *PathRoot) UnmarshalJSON(body []byte) error { 53 | type wrap struct { 54 | dropbox.Tagged 55 | // Root : Paths are relative to the authenticating user's root namespace 56 | // (This results in `PathRootError.invalid_root` if the user's root 57 | // namespace has changed.). 58 | Root string `json:"root,omitempty"` 59 | // NamespaceId : Paths are relative to given namespace id (This results 60 | // in `PathRootError.no_permission` if you don't have access to this 61 | // namespace.). 62 | NamespaceId string `json:"namespace_id,omitempty"` 63 | } 64 | var w wrap 65 | var err error 66 | if err = json.Unmarshal(body, &w); err != nil { 67 | return err 68 | } 69 | u.Tag = w.Tag 70 | switch u.Tag { 71 | case "root": 72 | u.Root = w.Root 73 | 74 | case "namespace_id": 75 | u.NamespaceId = w.NamespaceId 76 | 77 | } 78 | return nil 79 | } 80 | 81 | // PathRootError : has no documentation (yet) 82 | type PathRootError struct { 83 | dropbox.Tagged 84 | // InvalidRoot : The root namespace id in Dropbox-API-Path-Root header is 85 | // not valid. The value of this error is the user's latest root info. 86 | InvalidRoot IsRootInfo `json:"invalid_root,omitempty"` 87 | } 88 | 89 | // Valid tag values for PathRootError 90 | const ( 91 | PathRootErrorInvalidRoot = "invalid_root" 92 | PathRootErrorNoPermission = "no_permission" 93 | PathRootErrorOther = "other" 94 | ) 95 | 96 | // UnmarshalJSON deserializes into a PathRootError instance 97 | func (u *PathRootError) UnmarshalJSON(body []byte) error { 98 | type wrap struct { 99 | dropbox.Tagged 100 | // InvalidRoot : The root namespace id in Dropbox-API-Path-Root header 101 | // is not valid. The value of this error is the user's latest root info. 102 | InvalidRoot json.RawMessage `json:"invalid_root,omitempty"` 103 | } 104 | var w wrap 105 | var err error 106 | if err = json.Unmarshal(body, &w); err != nil { 107 | return err 108 | } 109 | u.Tag = w.Tag 110 | switch u.Tag { 111 | case "invalid_root": 112 | if u.InvalidRoot, err = IsRootInfoFromJSON(w.InvalidRoot); err != nil { 113 | return err 114 | } 115 | 116 | } 117 | return nil 118 | } 119 | 120 | // RootInfo : Information about current user's root. 121 | type RootInfo struct { 122 | // RootNamespaceId : The namespace ID for user's root namespace. It will be 123 | // the namespace ID of the shared team root if the user is member of a team 124 | // with a separate team root. Otherwise it will be same as 125 | // `RootInfo.home_namespace_id`. 126 | RootNamespaceId string `json:"root_namespace_id"` 127 | // HomeNamespaceId : The namespace ID for user's home namespace. 128 | HomeNamespaceId string `json:"home_namespace_id"` 129 | } 130 | 131 | // NewRootInfo returns a new RootInfo instance 132 | func NewRootInfo(RootNamespaceId string, HomeNamespaceId string) *RootInfo { 133 | s := new(RootInfo) 134 | s.RootNamespaceId = RootNamespaceId 135 | s.HomeNamespaceId = HomeNamespaceId 136 | return s 137 | } 138 | 139 | // IsRootInfo is the interface type for RootInfo and its subtypes 140 | type IsRootInfo interface { 141 | IsRootInfo() 142 | } 143 | 144 | // IsRootInfo implements the IsRootInfo interface 145 | func (u *RootInfo) IsRootInfo() {} 146 | 147 | type rootInfoUnion struct { 148 | dropbox.Tagged 149 | // Team : has no documentation (yet) 150 | Team *TeamRootInfo `json:"team,omitempty"` 151 | // User : has no documentation (yet) 152 | User *UserRootInfo `json:"user,omitempty"` 153 | } 154 | 155 | // Valid tag values for RootInfo 156 | const ( 157 | RootInfoTeam = "team" 158 | RootInfoUser = "user" 159 | ) 160 | 161 | // UnmarshalJSON deserializes into a rootInfoUnion instance 162 | func (u *rootInfoUnion) UnmarshalJSON(body []byte) error { 163 | type wrap struct { 164 | dropbox.Tagged 165 | } 166 | var w wrap 167 | var err error 168 | if err = json.Unmarshal(body, &w); err != nil { 169 | return err 170 | } 171 | u.Tag = w.Tag 172 | switch u.Tag { 173 | case "team": 174 | if err = json.Unmarshal(body, &u.Team); err != nil { 175 | return err 176 | } 177 | 178 | case "user": 179 | if err = json.Unmarshal(body, &u.User); err != nil { 180 | return err 181 | } 182 | 183 | } 184 | return nil 185 | } 186 | 187 | // IsRootInfoFromJSON converts JSON to a concrete IsRootInfo instance 188 | func IsRootInfoFromJSON(data []byte) (IsRootInfo, error) { 189 | var t rootInfoUnion 190 | if err := json.Unmarshal(data, &t); err != nil { 191 | return nil, err 192 | } 193 | switch t.Tag { 194 | case "team": 195 | return t.Team, nil 196 | 197 | case "user": 198 | return t.User, nil 199 | 200 | } 201 | return nil, nil 202 | } 203 | 204 | // TeamRootInfo : Root info when user is member of a team with a separate root 205 | // namespace ID. 206 | type TeamRootInfo struct { 207 | RootInfo 208 | // HomePath : The path for user's home directory under the shared team root. 209 | HomePath string `json:"home_path"` 210 | } 211 | 212 | // NewTeamRootInfo returns a new TeamRootInfo instance 213 | func NewTeamRootInfo(RootNamespaceId string, HomeNamespaceId string, HomePath string) *TeamRootInfo { 214 | s := new(TeamRootInfo) 215 | s.RootNamespaceId = RootNamespaceId 216 | s.HomeNamespaceId = HomeNamespaceId 217 | s.HomePath = HomePath 218 | return s 219 | } 220 | 221 | // UserRootInfo : Root info when user is not member of a team or the user is a 222 | // member of a team and the team does not have a separate root namespace. 223 | type UserRootInfo struct { 224 | RootInfo 225 | } 226 | 227 | // NewUserRootInfo returns a new UserRootInfo instance 228 | func NewUserRootInfo(RootNamespaceId string, HomeNamespaceId string) *UserRootInfo { 229 | s := new(UserRootInfo) 230 | s.RootNamespaceId = RootNamespaceId 231 | s.HomeNamespaceId = HomeNamespaceId 232 | return s 233 | } 234 | -------------------------------------------------------------------------------- /v6/dropbox/auth/types.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) Dropbox, Inc. 2 | // 3 | // Permission is hereby granted, free of charge, to any person obtaining a copy 4 | // of this software and associated documentation files (the "Software"), to deal 5 | // in the Software without restriction, including without limitation the rights 6 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | // copies of the Software, and to permit persons to whom the Software is 8 | // furnished to do so, subject to the following conditions: 9 | // 10 | // The above copyright notice and this permission notice shall be included in 11 | // all copies or substantial portions of the Software. 12 | // 13 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | // THE SOFTWARE. 20 | 21 | // Package auth : has no documentation (yet) 22 | package auth 23 | 24 | import ( 25 | "encoding/json" 26 | 27 | "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox" 28 | ) 29 | 30 | // AccessError : Error occurred because the account doesn't have permission to 31 | // access the resource. 32 | type AccessError struct { 33 | dropbox.Tagged 34 | // InvalidAccountType : Current account type cannot access the resource. 35 | InvalidAccountType *InvalidAccountTypeError `json:"invalid_account_type,omitempty"` 36 | // PaperAccessDenied : Current account cannot access Paper. 37 | PaperAccessDenied *PaperAccessError `json:"paper_access_denied,omitempty"` 38 | } 39 | 40 | // Valid tag values for AccessError 41 | const ( 42 | AccessErrorInvalidAccountType = "invalid_account_type" 43 | AccessErrorPaperAccessDenied = "paper_access_denied" 44 | AccessErrorOther = "other" 45 | ) 46 | 47 | // UnmarshalJSON deserializes into a AccessError instance 48 | func (u *AccessError) UnmarshalJSON(body []byte) error { 49 | type wrap struct { 50 | dropbox.Tagged 51 | // InvalidAccountType : Current account type cannot access the resource. 52 | InvalidAccountType *InvalidAccountTypeError `json:"invalid_account_type,omitempty"` 53 | // PaperAccessDenied : Current account cannot access Paper. 54 | PaperAccessDenied *PaperAccessError `json:"paper_access_denied,omitempty"` 55 | } 56 | var w wrap 57 | var err error 58 | if err = json.Unmarshal(body, &w); err != nil { 59 | return err 60 | } 61 | u.Tag = w.Tag 62 | switch u.Tag { 63 | case "invalid_account_type": 64 | u.InvalidAccountType = w.InvalidAccountType 65 | 66 | case "paper_access_denied": 67 | u.PaperAccessDenied = w.PaperAccessDenied 68 | 69 | } 70 | return nil 71 | } 72 | 73 | // AuthError : Errors occurred during authentication. 74 | type AuthError struct { 75 | dropbox.Tagged 76 | // MissingScope : The access token does not have the required scope to 77 | // access the route. 78 | MissingScope *TokenScopeError `json:"missing_scope,omitempty"` 79 | } 80 | 81 | // Valid tag values for AuthError 82 | const ( 83 | AuthErrorInvalidAccessToken = "invalid_access_token" 84 | AuthErrorInvalidSelectUser = "invalid_select_user" 85 | AuthErrorInvalidSelectAdmin = "invalid_select_admin" 86 | AuthErrorUserSuspended = "user_suspended" 87 | AuthErrorExpiredAccessToken = "expired_access_token" 88 | AuthErrorMissingScope = "missing_scope" 89 | AuthErrorRouteAccessDenied = "route_access_denied" 90 | AuthErrorOther = "other" 91 | ) 92 | 93 | // UnmarshalJSON deserializes into a AuthError instance 94 | func (u *AuthError) UnmarshalJSON(body []byte) error { 95 | type wrap struct { 96 | dropbox.Tagged 97 | } 98 | var w wrap 99 | var err error 100 | if err = json.Unmarshal(body, &w); err != nil { 101 | return err 102 | } 103 | u.Tag = w.Tag 104 | switch u.Tag { 105 | case "missing_scope": 106 | if err = json.Unmarshal(body, &u.MissingScope); err != nil { 107 | return err 108 | } 109 | 110 | } 111 | return nil 112 | } 113 | 114 | // InvalidAccountTypeError : has no documentation (yet) 115 | type InvalidAccountTypeError struct { 116 | dropbox.Tagged 117 | } 118 | 119 | // Valid tag values for InvalidAccountTypeError 120 | const ( 121 | InvalidAccountTypeErrorEndpoint = "endpoint" 122 | InvalidAccountTypeErrorFeature = "feature" 123 | InvalidAccountTypeErrorOther = "other" 124 | ) 125 | 126 | // PaperAccessError : has no documentation (yet) 127 | type PaperAccessError struct { 128 | dropbox.Tagged 129 | } 130 | 131 | // Valid tag values for PaperAccessError 132 | const ( 133 | PaperAccessErrorPaperDisabled = "paper_disabled" 134 | PaperAccessErrorNotPaperUser = "not_paper_user" 135 | PaperAccessErrorOther = "other" 136 | ) 137 | 138 | // RateLimitError : Error occurred because the app is being rate limited. 139 | type RateLimitError struct { 140 | // Reason : The reason why the app is being rate limited. 141 | Reason *RateLimitReason `json:"reason"` 142 | // RetryAfter : The number of seconds that the app should wait before making 143 | // another request. 144 | RetryAfter uint64 `json:"retry_after"` 145 | } 146 | 147 | // NewRateLimitError returns a new RateLimitError instance 148 | func NewRateLimitError(Reason *RateLimitReason) *RateLimitError { 149 | s := new(RateLimitError) 150 | s.Reason = Reason 151 | s.RetryAfter = 1 152 | return s 153 | } 154 | 155 | // RateLimitReason : has no documentation (yet) 156 | type RateLimitReason struct { 157 | dropbox.Tagged 158 | } 159 | 160 | // Valid tag values for RateLimitReason 161 | const ( 162 | RateLimitReasonTooManyRequests = "too_many_requests" 163 | RateLimitReasonTooManyWriteOperations = "too_many_write_operations" 164 | RateLimitReasonOther = "other" 165 | ) 166 | 167 | // TokenFromOAuth1Arg : has no documentation (yet) 168 | type TokenFromOAuth1Arg struct { 169 | // Oauth1Token : The supplied OAuth 1.0 access token. 170 | Oauth1Token string `json:"oauth1_token"` 171 | // Oauth1TokenSecret : The token secret associated with the supplied access 172 | // token. 173 | Oauth1TokenSecret string `json:"oauth1_token_secret"` 174 | } 175 | 176 | // NewTokenFromOAuth1Arg returns a new TokenFromOAuth1Arg instance 177 | func NewTokenFromOAuth1Arg(Oauth1Token string, Oauth1TokenSecret string) *TokenFromOAuth1Arg { 178 | s := new(TokenFromOAuth1Arg) 179 | s.Oauth1Token = Oauth1Token 180 | s.Oauth1TokenSecret = Oauth1TokenSecret 181 | return s 182 | } 183 | 184 | // TokenFromOAuth1Error : has no documentation (yet) 185 | type TokenFromOAuth1Error struct { 186 | dropbox.Tagged 187 | } 188 | 189 | // Valid tag values for TokenFromOAuth1Error 190 | const ( 191 | TokenFromOAuth1ErrorInvalidOauth1TokenInfo = "invalid_oauth1_token_info" 192 | TokenFromOAuth1ErrorAppIdMismatch = "app_id_mismatch" 193 | TokenFromOAuth1ErrorOther = "other" 194 | ) 195 | 196 | // TokenFromOAuth1Result : has no documentation (yet) 197 | type TokenFromOAuth1Result struct { 198 | // Oauth2Token : The OAuth 2.0 token generated from the supplied OAuth 1.0 199 | // token. 200 | Oauth2Token string `json:"oauth2_token"` 201 | } 202 | 203 | // NewTokenFromOAuth1Result returns a new TokenFromOAuth1Result instance 204 | func NewTokenFromOAuth1Result(Oauth2Token string) *TokenFromOAuth1Result { 205 | s := new(TokenFromOAuth1Result) 206 | s.Oauth2Token = Oauth2Token 207 | return s 208 | } 209 | 210 | // TokenScopeError : has no documentation (yet) 211 | type TokenScopeError struct { 212 | // RequiredScope : The required scope to access the route. 213 | RequiredScope string `json:"required_scope"` 214 | } 215 | 216 | // NewTokenScopeError returns a new TokenScopeError instance 217 | func NewTokenScopeError(RequiredScope string) *TokenScopeError { 218 | s := new(TokenScopeError) 219 | s.RequiredScope = RequiredScope 220 | return s 221 | } 222 | -------------------------------------------------------------------------------- /v6/dropbox/sdk_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) Dropbox, Inc. 2 | // 3 | // Permission is hereby granted, free of charge, to any person obtaining a copy 4 | // of this software and associated documentation files (the "Software"), to deal 5 | // in the Software without restriction, including without limitation the rights 6 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | // copies of the Software, and to permit persons to whom the Software is 8 | // furnished to do so, subject to the following conditions: 9 | // 10 | // The above copyright notice and this permission notice shall be included in 11 | // all copies or substantial portions of the Software. 12 | // 13 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | // THE SOFTWARE. 20 | 21 | package dropbox_test 22 | 23 | import ( 24 | "encoding/json" 25 | "fmt" 26 | "net/http" 27 | "net/http/httptest" 28 | "strings" 29 | "testing" 30 | 31 | "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox" 32 | "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox/auth" 33 | "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox/users" 34 | ) 35 | 36 | func generateURL(base string, namespace string, route string) string { 37 | return fmt.Sprintf("%s/%s/%s", base, namespace, route) 38 | } 39 | 40 | func TestInternalError(t *testing.T) { 41 | eString := "internal server error" 42 | ts := httptest.NewServer(http.HandlerFunc( 43 | func(w http.ResponseWriter, r *http.Request) { 44 | http.Error(w, eString, http.StatusInternalServerError) 45 | })) 46 | defer ts.Close() 47 | 48 | config := dropbox.Config{Client: ts.Client(), LogLevel: dropbox.LogDebug, 49 | URLGenerator: func(hostType string, namespace string, route string) string { 50 | return generateURL(ts.URL, namespace, route) 51 | }} 52 | client := users.New(config) 53 | v, e := client.GetCurrentAccount() 54 | if v != nil || strings.Trim(e.Error(), "\n") != eString { 55 | t.Errorf("v: %v e: '%s'\n", v, e.Error()) 56 | } 57 | } 58 | 59 | func TestRateLimitJSON(t *testing.T) { 60 | eString := `{"error_summary": "too_many_requests/..", "error": {"reason": {".tag": "too_many_requests"}, "retry_after": 300}}` 61 | ts := httptest.NewServer(http.HandlerFunc( 62 | func(w http.ResponseWriter, r *http.Request) { 63 | w.Header().Set("Content-Type", "application/json; charset=utf-8") 64 | w.Header().Set("Retry-After", "10") 65 | w.WriteHeader(http.StatusTooManyRequests) 66 | _, _ = w.Write([]byte(eString)) 67 | })) 68 | defer ts.Close() 69 | 70 | config := dropbox.Config{Client: ts.Client(), LogLevel: dropbox.LogDebug, 71 | URLGenerator: func(hostType string, namespace string, route string) string { 72 | return generateURL(ts.URL, namespace, route) 73 | }} 74 | client := users.New(config) 75 | _, e := client.GetCurrentAccount() 76 | re, ok := e.(auth.RateLimitAPIError) 77 | if !ok { 78 | t.Errorf("Unexpected error type: %T\n", e) 79 | } 80 | if re.RateLimitError.RetryAfter != 300 { 81 | t.Errorf("Unexpected retry-after value: %d\n", re.RateLimitError.RetryAfter) 82 | } 83 | if re.RateLimitError.Reason.Tag != auth.RateLimitReasonTooManyRequests { 84 | t.Errorf("Unexpected reason: %v\n", re.RateLimitError.Reason) 85 | } 86 | } 87 | 88 | func TestAuthError(t *testing.T) { 89 | eString := `{"error_summary": "user_suspended/...", "error": {".tag": "user_suspended"}}` 90 | ts := httptest.NewServer(http.HandlerFunc( 91 | func(w http.ResponseWriter, r *http.Request) { 92 | w.Header().Set("Content-Type", "application/json; charset=utf-8") 93 | w.WriteHeader(http.StatusUnauthorized) 94 | _, _ = w.Write([]byte(eString)) 95 | })) 96 | defer ts.Close() 97 | 98 | config := dropbox.Config{Client: ts.Client(), LogLevel: dropbox.LogDebug, 99 | URLGenerator: func(hostType string, namespace string, route string) string { 100 | return generateURL(ts.URL, namespace, route) 101 | }} 102 | client := users.New(config) 103 | _, e := client.GetCurrentAccount() 104 | re, ok := e.(auth.AuthAPIError) 105 | if !ok { 106 | t.Errorf("Unexpected error type: %T\n", e) 107 | } 108 | fmt.Printf("ERROR is %v\n", re) 109 | if re.AuthError.Tag != auth.AuthErrorUserSuspended { 110 | t.Errorf("Unexpected tag: %s\n", re.AuthError.Tag) 111 | } 112 | } 113 | 114 | func TestAccessError(t *testing.T) { 115 | eString := `{"error_summary": "access_error/...", 116 | "error": { 117 | ".tag": "paper_access_denied", 118 | "paper_access_denied": {".tag": "not_paper_user"} 119 | }}` 120 | ts := httptest.NewServer(http.HandlerFunc( 121 | func(w http.ResponseWriter, r *http.Request) { 122 | w.Header().Set("Content-Type", "application/json; charset=utf-8") 123 | w.WriteHeader(http.StatusForbidden) 124 | _, _ = w.Write([]byte(eString)) 125 | })) 126 | defer ts.Close() 127 | 128 | config := dropbox.Config{Client: ts.Client(), LogLevel: dropbox.LogDebug, 129 | URLGenerator: func(hostType string, namespace string, route string) string { 130 | return generateURL(ts.URL, namespace, route) 131 | }} 132 | client := users.New(config) 133 | _, e := client.GetCurrentAccount() 134 | re, ok := e.(auth.AccessAPIError) 135 | if !ok { 136 | t.Errorf("Unexpected error type: %T\n", e) 137 | } 138 | if re.AccessError.Tag != auth.AccessErrorPaperAccessDenied { 139 | t.Errorf("Unexpected tag: %s\n", re.AccessError.Tag) 140 | } 141 | if re.AccessError.PaperAccessDenied.Tag != auth.PaperAccessErrorNotPaperUser { 142 | t.Errorf("Unexpected tag: %s\n", re.AccessError.PaperAccessDenied.Tag) 143 | } 144 | } 145 | 146 | func TestAppError(t *testing.T) { 147 | eString := `{"error_summary":"","error":{".tag":"app_id_mismatch"}}` 148 | ts := httptest.NewServer(http.HandlerFunc( 149 | func(w http.ResponseWriter, r *http.Request) { 150 | w.Header().Set("Content-Type", "application/json; charset=utf-8") 151 | w.WriteHeader(http.StatusConflict) 152 | _, _ = w.Write([]byte(eString)) 153 | })) 154 | defer ts.Close() 155 | 156 | config := dropbox.Config{Client: ts.Client(), LogLevel: dropbox.LogDebug, 157 | URLGenerator: func(hostType string, namespace string, route string) string { 158 | return generateURL(ts.URL, namespace, route) 159 | }} 160 | client := auth.New(config) 161 | _, e := client.TokenFromOauth1(nil) 162 | re, ok := e.(auth.TokenFromOauth1APIError) 163 | if !ok { 164 | t.Errorf("Unexpected error type: %T\n%v\n", e, e) 165 | } 166 | if re.EndpointError.Tag != auth.TokenFromOAuth1ErrorAppIdMismatch { 167 | t.Errorf("Unexpected tag: %s\n", re.EndpointError.Tag) 168 | } 169 | } 170 | 171 | func TestHTTPHeaderSafeJSON(t *testing.T) { 172 | for _, test := range []struct { 173 | name string 174 | in interface{} 175 | want string 176 | }{ 177 | { 178 | name: "empty string", 179 | in: ``, 180 | want: `""`, 181 | }, 182 | { 183 | name: "integer", 184 | in: 123, 185 | want: `123`, 186 | }, 187 | { 188 | name: "normal string", 189 | in: `Normal string!`, 190 | want: `"Normal string!"`, 191 | }, 192 | { 193 | name: "unicode", 194 | in: `üñîcødé`, 195 | want: `"\u00fc\u00f1\u00eec\u00f8d\u00e9"`, 196 | }, 197 | { 198 | name: "7f", 199 | in: "\x7f", 200 | want: `"\u007f"`, 201 | }, 202 | { 203 | name: "example from the docs", 204 | in: struct { 205 | Field string `json:"field"` 206 | }{ 207 | Field: "some_üñîcødé_and_\x7F", 208 | }, 209 | want: `{"field":"some_\u00fc\u00f1\u00eec\u00f8d\u00e9_and_\u007f"}`, 210 | }, 211 | } { 212 | t.Run(test.name, func(t *testing.T) { 213 | b, err := json.Marshal(test.in) 214 | if err != nil { 215 | t.Fatal(err) 216 | } 217 | got := dropbox.HTTPHeaderSafeJSON(b) 218 | if got != test.want { 219 | t.Errorf("Want %q got %q", test.want, got) 220 | } 221 | }) 222 | } 223 | } 224 | -------------------------------------------------------------------------------- /generator/README.md: -------------------------------------------------------------------------------- 1 | # Dropbox Go SDK Generator 2 | 3 | This directory contains the [Stone](https://github.com/dropbox/stone) code generators 4 | used to programmatically generate the [Dropbox Go SDK](https://github.com/dropbox/dropbox-sdk-go). 5 | 6 | ## Requirements 7 | 8 | * While not a hard requirement, this repo currently assumes `python3` in the path. 9 | * Assumes you have already installed [Stone](https://github.com/dropbox/stone) and have `stone` in the path. 10 | * Requires [goimports](https://godoc.org/golang.org/x/tools/cmd/goimports) in the path to fix up imports in the auto-generated code. 11 | 12 | ## Basic Setup 13 | 14 | * Clone this repo 15 | * Run `git submodule init` followed by `git submodule update`. To fetch the latest API spec, use `git submodule update --remote` 16 | * Run `./generate-sdk.sh X.Y.Z`, where `X.Y.Z` is the desired version number, to generate code under `../vX/dropbox` 17 | 18 | ## Generated Code 19 | 20 | ### Basic Types 21 | 22 | Here is how Stone [basic types](https://github.com/dropbox/stone/blob/master/doc/lang_ref.rst#basic-types) map to Go types: 23 | 24 | Stone Type | Go Type 25 | ---------- | ------- 26 | Int32/Int64/UInt32/UInt64 | int32/int64/uint32/uint64 27 | Float32/Float64 | float32/float64 28 | Boolean | bool 29 | String | string 30 | Timestamp | time.Time 31 | Void | struct{} 32 | 33 | ### Structs 34 | 35 | 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. 36 | 37 | ``` 38 | struct Account 39 | "The amount of detail revealed about an account depends on the user 40 | being queried and the user making the query." 41 | 42 | account_id AccountId 43 | "The user's unique Dropbox ID." 44 | name Name 45 | "Details of a user's name." 46 | ``` 47 | 48 | ```go 49 | // The amount of detail revealed about an account depends on the user being 50 | // queried and the user making the query. 51 | type Account struct { 52 | // The user's unique Dropbox ID. 53 | AccountId string `json:"account_id"` 54 | // Details of a user's name. 55 | Name *Name `json:"name"` 56 | } 57 | ``` 58 | 59 | #### Inheritance 60 | 61 | 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) 62 | 63 | ``` 64 | struct BasicAccount extends Account 65 | "Basic information about any account." 66 | 67 | is_teammate Boolean 68 | "Whether this user is a teammate of the current user. If this account 69 | is the current user's account, then this will be :val:`true`." 70 | ``` 71 | 72 | ```go 73 | // Basic information about any account. 74 | type BasicAccount struct { 75 | Account 76 | // Whether this user is a teammate of the current user. If this account is 77 | // the current user's account, then this will be `True`. 78 | IsTeammate bool `json:"is_teammate"` 79 | ``` 80 | 81 | ### Unions 82 | 83 | 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. 84 | 85 | ``` 86 | union SpaceAllocation 87 | "Space is allocated differently based on the type of account." 88 | 89 | individual IndividualSpaceAllocation 90 | "The user's space allocation applies only to their individual account." 91 | team TeamSpaceAllocation 92 | "The user shares space with other members of their team." 93 | ``` 94 | 95 | ```go 96 | // Space is allocated differently based on the type of account. 97 | type SpaceAllocation struct { 98 | dropbox.Tagged 99 | // The user's space allocation applies only to their individual account. 100 | Individual *IndividualSpaceAllocation `json:"individual,omitempty"` 101 | // The user shares space with other members of their team. 102 | Team *TeamSpaceAllocation `json:"team,omitempty"` 103 | } 104 | 105 | // Valid tag values for `SpaceAllocation` 106 | const ( 107 | SpaceAllocation_Individual = "individual" 108 | SpaceAllocation_Team = "team" 109 | SpaceAllocation_Other = "other" 110 | ) 111 | 112 | func (u *SpaceAllocation) UnmarshalJSON(body []byte) error { 113 | type wrap struct { 114 | dropbox.Tagged 115 | // The user's space allocation applies only to their individual account. 116 | Individual json.RawMessage `json:"individual,omitempty"` 117 | // The user shares space with other members of their team. 118 | Team json.RawMessage `json:"team,omitempty"` 119 | } 120 | var w wrap 121 | if err := json.Unmarshal(body, &w); err != nil { 122 | return err 123 | } 124 | u.Tag = w.Tag 125 | switch u.Tag { 126 | case "individual": 127 | if err := json.Unmarshal(body, &u.Individual); err != nil { 128 | return err 129 | } 130 | 131 | case "team": 132 | if err := json.Unmarshal(body, &u.Team); err != nil { 133 | return err 134 | } 135 | 136 | } 137 | return nil 138 | } 139 | ``` 140 | 141 | ### Struct with Enumerated Subtypes 142 | 143 | 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: 144 | 145 | > 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. 146 | 147 | To represent structs with enumerated subtypes in Go, we use a combination of Go interface types and unions as implemented above. Considering the following: 148 | 149 | ``` 150 | struct Metadata 151 | union 152 | file FileMetadata 153 | folder FolderMetadata 154 | deleted DeletedMetadata # Used by list_folder* and search 155 | 156 | name String 157 | path_lower String? 158 | path_display String? 159 | parent_shared_folder_id common.SharedFolderId? 160 | 161 | struct FileMetadata extends Metadata 162 | id Id 163 | client_modified common.DropboxTimestamp 164 | ... 165 | ``` 166 | 167 | 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. 168 | 169 | First, we define structs to represent the base and enumerated types as we did for inherited structs above: 170 | 171 | ```go 172 | type Metadata struct { 173 | Name string `json:"name"` 174 | PathLower string `json:"path_lower,omitempty"` 175 | PathDisplay string `json:"path_display,omitempty"` 176 | ParentSharedFolderId string `json:"parent_shared_folder_id,omitempty"` 177 | } 178 | 179 | type FileMetadata struct { 180 | Metadata 181 | Id string `json:"id"` 182 | ClientModified time.Time `json:"client_modified"` 183 | ... 184 | } 185 | ``` 186 | 187 | Next, we define an interface type with a dummy method and ensure that both the base and the subtypes implement the interface: 188 | 189 | ```go 190 | type IsMetadata interface { 191 | IsMetadata() 192 | } 193 | 194 | func (u *Metadata) IsMetadata() {} // Subtypes get this for free due to embedding 195 | ``` 196 | 197 | At this point, types or methods that accept/return a struct with enumerated subtypes can use the interface type instead. For instance: 198 | 199 | ```go 200 | func GetMetadata(arg *GetMetadataArg) (res IsMetadata, err error) {...} 201 | 202 | type ListFolderResult struct { 203 | // The files and (direct) subfolders in the folder. 204 | Entries []IsMetadata `json:"entries"` 205 | ... 206 | } 207 | ``` 208 | 209 | 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. 210 | 211 | ```go 212 | type metadataUnion struct { 213 | dropbox.Tagged 214 | File *FileMetadata `json:"file,omitempty"` 215 | Folder *FolderMetadata `json:"folder,omitempty"` 216 | Deleted *DeletedMetadata `json:"deleted,omitempty"` 217 | } 218 | 219 | func (u *metadataUnion) UnmarshalJSON(body []byte) error {...} 220 | 221 | func (dbx *apiImpl) GetMetadata(arg *GetMetadataArg) (res IsMetadata, err error) { 222 | ... 223 | var tmp metadataUnion 224 | err = json.Unmarshal(body, &tmp) 225 | if err != nil { 226 | return 227 | } 228 | switch tmp.Tag { 229 | case "file": 230 | res = tmp.File 231 | case "folder": 232 | res = tmp.Folder 233 | case "deleted": 234 | res = tmp.Deleted 235 | } 236 | } 237 | ``` 238 | -------------------------------------------------------------------------------- /v6/dropbox/sdk.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) Dropbox, Inc. 2 | // 3 | // Permission is hereby granted, free of charge, to any person obtaining a copy 4 | // of this software and associated documentation files (the "Software"), to deal 5 | // in the Software without restriction, including without limitation the rights 6 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | // copies of the Software, and to permit persons to whom the Software is 8 | // furnished to do so, subject to the following conditions: 9 | // 10 | // The above copyright notice and this permission notice shall be included in 11 | // all copies or substantial portions of the Software. 12 | // 13 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | // THE SOFTWARE. 20 | 21 | package dropbox 22 | 23 | import ( 24 | "bytes" 25 | "context" 26 | "encoding/json" 27 | "errors" 28 | "fmt" 29 | "io" 30 | "io/ioutil" 31 | "log" 32 | "net/http" 33 | "strings" 34 | 35 | "golang.org/x/oauth2" 36 | ) 37 | 38 | const ( 39 | apiVersion = 2 40 | defaultDomain = ".dropboxapi.com" 41 | hostAPI = "api" 42 | hostContent = "content" 43 | hostNotify = "notify" 44 | sdkVersion = "6.0.5" 45 | specVersion = "c36ba27" 46 | ) 47 | 48 | // Version returns the current SDK version and API Spec version 49 | func Version() (string, string) { 50 | return sdkVersion, specVersion 51 | } 52 | 53 | // Tagged is used for tagged unions. 54 | type Tagged struct { 55 | Tag string `json:".tag"` 56 | } 57 | 58 | // APIError is the base type for endpoint-specific errors. 59 | type APIError struct { 60 | ErrorSummary string `json:"error_summary"` 61 | } 62 | 63 | func (e APIError) Error() string { 64 | return e.ErrorSummary 65 | } 66 | 67 | type SDKInternalError struct { 68 | StatusCode int 69 | Content string 70 | } 71 | 72 | func (e SDKInternalError) Error() string { 73 | return fmt.Sprintf("Unexpected error: %v (code: %v)", e.Content, e.StatusCode) 74 | } 75 | 76 | // Config contains parameters for configuring the SDK. 77 | type Config struct { 78 | // OAuth2 access token 79 | Token string 80 | // Logging level for SDK generated logs 81 | LogLevel LogLevel 82 | // Logging target for verbose SDK logging 83 | Logger *log.Logger 84 | // Used with APIs that support operations as another user 85 | AsMemberID string 86 | // Used with APIs that support operations as an admin 87 | AsAdminID string 88 | // Path relative to which action should be taken 89 | PathRoot string 90 | // No need to set -- for testing only 91 | Domain string 92 | // No need to set -- for testing only 93 | Client *http.Client 94 | // No need to set -- for testing only 95 | HeaderGenerator func(hostType string, namespace string, route string) map[string]string 96 | // No need to set -- for testing only 97 | URLGenerator func(hostType string, namespace string, route string) string 98 | } 99 | 100 | // LogLevel defines a type that can set the desired level of logging the SDK will generate. 101 | type LogLevel uint 102 | 103 | const ( 104 | // LogOff will disable all SDK logging. This is the default log level 105 | LogOff LogLevel = iota * (1 << 8) 106 | // LogDebug will enable detailed SDK debug logs. It will log requests (including arguments), 107 | // response and body contents. 108 | LogDebug 109 | // LogInfo will log SDK request (not including arguments) and responses. 110 | LogInfo 111 | ) 112 | 113 | func (l LogLevel) shouldLog(v LogLevel) bool { 114 | return l > v || l&v == v 115 | } 116 | 117 | func (c *Config) doLog(l LogLevel, format string, v ...interface{}) { 118 | if !c.LogLevel.shouldLog(l) { 119 | return 120 | } 121 | 122 | if c.Logger != nil { 123 | c.Logger.Printf(format, v...) 124 | } else { 125 | log.Printf(format, v...) 126 | } 127 | } 128 | 129 | // LogDebug emits a debug level SDK log if config's log level is at least LogDebug 130 | func (c *Config) LogDebug(format string, v ...interface{}) { 131 | c.doLog(LogDebug, format, v...) 132 | } 133 | 134 | // LogInfo emits an info level SDK log if config's log level is at least LogInfo 135 | func (c *Config) LogInfo(format string, v ...interface{}) { 136 | c.doLog(LogInfo, format, v...) 137 | } 138 | 139 | // Ergonomic methods to set namespace relative to which action should be taken 140 | func (c Config) WithNamespaceID(nsID string) Config { 141 | c.PathRoot = fmt.Sprintf(`{".tag": "namespace_id", "namespace_id": "%s"}`, nsID) 142 | return c 143 | } 144 | 145 | func (c Config) WithRoot(nsID string) Config { 146 | c.PathRoot = fmt.Sprintf(`{".tag": "root", "root": "%s"}`, nsID) 147 | return c 148 | } 149 | 150 | // Context is the base client context used to implement per-namespace clients. 151 | type Context struct { 152 | Config Config 153 | Client *http.Client 154 | NoAuthClient *http.Client 155 | HeaderGenerator func(hostType string, namespace string, route string) map[string]string 156 | URLGenerator func(hostType string, namespace string, route string) string 157 | } 158 | 159 | type Request struct { 160 | Host string 161 | Namespace string 162 | Route string 163 | Style string 164 | Auth string 165 | 166 | Arg interface{} 167 | ExtraHeaders map[string]string 168 | } 169 | 170 | func (c *Context) Execute(req Request, body io.Reader) ([]byte, io.ReadCloser, error) { 171 | url := c.URLGenerator(req.Host, req.Namespace, req.Route) 172 | httpReq, err := http.NewRequest("POST", url, body) 173 | if err != nil { 174 | return nil, nil, err 175 | } 176 | 177 | for k, v := range req.ExtraHeaders { 178 | httpReq.Header.Add(k, v) 179 | } 180 | 181 | for k, v := range c.HeaderGenerator(req.Host, req.Namespace, req.Route) { 182 | httpReq.Header.Add(k, v) 183 | } 184 | 185 | if httpReq.Header.Get("Host") != "" { 186 | httpReq.Host = httpReq.Header.Get("Host") 187 | } 188 | 189 | if req.Auth == "noauth" { 190 | httpReq.Header.Del("Authorization") 191 | } 192 | if req.Auth != "team" && c.Config.AsMemberID != "" { 193 | httpReq.Header.Add("Dropbox-API-Select-User", c.Config.AsMemberID) 194 | } 195 | if req.Auth != "team" && c.Config.AsAdminID != "" { 196 | httpReq.Header.Add("Dropbox-API-Select-Admin", c.Config.AsAdminID) 197 | } 198 | if c.Config.PathRoot != "" { 199 | httpReq.Header.Add("Dropbox-API-Path-Root", c.Config.PathRoot) 200 | } 201 | 202 | if req.Arg != nil { 203 | serializedArg, err := json.Marshal(req.Arg) 204 | if err != nil { 205 | return nil, nil, err 206 | } 207 | 208 | switch req.Style { 209 | case "rpc": 210 | if body != nil { 211 | return nil, nil, errors.New("RPC style requests can not have body") 212 | } 213 | 214 | httpReq.Header.Set("Content-Type", "application/json") 215 | httpReq.Body = ioutil.NopCloser(bytes.NewReader(serializedArg)) 216 | httpReq.ContentLength = int64(len(serializedArg)) 217 | case "upload", "download": 218 | httpReq.Header.Set("Dropbox-API-Arg", string(serializedArg)) 219 | httpReq.Header.Set("Content-Type", "application/octet-stream") 220 | } 221 | } 222 | 223 | client := c.Client 224 | if req.Auth == "noauth" { 225 | client = c.NoAuthClient 226 | } 227 | 228 | resp, err := client.Do(httpReq) 229 | if err != nil { 230 | return nil, nil, err 231 | } 232 | 233 | if resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusPartialContent { 234 | switch req.Style { 235 | case "rpc", "upload": 236 | if resp.Body == nil { 237 | return nil, nil, errors.New("Expected body in RPC response, got nil") 238 | } 239 | 240 | b, err := ioutil.ReadAll(resp.Body) 241 | resp.Body.Close() 242 | if err != nil { 243 | return nil, nil, err 244 | } 245 | 246 | return b, nil, nil 247 | case "download": 248 | b := []byte(resp.Header.Get("Dropbox-API-Result")) 249 | return b, resp.Body, nil 250 | } 251 | } 252 | 253 | b, err := ioutil.ReadAll(resp.Body) 254 | resp.Body.Close() 255 | if err != nil { 256 | return nil, nil, err 257 | } 258 | 259 | return nil, nil, SDKInternalError{ 260 | StatusCode: resp.StatusCode, 261 | Content: string(b), 262 | } 263 | } 264 | 265 | // NewContext returns a new Context with the given Config. 266 | func NewContext(c Config) Context { 267 | domain := c.Domain 268 | if domain == "" { 269 | domain = defaultDomain 270 | } 271 | 272 | client := c.Client 273 | if client == nil { 274 | var conf = &oauth2.Config{Endpoint: OAuthEndpoint(domain)} 275 | tok := &oauth2.Token{AccessToken: c.Token} 276 | client = conf.Client(context.Background(), tok) 277 | } 278 | 279 | noAuthClient := c.Client 280 | if noAuthClient == nil { 281 | noAuthClient = &http.Client{} 282 | } 283 | 284 | headerGenerator := c.HeaderGenerator 285 | if headerGenerator == nil { 286 | headerGenerator = func(hostType string, namespace string, route string) map[string]string { 287 | return map[string]string{} 288 | } 289 | } 290 | 291 | urlGenerator := c.URLGenerator 292 | if urlGenerator == nil { 293 | hostMap := map[string]string{ 294 | hostAPI: hostAPI + domain, 295 | hostContent: hostContent + domain, 296 | hostNotify: hostNotify + domain, 297 | } 298 | urlGenerator = func(hostType string, namespace string, route string) string { 299 | fqHost := hostMap[hostType] 300 | return fmt.Sprintf("https://%s/%d/%s/%s", fqHost, apiVersion, namespace, route) 301 | } 302 | } 303 | 304 | return Context{c, client, noAuthClient, headerGenerator, urlGenerator} 305 | } 306 | 307 | // OAuthEndpoint constructs an `oauth2.Endpoint` for the given domain 308 | func OAuthEndpoint(domain string) oauth2.Endpoint { 309 | if domain == "" { 310 | domain = defaultDomain 311 | } 312 | authURL := fmt.Sprintf("https://meta%s/1/oauth2/authorize", domain) 313 | tokenURL := fmt.Sprintf("https://api%s/1/oauth2/token", domain) 314 | if domain == defaultDomain { 315 | authURL = "https://www.dropbox.com/1/oauth2/authorize" 316 | } 317 | return oauth2.Endpoint{AuthURL: authURL, TokenURL: tokenURL} 318 | } 319 | 320 | // HTTPHeaderSafeJSON encode the JSON passed in b []byte passed in in 321 | // a way that is suitable for HTTP headers. 322 | // 323 | // See: https://www.dropbox.com/developers/reference/json-encoding 324 | func HTTPHeaderSafeJSON(b []byte) string { 325 | var s strings.Builder 326 | s.Grow(len(b)) 327 | for _, r := range string(b) { 328 | if r >= 0x007f { 329 | fmt.Fprintf(&s, "\\u%04x", r) 330 | } else { 331 | s.WriteRune(r) 332 | } 333 | } 334 | return s.String() 335 | } 336 | -------------------------------------------------------------------------------- /generator/go_rsrc/sdk.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) Dropbox, Inc. 2 | // 3 | // Permission is hereby granted, free of charge, to any person obtaining a copy 4 | // of this software and associated documentation files (the "Software"), to deal 5 | // in the Software without restriction, including without limitation the rights 6 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | // copies of the Software, and to permit persons to whom the Software is 8 | // furnished to do so, subject to the following conditions: 9 | // 10 | // The above copyright notice and this permission notice shall be included in 11 | // all copies or substantial portions of the Software. 12 | // 13 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | // THE SOFTWARE. 20 | 21 | package dropbox 22 | 23 | import ( 24 | "bytes" 25 | "context" 26 | "encoding/json" 27 | "errors" 28 | "fmt" 29 | "io" 30 | "io/ioutil" 31 | "log" 32 | "net/http" 33 | "strings" 34 | 35 | "golang.org/x/oauth2" 36 | ) 37 | 38 | const ( 39 | apiVersion = 2 40 | defaultDomain = ".dropboxapi.com" 41 | hostAPI = "api" 42 | hostContent = "content" 43 | hostNotify = "notify" 44 | sdkVersion = "UNKNOWN SDK VERSION" 45 | specVersion = "UNKNOWN SPEC VERSION" 46 | ) 47 | 48 | // Version returns the current SDK version and API Spec version 49 | func Version() (string, string) { 50 | return sdkVersion, specVersion 51 | } 52 | 53 | // Tagged is used for tagged unions. 54 | type Tagged struct { 55 | Tag string `json:".tag"` 56 | } 57 | 58 | // APIError is the base type for endpoint-specific errors. 59 | type APIError struct { 60 | ErrorSummary string `json:"error_summary"` 61 | } 62 | 63 | func (e APIError) Error() string { 64 | return e.ErrorSummary 65 | } 66 | 67 | type SDKInternalError struct { 68 | StatusCode int 69 | Content string 70 | } 71 | 72 | func (e SDKInternalError) Error() string { 73 | return fmt.Sprintf("Unexpected error: %v (code: %v)", e.Content, e.StatusCode) 74 | } 75 | 76 | // Config contains parameters for configuring the SDK. 77 | type Config struct { 78 | // OAuth2 access token 79 | Token string 80 | // Logging level for SDK generated logs 81 | LogLevel LogLevel 82 | // Logging target for verbose SDK logging 83 | Logger *log.Logger 84 | // Used with APIs that support operations as another user 85 | AsMemberID string 86 | // Used with APIs that support operations as an admin 87 | AsAdminID string 88 | // Path relative to which action should be taken 89 | PathRoot string 90 | // No need to set -- for testing only 91 | Domain string 92 | // No need to set -- for testing only 93 | Client *http.Client 94 | // No need to set -- for testing only 95 | HeaderGenerator func(hostType string, namespace string, route string) map[string]string 96 | // No need to set -- for testing only 97 | URLGenerator func(hostType string, namespace string, route string) string 98 | } 99 | 100 | // LogLevel defines a type that can set the desired level of logging the SDK will generate. 101 | type LogLevel uint 102 | 103 | const ( 104 | // LogOff will disable all SDK logging. This is the default log level 105 | LogOff LogLevel = iota * (1 << 8) 106 | // LogDebug will enable detailed SDK debug logs. It will log requests (including arguments), 107 | // response and body contents. 108 | LogDebug 109 | // LogInfo will log SDK request (not including arguments) and responses. 110 | LogInfo 111 | ) 112 | 113 | func (l LogLevel) shouldLog(v LogLevel) bool { 114 | return l > v || l&v == v 115 | } 116 | 117 | func (c *Config) doLog(l LogLevel, format string, v ...interface{}) { 118 | if !c.LogLevel.shouldLog(l) { 119 | return 120 | } 121 | 122 | if c.Logger != nil { 123 | c.Logger.Printf(format, v...) 124 | } else { 125 | log.Printf(format, v...) 126 | } 127 | } 128 | 129 | // LogDebug emits a debug level SDK log if config's log level is at least LogDebug 130 | func (c *Config) LogDebug(format string, v ...interface{}) { 131 | c.doLog(LogDebug, format, v...) 132 | } 133 | 134 | // LogInfo emits an info level SDK log if config's log level is at least LogInfo 135 | func (c *Config) LogInfo(format string, v ...interface{}) { 136 | c.doLog(LogInfo, format, v...) 137 | } 138 | 139 | // Ergonomic methods to set namespace relative to which action should be taken 140 | func (c Config) WithNamespaceID(nsID string) Config { 141 | c.PathRoot = fmt.Sprintf(`{".tag": "namespace_id", "namespace_id": "%s"}`, nsID) 142 | return c 143 | } 144 | 145 | func (c Config) WithRoot(nsID string) Config { 146 | c.PathRoot = fmt.Sprintf(`{".tag": "root", "root": "%s"}`, nsID) 147 | return c 148 | } 149 | 150 | // Context is the base client context used to implement per-namespace clients. 151 | type Context struct { 152 | Config Config 153 | Client *http.Client 154 | NoAuthClient *http.Client 155 | HeaderGenerator func(hostType string, namespace string, route string) map[string]string 156 | URLGenerator func(hostType string, namespace string, route string) string 157 | } 158 | 159 | type Request struct { 160 | Host string 161 | Namespace string 162 | Route string 163 | Style string 164 | Auth string 165 | 166 | Arg interface{} 167 | ExtraHeaders map[string]string 168 | } 169 | 170 | func (c *Context) Execute(req Request, body io.Reader) ([]byte, io.ReadCloser, error) { 171 | url := c.URLGenerator(req.Host, req.Namespace, req.Route) 172 | httpReq, err := http.NewRequest("POST", url, body) 173 | if err != nil { 174 | return nil, nil, err 175 | } 176 | 177 | for k, v := range req.ExtraHeaders { 178 | httpReq.Header.Add(k, v) 179 | } 180 | 181 | for k, v := range c.HeaderGenerator(req.Host, req.Namespace, req.Route) { 182 | httpReq.Header.Add(k, v) 183 | } 184 | 185 | if httpReq.Header.Get("Host") != "" { 186 | httpReq.Host = httpReq.Header.Get("Host") 187 | } 188 | 189 | if req.Auth == "noauth" { 190 | httpReq.Header.Del("Authorization") 191 | } 192 | if req.Auth != "team" && c.Config.AsMemberID != "" { 193 | httpReq.Header.Add("Dropbox-API-Select-User", c.Config.AsMemberID) 194 | } 195 | if req.Auth != "team" && c.Config.AsAdminID != "" { 196 | httpReq.Header.Add("Dropbox-API-Select-Admin", c.Config.AsAdminID) 197 | } 198 | if c.Config.PathRoot != "" { 199 | httpReq.Header.Add("Dropbox-API-Path-Root", c.Config.PathRoot) 200 | } 201 | 202 | if req.Arg != nil { 203 | serializedArg, err := json.Marshal(req.Arg) 204 | if err != nil { 205 | return nil, nil, err 206 | } 207 | 208 | switch req.Style { 209 | case "rpc": 210 | if body != nil { 211 | return nil, nil, errors.New("RPC style requests can not have body") 212 | } 213 | 214 | httpReq.Header.Set("Content-Type", "application/json") 215 | httpReq.Body = ioutil.NopCloser(bytes.NewReader(serializedArg)) 216 | httpReq.ContentLength = int64(len(serializedArg)) 217 | case "upload", "download": 218 | httpReq.Header.Set("Dropbox-API-Arg", string(serializedArg)) 219 | httpReq.Header.Set("Content-Type", "application/octet-stream") 220 | } 221 | } 222 | 223 | client := c.Client 224 | if req.Auth == "noauth" { 225 | client = c.NoAuthClient 226 | } 227 | 228 | resp, err := client.Do(httpReq) 229 | if err != nil { 230 | return nil, nil, err 231 | } 232 | 233 | if resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusPartialContent { 234 | switch req.Style { 235 | case "rpc", "upload": 236 | if resp.Body == nil { 237 | return nil, nil, errors.New("Expected body in RPC response, got nil") 238 | } 239 | 240 | b, err := ioutil.ReadAll(resp.Body) 241 | resp.Body.Close() 242 | if err != nil { 243 | return nil, nil, err 244 | } 245 | 246 | return b, nil, nil 247 | case "download": 248 | b := []byte(resp.Header.Get("Dropbox-API-Result")) 249 | return b, resp.Body, nil 250 | } 251 | } 252 | 253 | b, err := ioutil.ReadAll(resp.Body) 254 | resp.Body.Close() 255 | if err != nil { 256 | return nil, nil, err 257 | } 258 | 259 | return nil, nil, SDKInternalError{ 260 | StatusCode: resp.StatusCode, 261 | Content: string(b), 262 | } 263 | } 264 | 265 | // NewContext returns a new Context with the given Config. 266 | func NewContext(c Config) Context { 267 | domain := c.Domain 268 | if domain == "" { 269 | domain = defaultDomain 270 | } 271 | 272 | client := c.Client 273 | if client == nil { 274 | var conf = &oauth2.Config{Endpoint: OAuthEndpoint(domain)} 275 | tok := &oauth2.Token{AccessToken: c.Token} 276 | client = conf.Client(context.Background(), tok) 277 | } 278 | 279 | noAuthClient := c.Client 280 | if noAuthClient == nil { 281 | noAuthClient = &http.Client{} 282 | } 283 | 284 | headerGenerator := c.HeaderGenerator 285 | if headerGenerator == nil { 286 | headerGenerator = func(hostType string, namespace string, route string) map[string]string { 287 | return map[string]string{} 288 | } 289 | } 290 | 291 | urlGenerator := c.URLGenerator 292 | if urlGenerator == nil { 293 | hostMap := map[string]string{ 294 | hostAPI: hostAPI + domain, 295 | hostContent: hostContent + domain, 296 | hostNotify: hostNotify + domain, 297 | } 298 | urlGenerator = func(hostType string, namespace string, route string) string { 299 | fqHost := hostMap[hostType] 300 | return fmt.Sprintf("https://%s/%d/%s/%s", fqHost, apiVersion, namespace, route) 301 | } 302 | } 303 | 304 | return Context{c, client, noAuthClient, headerGenerator, urlGenerator} 305 | } 306 | 307 | // OAuthEndpoint constructs an `oauth2.Endpoint` for the given domain 308 | func OAuthEndpoint(domain string) oauth2.Endpoint { 309 | if domain == "" { 310 | domain = defaultDomain 311 | } 312 | authURL := fmt.Sprintf("https://meta%s/1/oauth2/authorize", domain) 313 | tokenURL := fmt.Sprintf("https://api%s/1/oauth2/token", domain) 314 | if domain == defaultDomain { 315 | authURL = "https://www.dropbox.com/1/oauth2/authorize" 316 | } 317 | return oauth2.Endpoint{AuthURL: authURL, TokenURL: tokenURL} 318 | } 319 | 320 | // HTTPHeaderSafeJSON encode the JSON passed in b []byte passed in in 321 | // a way that is suitable for HTTP headers. 322 | // 323 | // See: https://www.dropbox.com/developers/reference/json-encoding 324 | func HTTPHeaderSafeJSON(b []byte) string { 325 | var s strings.Builder 326 | s.Grow(len(b)) 327 | for _, r := range string(b) { 328 | if r >= 0x007f { 329 | fmt.Fprintf(&s, "\\u%04x", r) 330 | } else { 331 | s.WriteRune(r) 332 | } 333 | } 334 | return s.String() 335 | } 336 | -------------------------------------------------------------------------------- /generator/go_types.stoneg.py: -------------------------------------------------------------------------------- 1 | import os 2 | import shutil 3 | 4 | from stone.backend import CodeBackend 5 | from stone.ir import ( 6 | is_boolean_type, 7 | is_list_type, 8 | is_nullable_type, 9 | is_primitive_type, 10 | is_string_type, 11 | is_struct_type, 12 | is_union_type, 13 | is_void_type, 14 | ) 15 | 16 | from go_helpers import ( 17 | HEADER, 18 | fmt_type, 19 | fmt_var, 20 | generate_doc, 21 | needs_base_type, 22 | _needs_base_type 23 | ) 24 | 25 | 26 | class GoTypesBackend(CodeBackend): 27 | def generate(self, api): 28 | rsrc_folder = os.path.join(os.path.dirname(__file__), 'go_rsrc') 29 | shutil.copy(os.path.join(rsrc_folder, 'sdk.go'), 30 | self.target_folder_path) 31 | for namespace in api.namespaces.values(): 32 | self._generate_namespace(namespace) 33 | 34 | def _generate_namespace(self, namespace): 35 | file_name = os.path.join(self.target_folder_path, namespace.name, 36 | 'types.go') 37 | with self.output_to_relative_path(file_name): 38 | self.emit_raw(HEADER) 39 | self.emit() 40 | generate_doc(self, namespace) 41 | self.emit('package %s' % namespace.name) 42 | self.emit() 43 | 44 | for data_type in namespace.linearize_data_types(): 45 | self._generate_data_type(data_type) 46 | 47 | def _generate_data_type(self, data_type): 48 | generate_doc(self, data_type) 49 | if is_struct_type(data_type): 50 | self._generate_struct(data_type) 51 | if data_type.has_enumerated_subtypes(): 52 | self._generate_base_type(data_type) 53 | elif is_union_type(data_type): 54 | self._generate_union(data_type) 55 | else: 56 | self.logger.info("Unhandled data type", data_type) 57 | 58 | def _generate_base_type(self, base): 59 | t = fmt_type(base).lstrip('*') 60 | self.emit('// Is{0} is the interface type for {0} and its subtypes'.format(t)) 61 | with self.block('type Is%s interface' % t): 62 | self.emit('Is%s()' % t) 63 | self.emit() 64 | self.emit('// Is{0} implements the Is{0} interface'.format(t)) 65 | self.emit("func (u *{0}) Is{0}() {{}}".format(t)) 66 | self.emit() 67 | self._generate_union_helper(base) 68 | 69 | self.emit("// Is{0}FromJSON converts JSON to a concrete Is{0} instance".format(t)) 70 | with self.block("func Is{0}FromJSON(data []byte) (Is{0}, error)".format(t)): 71 | name = fmt_var(t, export=False) + 'Union' 72 | self.emit("var t {0}".format(name)) 73 | with self.block("if err := json.Unmarshal(data, &t); err != nil"): 74 | self.emit("return nil, err") 75 | with self.block("switch t.Tag"): 76 | fields = base.get_enumerated_subtypes() 77 | for field in fields: 78 | with self.block('case "%s":' % field.name, delim=(None, None)): 79 | self.emit("return t.{0}, nil".format(fmt_var(field.name))) 80 | # FIX THIS 81 | self.emit("return nil, nil") 82 | 83 | def _generate_struct(self, struct): 84 | with self.block('type %s struct' % struct.name): 85 | if struct.parent_type: 86 | self.emit(fmt_type(struct.parent_type, struct.namespace).lstrip('*')) 87 | for field in struct.fields: 88 | self._generate_field(field, namespace=struct.namespace) 89 | if struct.name in ('DownloadArg',): 90 | self.emit('// ExtraHeaders can be used to pass Range, If-None-Match headers') 91 | self.emit('ExtraHeaders map[string]string `json:"-"`') 92 | self._generate_struct_builder(struct) 93 | self.emit() 94 | if needs_base_type(struct): 95 | self.emit('// UnmarshalJSON deserializes into a %s instance' % struct.name) 96 | with self.block('func (u *%s) UnmarshalJSON(b []byte) error' % struct.name): 97 | with self.block('type wrap struct'): 98 | for field in struct.all_fields: 99 | self._generate_field(field, namespace=struct.namespace, 100 | raw=_needs_base_type(field.data_type)) 101 | self.emit('var w wrap') 102 | with self.block('if err := json.Unmarshal(b, &w); err != nil'): 103 | self.emit('return err') 104 | for field in struct.all_fields: 105 | dt = field.data_type 106 | fn = fmt_var(field.name) 107 | tn = fmt_type(dt, namespace=struct.namespace, use_interface=True) 108 | if _needs_base_type(dt): 109 | if is_list_type(dt): 110 | self.emit("u.{0} = make({1}, len(w.{0}))".format(fn, tn)) 111 | # Grab the underlying type to get the correct Is...FromJSON method 112 | tn = fmt_type(dt.data_type, namespace=struct.namespace, use_interface=True) 113 | with self.block("for i, e := range w.{0}".format(fn)): 114 | self.emit("v, err := {1}FromJSON(e)".format(fn, tn)) 115 | with self.block('if err != nil'): 116 | self.emit('return err') 117 | self.emit("u.{0}[i] = v".format(fn)) 118 | else: 119 | self.emit("{0}, err := {1}FromJSON(w.{0})".format(fn, tn)) 120 | with self.block('if err != nil'): 121 | self.emit('return err') 122 | self.emit("u.{0} = {0}".format(fn)) 123 | else: 124 | self.emit("u.{0} = w.{0}".format(fn)) 125 | self.emit('return nil') 126 | 127 | def _generate_struct_builder(self, struct): 128 | fields = ["%s %s" % (fmt_var(field.name), 129 | fmt_type(field.data_type, struct.namespace, 130 | use_interface=True)) 131 | for field in struct.all_required_fields] 132 | self.emit('// New{0} returns a new {0} instance'.format(struct.name)) 133 | signature = "func New{0}({1}) *{0}".format(struct.name, ', '.join(fields)) 134 | with self.block(signature): 135 | self.emit('s := new({0})'.format(struct.name)) 136 | for field in struct.all_required_fields: 137 | field_name = fmt_var(field.name) 138 | self.emit("s.{0} = {0}".format(field_name)) 139 | 140 | for field in struct.all_optional_fields: 141 | if field.has_default: 142 | if is_primitive_type(field.data_type): 143 | default = field.default 144 | if is_boolean_type(field.data_type): 145 | default = str(default).lower() 146 | if is_string_type(field.data_type): 147 | default = '"{}"'.format(default) 148 | self.emit('s.{0} = {1}'.format(fmt_var(field.name), default)) 149 | elif is_union_type(field.data_type): 150 | self.emit('s.%s = &%s{Tagged:dropbox.Tagged{Tag: "%s"}}' % 151 | (fmt_var(field.name), 152 | fmt_type(field.data_type, struct.namespace).lstrip('*'), 153 | field.default.tag_name)) 154 | self.emit('return s') 155 | self.emit() 156 | 157 | def _generate_field(self, field, union_field=False, namespace=None, raw=False): 158 | generate_doc(self, field) 159 | field_name = fmt_var(field.name) 160 | type_name = fmt_type(field.data_type, namespace, use_interface=True, raw=raw) 161 | json_tag = '`json:"%s"`' % field.name 162 | if is_nullable_type(field.data_type) or union_field: 163 | json_tag = '`json:"%s,omitempty"`' % field.name 164 | self.emit('%s %s %s' % (field_name, type_name, json_tag)) 165 | 166 | def _generate_union(self, union): 167 | self._generate_union_helper(union) 168 | 169 | def _generate_union_helper(self, u): 170 | name = u.name 171 | namespace = u.namespace 172 | # Unions can be inherited, but don't need to be polymorphic. 173 | # So let's flatten out all the inherited fields. 174 | fields = u.all_fields 175 | if is_struct_type(u) and u.has_enumerated_subtypes(): 176 | name = fmt_var(name, export=False) + 'Union' 177 | fields = u.get_enumerated_subtypes() 178 | 179 | with self.block('type %s struct' % name): 180 | self.emit('dropbox.Tagged') 181 | for field in fields: 182 | if is_void_type(field.data_type): 183 | continue 184 | self._generate_field(field, union_field=True, 185 | namespace=namespace) 186 | self.emit() 187 | self.emit('// Valid tag values for %s' % fmt_var(u.name)) 188 | with self.block('const', delim=('(', ')')): 189 | for field in fields: 190 | self.emit('%s%s = "%s"' % (fmt_var(u.name), fmt_var(field.name), field.name)) 191 | self.emit() 192 | 193 | num_void_fields = sum([is_void_type(f.data_type) for f in fields]) 194 | # Simple structure, no need in UnmarshalJSON 195 | if len(fields) == num_void_fields: 196 | return 197 | 198 | self.emit('// UnmarshalJSON deserializes into a %s instance' % name) 199 | with self.block('func (u *%s) UnmarshalJSON(body []byte) error' % name): 200 | with self.block('type wrap struct'): 201 | self.emit('dropbox.Tagged') 202 | for field in fields: 203 | if is_void_type(field.data_type) or ( 204 | is_struct_type(field.data_type) and not _needs_base_type(field.data_type)): 205 | # pure structures are flattened in the containing union json blob and thus are loaded from body 206 | continue 207 | # sub-unions must be handled as RawMessage, which will be loaded into correct implementation later 208 | self._generate_field(field, union_field=True, 209 | namespace=namespace, raw=_needs_base_type(field.data_type)) 210 | self.emit('var w wrap') 211 | self.emit('var err error') 212 | with self.block('if err = json.Unmarshal(body, &w); err != nil'): 213 | self.emit('return err') 214 | self.emit('u.Tag = w.Tag') 215 | with self.block('switch u.Tag'): 216 | for field in fields: 217 | if is_void_type(field.data_type): 218 | continue 219 | field_name = fmt_var(field.name) 220 | with self.block('case "%s":' % field.name, delim=(None, None)): 221 | if _needs_base_type(field.data_type): 222 | with self.block("if u.{0}, err = Is{1}FromJSON(w.{0}); err != nil" 223 | .format(field_name, field.data_type.name)): 224 | self.emit("return err") 225 | elif is_struct_type(field.data_type): 226 | with self.block('if err = json.Unmarshal(body, &u.{0}); err != nil' 227 | .format(field_name)): 228 | self.emit("return err") 229 | else: 230 | self.emit('u.{0} = w.{0}'.format(field_name)) 231 | self.emit('return nil') 232 | self.emit() 233 | -------------------------------------------------------------------------------- /v6/dropbox/file_requests/client.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) Dropbox, Inc. 2 | // 3 | // Permission is hereby granted, free of charge, to any person obtaining a copy 4 | // of this software and associated documentation files (the "Software"), to deal 5 | // in the Software without restriction, including without limitation the rights 6 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | // copies of the Software, and to permit persons to whom the Software is 8 | // furnished to do so, subject to the following conditions: 9 | // 10 | // The above copyright notice and this permission notice shall be included in 11 | // all copies or substantial portions of the Software. 12 | // 13 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | // THE SOFTWARE. 20 | 21 | package file_requests 22 | 23 | import ( 24 | "encoding/json" 25 | "io" 26 | 27 | "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox" 28 | "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox/auth" 29 | ) 30 | 31 | // Client interface describes all routes in this namespace 32 | type Client interface { 33 | // Count : Returns the total number of file requests owned by this user. 34 | // Includes both open and closed file requests. 35 | Count() (res *CountFileRequestsResult, err error) 36 | // Create : Creates a file request for this user. 37 | Create(arg *CreateFileRequestArgs) (res *FileRequest, err error) 38 | // Delete : Delete a batch of closed file requests. 39 | Delete(arg *DeleteFileRequestArgs) (res *DeleteFileRequestsResult, err error) 40 | // DeleteAllClosed : Delete all closed file requests owned by this user. 41 | DeleteAllClosed() (res *DeleteAllClosedFileRequestsResult, err error) 42 | // Get : Returns the specified file request. 43 | Get(arg *GetFileRequestArgs) (res *FileRequest, err error) 44 | // List : Returns a list of file requests owned by this user. For apps with 45 | // the app folder permission, this will only return file requests with 46 | // destinations in the app folder. 47 | ListV2(arg *ListFileRequestsArg) (res *ListFileRequestsV2Result, err error) 48 | // List : Returns a list of file requests owned by this user. For apps with 49 | // the app folder permission, this will only return file requests with 50 | // destinations in the app folder. 51 | List() (res *ListFileRequestsResult, err error) 52 | // ListContinue : Once a cursor has been retrieved from `list`, use this to 53 | // paginate through all file requests. The cursor must come from a previous 54 | // call to `list` or `listContinue`. 55 | ListContinue(arg *ListFileRequestsContinueArg) (res *ListFileRequestsV2Result, err error) 56 | // Update : Update a file request. 57 | Update(arg *UpdateFileRequestArgs) (res *FileRequest, err error) 58 | } 59 | 60 | type apiImpl dropbox.Context 61 | 62 | //CountAPIError is an error-wrapper for the count route 63 | type CountAPIError struct { 64 | dropbox.APIError 65 | EndpointError *CountFileRequestsError `json:"error"` 66 | } 67 | 68 | func (dbx *apiImpl) Count() (res *CountFileRequestsResult, err error) { 69 | req := dropbox.Request{ 70 | Host: "api", 71 | Namespace: "file_requests", 72 | Route: "count", 73 | Auth: "user", 74 | Style: "rpc", 75 | Arg: nil, 76 | ExtraHeaders: nil, 77 | } 78 | 79 | var resp []byte 80 | var respBody io.ReadCloser 81 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 82 | if err != nil { 83 | var appErr CountAPIError 84 | err = auth.ParseError(err, &appErr) 85 | if err == &appErr { 86 | err = appErr 87 | } 88 | return 89 | } 90 | 91 | err = json.Unmarshal(resp, &res) 92 | if err != nil { 93 | return 94 | } 95 | 96 | _ = respBody 97 | return 98 | } 99 | 100 | //CreateAPIError is an error-wrapper for the create route 101 | type CreateAPIError struct { 102 | dropbox.APIError 103 | EndpointError *CreateFileRequestError `json:"error"` 104 | } 105 | 106 | func (dbx *apiImpl) Create(arg *CreateFileRequestArgs) (res *FileRequest, err error) { 107 | req := dropbox.Request{ 108 | Host: "api", 109 | Namespace: "file_requests", 110 | Route: "create", 111 | Auth: "user", 112 | Style: "rpc", 113 | Arg: arg, 114 | ExtraHeaders: nil, 115 | } 116 | 117 | var resp []byte 118 | var respBody io.ReadCloser 119 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 120 | if err != nil { 121 | var appErr CreateAPIError 122 | err = auth.ParseError(err, &appErr) 123 | if err == &appErr { 124 | err = appErr 125 | } 126 | return 127 | } 128 | 129 | err = json.Unmarshal(resp, &res) 130 | if err != nil { 131 | return 132 | } 133 | 134 | _ = respBody 135 | return 136 | } 137 | 138 | //DeleteAPIError is an error-wrapper for the delete route 139 | type DeleteAPIError struct { 140 | dropbox.APIError 141 | EndpointError *DeleteFileRequestError `json:"error"` 142 | } 143 | 144 | func (dbx *apiImpl) Delete(arg *DeleteFileRequestArgs) (res *DeleteFileRequestsResult, err error) { 145 | req := dropbox.Request{ 146 | Host: "api", 147 | Namespace: "file_requests", 148 | Route: "delete", 149 | Auth: "user", 150 | Style: "rpc", 151 | Arg: arg, 152 | ExtraHeaders: nil, 153 | } 154 | 155 | var resp []byte 156 | var respBody io.ReadCloser 157 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 158 | if err != nil { 159 | var appErr DeleteAPIError 160 | err = auth.ParseError(err, &appErr) 161 | if err == &appErr { 162 | err = appErr 163 | } 164 | return 165 | } 166 | 167 | err = json.Unmarshal(resp, &res) 168 | if err != nil { 169 | return 170 | } 171 | 172 | _ = respBody 173 | return 174 | } 175 | 176 | //DeleteAllClosedAPIError is an error-wrapper for the delete_all_closed route 177 | type DeleteAllClosedAPIError struct { 178 | dropbox.APIError 179 | EndpointError *DeleteAllClosedFileRequestsError `json:"error"` 180 | } 181 | 182 | func (dbx *apiImpl) DeleteAllClosed() (res *DeleteAllClosedFileRequestsResult, err error) { 183 | req := dropbox.Request{ 184 | Host: "api", 185 | Namespace: "file_requests", 186 | Route: "delete_all_closed", 187 | Auth: "user", 188 | Style: "rpc", 189 | Arg: nil, 190 | ExtraHeaders: nil, 191 | } 192 | 193 | var resp []byte 194 | var respBody io.ReadCloser 195 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 196 | if err != nil { 197 | var appErr DeleteAllClosedAPIError 198 | err = auth.ParseError(err, &appErr) 199 | if err == &appErr { 200 | err = appErr 201 | } 202 | return 203 | } 204 | 205 | err = json.Unmarshal(resp, &res) 206 | if err != nil { 207 | return 208 | } 209 | 210 | _ = respBody 211 | return 212 | } 213 | 214 | //GetAPIError is an error-wrapper for the get route 215 | type GetAPIError struct { 216 | dropbox.APIError 217 | EndpointError *GetFileRequestError `json:"error"` 218 | } 219 | 220 | func (dbx *apiImpl) Get(arg *GetFileRequestArgs) (res *FileRequest, err error) { 221 | req := dropbox.Request{ 222 | Host: "api", 223 | Namespace: "file_requests", 224 | Route: "get", 225 | Auth: "user", 226 | Style: "rpc", 227 | Arg: arg, 228 | ExtraHeaders: nil, 229 | } 230 | 231 | var resp []byte 232 | var respBody io.ReadCloser 233 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 234 | if err != nil { 235 | var appErr GetAPIError 236 | err = auth.ParseError(err, &appErr) 237 | if err == &appErr { 238 | err = appErr 239 | } 240 | return 241 | } 242 | 243 | err = json.Unmarshal(resp, &res) 244 | if err != nil { 245 | return 246 | } 247 | 248 | _ = respBody 249 | return 250 | } 251 | 252 | //ListV2APIError is an error-wrapper for the list_v2 route 253 | type ListV2APIError struct { 254 | dropbox.APIError 255 | EndpointError *ListFileRequestsError `json:"error"` 256 | } 257 | 258 | func (dbx *apiImpl) ListV2(arg *ListFileRequestsArg) (res *ListFileRequestsV2Result, err error) { 259 | req := dropbox.Request{ 260 | Host: "api", 261 | Namespace: "file_requests", 262 | Route: "list_v2", 263 | Auth: "user", 264 | Style: "rpc", 265 | Arg: arg, 266 | ExtraHeaders: nil, 267 | } 268 | 269 | var resp []byte 270 | var respBody io.ReadCloser 271 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 272 | if err != nil { 273 | var appErr ListV2APIError 274 | err = auth.ParseError(err, &appErr) 275 | if err == &appErr { 276 | err = appErr 277 | } 278 | return 279 | } 280 | 281 | err = json.Unmarshal(resp, &res) 282 | if err != nil { 283 | return 284 | } 285 | 286 | _ = respBody 287 | return 288 | } 289 | 290 | //ListAPIError is an error-wrapper for the list route 291 | type ListAPIError struct { 292 | dropbox.APIError 293 | EndpointError *ListFileRequestsError `json:"error"` 294 | } 295 | 296 | func (dbx *apiImpl) List() (res *ListFileRequestsResult, err error) { 297 | req := dropbox.Request{ 298 | Host: "api", 299 | Namespace: "file_requests", 300 | Route: "list", 301 | Auth: "user", 302 | Style: "rpc", 303 | Arg: nil, 304 | ExtraHeaders: nil, 305 | } 306 | 307 | var resp []byte 308 | var respBody io.ReadCloser 309 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 310 | if err != nil { 311 | var appErr ListAPIError 312 | err = auth.ParseError(err, &appErr) 313 | if err == &appErr { 314 | err = appErr 315 | } 316 | return 317 | } 318 | 319 | err = json.Unmarshal(resp, &res) 320 | if err != nil { 321 | return 322 | } 323 | 324 | _ = respBody 325 | return 326 | } 327 | 328 | //ListContinueAPIError is an error-wrapper for the list/continue route 329 | type ListContinueAPIError struct { 330 | dropbox.APIError 331 | EndpointError *ListFileRequestsContinueError `json:"error"` 332 | } 333 | 334 | func (dbx *apiImpl) ListContinue(arg *ListFileRequestsContinueArg) (res *ListFileRequestsV2Result, err error) { 335 | req := dropbox.Request{ 336 | Host: "api", 337 | Namespace: "file_requests", 338 | Route: "list/continue", 339 | Auth: "user", 340 | Style: "rpc", 341 | Arg: arg, 342 | ExtraHeaders: nil, 343 | } 344 | 345 | var resp []byte 346 | var respBody io.ReadCloser 347 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 348 | if err != nil { 349 | var appErr ListContinueAPIError 350 | err = auth.ParseError(err, &appErr) 351 | if err == &appErr { 352 | err = appErr 353 | } 354 | return 355 | } 356 | 357 | err = json.Unmarshal(resp, &res) 358 | if err != nil { 359 | return 360 | } 361 | 362 | _ = respBody 363 | return 364 | } 365 | 366 | //UpdateAPIError is an error-wrapper for the update route 367 | type UpdateAPIError struct { 368 | dropbox.APIError 369 | EndpointError *UpdateFileRequestError `json:"error"` 370 | } 371 | 372 | func (dbx *apiImpl) Update(arg *UpdateFileRequestArgs) (res *FileRequest, err error) { 373 | req := dropbox.Request{ 374 | Host: "api", 375 | Namespace: "file_requests", 376 | Route: "update", 377 | Auth: "user", 378 | Style: "rpc", 379 | Arg: arg, 380 | ExtraHeaders: nil, 381 | } 382 | 383 | var resp []byte 384 | var respBody io.ReadCloser 385 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 386 | if err != nil { 387 | var appErr UpdateAPIError 388 | err = auth.ParseError(err, &appErr) 389 | if err == &appErr { 390 | err = appErr 391 | } 392 | return 393 | } 394 | 395 | err = json.Unmarshal(resp, &res) 396 | if err != nil { 397 | return 398 | } 399 | 400 | _ = respBody 401 | return 402 | } 403 | 404 | // New returns a Client implementation for this namespace 405 | func New(c dropbox.Config) Client { 406 | ctx := apiImpl(dropbox.NewContext(c)) 407 | return &ctx 408 | } 409 | -------------------------------------------------------------------------------- /v6/dropbox/team_policies/types.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) Dropbox, Inc. 2 | // 3 | // Permission is hereby granted, free of charge, to any person obtaining a copy 4 | // of this software and associated documentation files (the "Software"), to deal 5 | // in the Software without restriction, including without limitation the rights 6 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | // copies of the Software, and to permit persons to whom the Software is 8 | // furnished to do so, subject to the following conditions: 9 | // 10 | // The above copyright notice and this permission notice shall be included in 11 | // all copies or substantial portions of the Software. 12 | // 13 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | // THE SOFTWARE. 20 | 21 | // Package team_policies : has no documentation (yet) 22 | package team_policies 23 | 24 | import "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox" 25 | 26 | // CameraUploadsPolicyState : has no documentation (yet) 27 | type CameraUploadsPolicyState struct { 28 | dropbox.Tagged 29 | } 30 | 31 | // Valid tag values for CameraUploadsPolicyState 32 | const ( 33 | CameraUploadsPolicyStateDisabled = "disabled" 34 | CameraUploadsPolicyStateEnabled = "enabled" 35 | CameraUploadsPolicyStateOther = "other" 36 | ) 37 | 38 | // ComputerBackupPolicyState : has no documentation (yet) 39 | type ComputerBackupPolicyState struct { 40 | dropbox.Tagged 41 | } 42 | 43 | // Valid tag values for ComputerBackupPolicyState 44 | const ( 45 | ComputerBackupPolicyStateDisabled = "disabled" 46 | ComputerBackupPolicyStateEnabled = "enabled" 47 | ComputerBackupPolicyStateDefault = "default" 48 | ComputerBackupPolicyStateOther = "other" 49 | ) 50 | 51 | // EmmState : has no documentation (yet) 52 | type EmmState struct { 53 | dropbox.Tagged 54 | } 55 | 56 | // Valid tag values for EmmState 57 | const ( 58 | EmmStateDisabled = "disabled" 59 | EmmStateOptional = "optional" 60 | EmmStateRequired = "required" 61 | EmmStateOther = "other" 62 | ) 63 | 64 | // ExternalDriveBackupPolicyState : has no documentation (yet) 65 | type ExternalDriveBackupPolicyState struct { 66 | dropbox.Tagged 67 | } 68 | 69 | // Valid tag values for ExternalDriveBackupPolicyState 70 | const ( 71 | ExternalDriveBackupPolicyStateDisabled = "disabled" 72 | ExternalDriveBackupPolicyStateEnabled = "enabled" 73 | ExternalDriveBackupPolicyStateDefault = "default" 74 | ExternalDriveBackupPolicyStateOther = "other" 75 | ) 76 | 77 | // FileLockingPolicyState : has no documentation (yet) 78 | type FileLockingPolicyState struct { 79 | dropbox.Tagged 80 | } 81 | 82 | // Valid tag values for FileLockingPolicyState 83 | const ( 84 | FileLockingPolicyStateDisabled = "disabled" 85 | FileLockingPolicyStateEnabled = "enabled" 86 | FileLockingPolicyStateOther = "other" 87 | ) 88 | 89 | // FileProviderMigrationPolicyState : has no documentation (yet) 90 | type FileProviderMigrationPolicyState struct { 91 | dropbox.Tagged 92 | } 93 | 94 | // Valid tag values for FileProviderMigrationPolicyState 95 | const ( 96 | FileProviderMigrationPolicyStateDisabled = "disabled" 97 | FileProviderMigrationPolicyStateEnabled = "enabled" 98 | FileProviderMigrationPolicyStateDefault = "default" 99 | FileProviderMigrationPolicyStateOther = "other" 100 | ) 101 | 102 | // GroupCreation : has no documentation (yet) 103 | type GroupCreation struct { 104 | dropbox.Tagged 105 | } 106 | 107 | // Valid tag values for GroupCreation 108 | const ( 109 | GroupCreationAdminsAndMembers = "admins_and_members" 110 | GroupCreationAdminsOnly = "admins_only" 111 | ) 112 | 113 | // OfficeAddInPolicy : has no documentation (yet) 114 | type OfficeAddInPolicy struct { 115 | dropbox.Tagged 116 | } 117 | 118 | // Valid tag values for OfficeAddInPolicy 119 | const ( 120 | OfficeAddInPolicyDisabled = "disabled" 121 | OfficeAddInPolicyEnabled = "enabled" 122 | OfficeAddInPolicyOther = "other" 123 | ) 124 | 125 | // PaperDefaultFolderPolicy : has no documentation (yet) 126 | type PaperDefaultFolderPolicy struct { 127 | dropbox.Tagged 128 | } 129 | 130 | // Valid tag values for PaperDefaultFolderPolicy 131 | const ( 132 | PaperDefaultFolderPolicyEveryoneInTeam = "everyone_in_team" 133 | PaperDefaultFolderPolicyInviteOnly = "invite_only" 134 | PaperDefaultFolderPolicyOther = "other" 135 | ) 136 | 137 | // PaperDeploymentPolicy : has no documentation (yet) 138 | type PaperDeploymentPolicy struct { 139 | dropbox.Tagged 140 | } 141 | 142 | // Valid tag values for PaperDeploymentPolicy 143 | const ( 144 | PaperDeploymentPolicyFull = "full" 145 | PaperDeploymentPolicyPartial = "partial" 146 | PaperDeploymentPolicyOther = "other" 147 | ) 148 | 149 | // PaperDesktopPolicy : has no documentation (yet) 150 | type PaperDesktopPolicy struct { 151 | dropbox.Tagged 152 | } 153 | 154 | // Valid tag values for PaperDesktopPolicy 155 | const ( 156 | PaperDesktopPolicyDisabled = "disabled" 157 | PaperDesktopPolicyEnabled = "enabled" 158 | PaperDesktopPolicyOther = "other" 159 | ) 160 | 161 | // PaperEnabledPolicy : has no documentation (yet) 162 | type PaperEnabledPolicy struct { 163 | dropbox.Tagged 164 | } 165 | 166 | // Valid tag values for PaperEnabledPolicy 167 | const ( 168 | PaperEnabledPolicyDisabled = "disabled" 169 | PaperEnabledPolicyEnabled = "enabled" 170 | PaperEnabledPolicyUnspecified = "unspecified" 171 | PaperEnabledPolicyOther = "other" 172 | ) 173 | 174 | // PasswordControlMode : has no documentation (yet) 175 | type PasswordControlMode struct { 176 | dropbox.Tagged 177 | } 178 | 179 | // Valid tag values for PasswordControlMode 180 | const ( 181 | PasswordControlModeDisabled = "disabled" 182 | PasswordControlModeEnabled = "enabled" 183 | PasswordControlModeOther = "other" 184 | ) 185 | 186 | // PasswordStrengthPolicy : has no documentation (yet) 187 | type PasswordStrengthPolicy struct { 188 | dropbox.Tagged 189 | } 190 | 191 | // Valid tag values for PasswordStrengthPolicy 192 | const ( 193 | PasswordStrengthPolicyMinimalRequirements = "minimal_requirements" 194 | PasswordStrengthPolicyModeratePassword = "moderate_password" 195 | PasswordStrengthPolicyStrongPassword = "strong_password" 196 | PasswordStrengthPolicyOther = "other" 197 | ) 198 | 199 | // RolloutMethod : has no documentation (yet) 200 | type RolloutMethod struct { 201 | dropbox.Tagged 202 | } 203 | 204 | // Valid tag values for RolloutMethod 205 | const ( 206 | RolloutMethodUnlinkAll = "unlink_all" 207 | RolloutMethodUnlinkMostInactive = "unlink_most_inactive" 208 | RolloutMethodAddMemberToExceptions = "add_member_to_exceptions" 209 | ) 210 | 211 | // SharedFolderJoinPolicy : Policy governing which shared folders a team member 212 | // can join. 213 | type SharedFolderJoinPolicy struct { 214 | dropbox.Tagged 215 | } 216 | 217 | // Valid tag values for SharedFolderJoinPolicy 218 | const ( 219 | SharedFolderJoinPolicyFromTeamOnly = "from_team_only" 220 | SharedFolderJoinPolicyFromAnyone = "from_anyone" 221 | SharedFolderJoinPolicyOther = "other" 222 | ) 223 | 224 | // SharedFolderMemberPolicy : Policy governing who can be a member of a folder 225 | // shared by a team member. 226 | type SharedFolderMemberPolicy struct { 227 | dropbox.Tagged 228 | } 229 | 230 | // Valid tag values for SharedFolderMemberPolicy 231 | const ( 232 | SharedFolderMemberPolicyTeam = "team" 233 | SharedFolderMemberPolicyAnyone = "anyone" 234 | SharedFolderMemberPolicyOther = "other" 235 | ) 236 | 237 | // SharedLinkCreatePolicy : Policy governing the visibility of shared links. 238 | // This policy can apply to newly created shared links, or all shared links. 239 | type SharedLinkCreatePolicy struct { 240 | dropbox.Tagged 241 | } 242 | 243 | // Valid tag values for SharedLinkCreatePolicy 244 | const ( 245 | SharedLinkCreatePolicyDefaultPublic = "default_public" 246 | SharedLinkCreatePolicyDefaultTeamOnly = "default_team_only" 247 | SharedLinkCreatePolicyTeamOnly = "team_only" 248 | SharedLinkCreatePolicyDefaultNoOne = "default_no_one" 249 | SharedLinkCreatePolicyOther = "other" 250 | ) 251 | 252 | // ShowcaseDownloadPolicy : has no documentation (yet) 253 | type ShowcaseDownloadPolicy struct { 254 | dropbox.Tagged 255 | } 256 | 257 | // Valid tag values for ShowcaseDownloadPolicy 258 | const ( 259 | ShowcaseDownloadPolicyDisabled = "disabled" 260 | ShowcaseDownloadPolicyEnabled = "enabled" 261 | ShowcaseDownloadPolicyOther = "other" 262 | ) 263 | 264 | // ShowcaseEnabledPolicy : has no documentation (yet) 265 | type ShowcaseEnabledPolicy struct { 266 | dropbox.Tagged 267 | } 268 | 269 | // Valid tag values for ShowcaseEnabledPolicy 270 | const ( 271 | ShowcaseEnabledPolicyDisabled = "disabled" 272 | ShowcaseEnabledPolicyEnabled = "enabled" 273 | ShowcaseEnabledPolicyOther = "other" 274 | ) 275 | 276 | // ShowcaseExternalSharingPolicy : has no documentation (yet) 277 | type ShowcaseExternalSharingPolicy struct { 278 | dropbox.Tagged 279 | } 280 | 281 | // Valid tag values for ShowcaseExternalSharingPolicy 282 | const ( 283 | ShowcaseExternalSharingPolicyDisabled = "disabled" 284 | ShowcaseExternalSharingPolicyEnabled = "enabled" 285 | ShowcaseExternalSharingPolicyOther = "other" 286 | ) 287 | 288 | // SmartSyncPolicy : has no documentation (yet) 289 | type SmartSyncPolicy struct { 290 | dropbox.Tagged 291 | } 292 | 293 | // Valid tag values for SmartSyncPolicy 294 | const ( 295 | SmartSyncPolicyLocal = "local" 296 | SmartSyncPolicyOnDemand = "on_demand" 297 | SmartSyncPolicyOther = "other" 298 | ) 299 | 300 | // SmarterSmartSyncPolicyState : has no documentation (yet) 301 | type SmarterSmartSyncPolicyState struct { 302 | dropbox.Tagged 303 | } 304 | 305 | // Valid tag values for SmarterSmartSyncPolicyState 306 | const ( 307 | SmarterSmartSyncPolicyStateDisabled = "disabled" 308 | SmarterSmartSyncPolicyStateEnabled = "enabled" 309 | SmarterSmartSyncPolicyStateOther = "other" 310 | ) 311 | 312 | // SsoPolicy : has no documentation (yet) 313 | type SsoPolicy struct { 314 | dropbox.Tagged 315 | } 316 | 317 | // Valid tag values for SsoPolicy 318 | const ( 319 | SsoPolicyDisabled = "disabled" 320 | SsoPolicyOptional = "optional" 321 | SsoPolicyRequired = "required" 322 | SsoPolicyOther = "other" 323 | ) 324 | 325 | // SuggestMembersPolicy : has no documentation (yet) 326 | type SuggestMembersPolicy struct { 327 | dropbox.Tagged 328 | } 329 | 330 | // Valid tag values for SuggestMembersPolicy 331 | const ( 332 | SuggestMembersPolicyDisabled = "disabled" 333 | SuggestMembersPolicyEnabled = "enabled" 334 | SuggestMembersPolicyOther = "other" 335 | ) 336 | 337 | // TeamMemberPolicies : Policies governing team members. 338 | type TeamMemberPolicies struct { 339 | // Sharing : Policies governing sharing. 340 | Sharing *TeamSharingPolicies `json:"sharing"` 341 | // EmmState : This describes the Enterprise Mobility Management (EMM) state 342 | // for this team. This information can be used to understand if an 343 | // organization is integrating with a third-party EMM vendor to further 344 | // manage and apply restrictions upon the team's Dropbox usage on mobile 345 | // devices. This is a new feature and in the future we'll be adding more new 346 | // fields and additional documentation. 347 | EmmState *EmmState `json:"emm_state"` 348 | // OfficeAddin : The admin policy around the Dropbox Office Add-In for this 349 | // team. 350 | OfficeAddin *OfficeAddInPolicy `json:"office_addin"` 351 | // SuggestMembersPolicy : The team policy on if teammembers are allowed to 352 | // suggest users for admins to invite to the team. 353 | SuggestMembersPolicy *SuggestMembersPolicy `json:"suggest_members_policy"` 354 | } 355 | 356 | // NewTeamMemberPolicies returns a new TeamMemberPolicies instance 357 | func NewTeamMemberPolicies(Sharing *TeamSharingPolicies, EmmState *EmmState, OfficeAddin *OfficeAddInPolicy, SuggestMembersPolicy *SuggestMembersPolicy) *TeamMemberPolicies { 358 | s := new(TeamMemberPolicies) 359 | s.Sharing = Sharing 360 | s.EmmState = EmmState 361 | s.OfficeAddin = OfficeAddin 362 | s.SuggestMembersPolicy = SuggestMembersPolicy 363 | return s 364 | } 365 | 366 | // TeamSharingPolicies : Policies governing sharing within and outside of the 367 | // team. 368 | type TeamSharingPolicies struct { 369 | // SharedFolderMemberPolicy : Who can join folders shared by team members. 370 | SharedFolderMemberPolicy *SharedFolderMemberPolicy `json:"shared_folder_member_policy"` 371 | // SharedFolderJoinPolicy : Which shared folders team members can join. 372 | SharedFolderJoinPolicy *SharedFolderJoinPolicy `json:"shared_folder_join_policy"` 373 | // SharedLinkCreatePolicy : Who can view shared links owned by team members. 374 | SharedLinkCreatePolicy *SharedLinkCreatePolicy `json:"shared_link_create_policy"` 375 | } 376 | 377 | // NewTeamSharingPolicies returns a new TeamSharingPolicies instance 378 | func NewTeamSharingPolicies(SharedFolderMemberPolicy *SharedFolderMemberPolicy, SharedFolderJoinPolicy *SharedFolderJoinPolicy, SharedLinkCreatePolicy *SharedLinkCreatePolicy) *TeamSharingPolicies { 379 | s := new(TeamSharingPolicies) 380 | s.SharedFolderMemberPolicy = SharedFolderMemberPolicy 381 | s.SharedFolderJoinPolicy = SharedFolderJoinPolicy 382 | s.SharedLinkCreatePolicy = SharedLinkCreatePolicy 383 | return s 384 | } 385 | 386 | // TwoStepVerificationPolicy : has no documentation (yet) 387 | type TwoStepVerificationPolicy struct { 388 | dropbox.Tagged 389 | } 390 | 391 | // Valid tag values for TwoStepVerificationPolicy 392 | const ( 393 | TwoStepVerificationPolicyRequireTfaEnable = "require_tfa_enable" 394 | TwoStepVerificationPolicyRequireTfaDisable = "require_tfa_disable" 395 | TwoStepVerificationPolicyOther = "other" 396 | ) 397 | 398 | // TwoStepVerificationState : has no documentation (yet) 399 | type TwoStepVerificationState struct { 400 | dropbox.Tagged 401 | } 402 | 403 | // Valid tag values for TwoStepVerificationState 404 | const ( 405 | TwoStepVerificationStateRequired = "required" 406 | TwoStepVerificationStateOptional = "optional" 407 | TwoStepVerificationStateDisabled = "disabled" 408 | TwoStepVerificationStateOther = "other" 409 | ) 410 | -------------------------------------------------------------------------------- /v6/dropbox/file_requests/types.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) Dropbox, Inc. 2 | // 3 | // Permission is hereby granted, free of charge, to any person obtaining a copy 4 | // of this software and associated documentation files (the "Software"), to deal 5 | // in the Software without restriction, including without limitation the rights 6 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | // copies of the Software, and to permit persons to whom the Software is 8 | // furnished to do so, subject to the following conditions: 9 | // 10 | // The above copyright notice and this permission notice shall be included in 11 | // all copies or substantial portions of the Software. 12 | // 13 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | // THE SOFTWARE. 20 | 21 | // Package file_requests : This namespace contains endpoints and data types for 22 | // file request operations. 23 | package file_requests 24 | 25 | import ( 26 | "encoding/json" 27 | "time" 28 | 29 | "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox" 30 | ) 31 | 32 | // GeneralFileRequestsError : There is an error accessing the file requests 33 | // functionality. 34 | type GeneralFileRequestsError struct { 35 | dropbox.Tagged 36 | } 37 | 38 | // Valid tag values for GeneralFileRequestsError 39 | const ( 40 | GeneralFileRequestsErrorDisabledForTeam = "disabled_for_team" 41 | GeneralFileRequestsErrorOther = "other" 42 | ) 43 | 44 | // CountFileRequestsError : There was an error counting the file requests. 45 | type CountFileRequestsError struct { 46 | dropbox.Tagged 47 | } 48 | 49 | // Valid tag values for CountFileRequestsError 50 | const ( 51 | CountFileRequestsErrorDisabledForTeam = "disabled_for_team" 52 | CountFileRequestsErrorOther = "other" 53 | ) 54 | 55 | // CountFileRequestsResult : Result for `count`. 56 | type CountFileRequestsResult struct { 57 | // FileRequestCount : The number file requests owner by this user. 58 | FileRequestCount uint64 `json:"file_request_count"` 59 | } 60 | 61 | // NewCountFileRequestsResult returns a new CountFileRequestsResult instance 62 | func NewCountFileRequestsResult(FileRequestCount uint64) *CountFileRequestsResult { 63 | s := new(CountFileRequestsResult) 64 | s.FileRequestCount = FileRequestCount 65 | return s 66 | } 67 | 68 | // CreateFileRequestArgs : Arguments for `create`. 69 | type CreateFileRequestArgs struct { 70 | // Title : The title of the file request. Must not be empty. 71 | Title string `json:"title"` 72 | // Destination : The path of the folder in the Dropbox where uploaded files 73 | // will be sent. For apps with the app folder permission, this will be 74 | // relative to the app folder. 75 | Destination string `json:"destination"` 76 | // Deadline : The deadline for the file request. Deadlines can only be set 77 | // by Professional and Business accounts. 78 | Deadline *FileRequestDeadline `json:"deadline,omitempty"` 79 | // Open : Whether or not the file request should be open. If the file 80 | // request is closed, it will not accept any file submissions, but it can be 81 | // opened later. 82 | Open bool `json:"open"` 83 | // Description : A description of the file request. 84 | Description string `json:"description,omitempty"` 85 | } 86 | 87 | // NewCreateFileRequestArgs returns a new CreateFileRequestArgs instance 88 | func NewCreateFileRequestArgs(Title string, Destination string) *CreateFileRequestArgs { 89 | s := new(CreateFileRequestArgs) 90 | s.Title = Title 91 | s.Destination = Destination 92 | s.Open = true 93 | return s 94 | } 95 | 96 | // FileRequestError : There is an error with the file request. 97 | type FileRequestError struct { 98 | dropbox.Tagged 99 | } 100 | 101 | // Valid tag values for FileRequestError 102 | const ( 103 | FileRequestErrorDisabledForTeam = "disabled_for_team" 104 | FileRequestErrorOther = "other" 105 | FileRequestErrorNotFound = "not_found" 106 | FileRequestErrorNotAFolder = "not_a_folder" 107 | FileRequestErrorAppLacksAccess = "app_lacks_access" 108 | FileRequestErrorNoPermission = "no_permission" 109 | FileRequestErrorEmailUnverified = "email_unverified" 110 | FileRequestErrorValidationError = "validation_error" 111 | ) 112 | 113 | // CreateFileRequestError : There was an error creating the file request. 114 | type CreateFileRequestError struct { 115 | dropbox.Tagged 116 | } 117 | 118 | // Valid tag values for CreateFileRequestError 119 | const ( 120 | CreateFileRequestErrorDisabledForTeam = "disabled_for_team" 121 | CreateFileRequestErrorOther = "other" 122 | CreateFileRequestErrorNotFound = "not_found" 123 | CreateFileRequestErrorNotAFolder = "not_a_folder" 124 | CreateFileRequestErrorAppLacksAccess = "app_lacks_access" 125 | CreateFileRequestErrorNoPermission = "no_permission" 126 | CreateFileRequestErrorEmailUnverified = "email_unverified" 127 | CreateFileRequestErrorValidationError = "validation_error" 128 | CreateFileRequestErrorInvalidLocation = "invalid_location" 129 | CreateFileRequestErrorRateLimit = "rate_limit" 130 | ) 131 | 132 | // DeleteAllClosedFileRequestsError : There was an error deleting all closed 133 | // file requests. 134 | type DeleteAllClosedFileRequestsError struct { 135 | dropbox.Tagged 136 | } 137 | 138 | // Valid tag values for DeleteAllClosedFileRequestsError 139 | const ( 140 | DeleteAllClosedFileRequestsErrorDisabledForTeam = "disabled_for_team" 141 | DeleteAllClosedFileRequestsErrorOther = "other" 142 | DeleteAllClosedFileRequestsErrorNotFound = "not_found" 143 | DeleteAllClosedFileRequestsErrorNotAFolder = "not_a_folder" 144 | DeleteAllClosedFileRequestsErrorAppLacksAccess = "app_lacks_access" 145 | DeleteAllClosedFileRequestsErrorNoPermission = "no_permission" 146 | DeleteAllClosedFileRequestsErrorEmailUnverified = "email_unverified" 147 | DeleteAllClosedFileRequestsErrorValidationError = "validation_error" 148 | ) 149 | 150 | // DeleteAllClosedFileRequestsResult : Result for `deleteAllClosed`. 151 | type DeleteAllClosedFileRequestsResult struct { 152 | // FileRequests : The file requests deleted for this user. 153 | FileRequests []*FileRequest `json:"file_requests"` 154 | } 155 | 156 | // NewDeleteAllClosedFileRequestsResult returns a new DeleteAllClosedFileRequestsResult instance 157 | func NewDeleteAllClosedFileRequestsResult(FileRequests []*FileRequest) *DeleteAllClosedFileRequestsResult { 158 | s := new(DeleteAllClosedFileRequestsResult) 159 | s.FileRequests = FileRequests 160 | return s 161 | } 162 | 163 | // DeleteFileRequestArgs : Arguments for `delete`. 164 | type DeleteFileRequestArgs struct { 165 | // Ids : List IDs of the file requests to delete. 166 | Ids []string `json:"ids"` 167 | } 168 | 169 | // NewDeleteFileRequestArgs returns a new DeleteFileRequestArgs instance 170 | func NewDeleteFileRequestArgs(Ids []string) *DeleteFileRequestArgs { 171 | s := new(DeleteFileRequestArgs) 172 | s.Ids = Ids 173 | return s 174 | } 175 | 176 | // DeleteFileRequestError : There was an error deleting these file requests. 177 | type DeleteFileRequestError struct { 178 | dropbox.Tagged 179 | } 180 | 181 | // Valid tag values for DeleteFileRequestError 182 | const ( 183 | DeleteFileRequestErrorDisabledForTeam = "disabled_for_team" 184 | DeleteFileRequestErrorOther = "other" 185 | DeleteFileRequestErrorNotFound = "not_found" 186 | DeleteFileRequestErrorNotAFolder = "not_a_folder" 187 | DeleteFileRequestErrorAppLacksAccess = "app_lacks_access" 188 | DeleteFileRequestErrorNoPermission = "no_permission" 189 | DeleteFileRequestErrorEmailUnverified = "email_unverified" 190 | DeleteFileRequestErrorValidationError = "validation_error" 191 | DeleteFileRequestErrorFileRequestOpen = "file_request_open" 192 | ) 193 | 194 | // DeleteFileRequestsResult : Result for `delete`. 195 | type DeleteFileRequestsResult struct { 196 | // FileRequests : The file requests deleted by the request. 197 | FileRequests []*FileRequest `json:"file_requests"` 198 | } 199 | 200 | // NewDeleteFileRequestsResult returns a new DeleteFileRequestsResult instance 201 | func NewDeleteFileRequestsResult(FileRequests []*FileRequest) *DeleteFileRequestsResult { 202 | s := new(DeleteFileRequestsResult) 203 | s.FileRequests = FileRequests 204 | return s 205 | } 206 | 207 | // FileRequest : A `file request` for 208 | // receiving files into the user's Dropbox account. 209 | type FileRequest struct { 210 | // Id : The ID of the file request. 211 | Id string `json:"id"` 212 | // Url : The URL of the file request. 213 | Url string `json:"url"` 214 | // Title : The title of the file request. 215 | Title string `json:"title"` 216 | // Destination : The path of the folder in the Dropbox where uploaded files 217 | // will be sent. This can be nil if the destination was removed. For apps 218 | // with the app folder permission, this will be relative to the app folder. 219 | Destination string `json:"destination,omitempty"` 220 | // Created : When this file request was created. 221 | Created time.Time `json:"created"` 222 | // Deadline : The deadline for this file request. Only set if the request 223 | // has a deadline. 224 | Deadline *FileRequestDeadline `json:"deadline,omitempty"` 225 | // IsOpen : Whether or not the file request is open. If the file request is 226 | // closed, it will not accept any more file submissions. 227 | IsOpen bool `json:"is_open"` 228 | // FileCount : The number of files this file request has received. 229 | FileCount int64 `json:"file_count"` 230 | // Description : A description of the file request. 231 | Description string `json:"description,omitempty"` 232 | } 233 | 234 | // NewFileRequest returns a new FileRequest instance 235 | func NewFileRequest(Id string, Url string, Title string, Created time.Time, IsOpen bool, FileCount int64) *FileRequest { 236 | s := new(FileRequest) 237 | s.Id = Id 238 | s.Url = Url 239 | s.Title = Title 240 | s.Created = Created 241 | s.IsOpen = IsOpen 242 | s.FileCount = FileCount 243 | return s 244 | } 245 | 246 | // FileRequestDeadline : has no documentation (yet) 247 | type FileRequestDeadline struct { 248 | // Deadline : The deadline for this file request. 249 | Deadline time.Time `json:"deadline"` 250 | // AllowLateUploads : If set, allow uploads after the deadline has passed. 251 | // These uploads will be marked overdue. 252 | AllowLateUploads *GracePeriod `json:"allow_late_uploads,omitempty"` 253 | } 254 | 255 | // NewFileRequestDeadline returns a new FileRequestDeadline instance 256 | func NewFileRequestDeadline(Deadline time.Time) *FileRequestDeadline { 257 | s := new(FileRequestDeadline) 258 | s.Deadline = Deadline 259 | return s 260 | } 261 | 262 | // GetFileRequestArgs : Arguments for `get`. 263 | type GetFileRequestArgs struct { 264 | // Id : The ID of the file request to retrieve. 265 | Id string `json:"id"` 266 | } 267 | 268 | // NewGetFileRequestArgs returns a new GetFileRequestArgs instance 269 | func NewGetFileRequestArgs(Id string) *GetFileRequestArgs { 270 | s := new(GetFileRequestArgs) 271 | s.Id = Id 272 | return s 273 | } 274 | 275 | // GetFileRequestError : There was an error retrieving the specified file 276 | // request. 277 | type GetFileRequestError struct { 278 | dropbox.Tagged 279 | } 280 | 281 | // Valid tag values for GetFileRequestError 282 | const ( 283 | GetFileRequestErrorDisabledForTeam = "disabled_for_team" 284 | GetFileRequestErrorOther = "other" 285 | GetFileRequestErrorNotFound = "not_found" 286 | GetFileRequestErrorNotAFolder = "not_a_folder" 287 | GetFileRequestErrorAppLacksAccess = "app_lacks_access" 288 | GetFileRequestErrorNoPermission = "no_permission" 289 | GetFileRequestErrorEmailUnverified = "email_unverified" 290 | GetFileRequestErrorValidationError = "validation_error" 291 | ) 292 | 293 | // GracePeriod : has no documentation (yet) 294 | type GracePeriod struct { 295 | dropbox.Tagged 296 | } 297 | 298 | // Valid tag values for GracePeriod 299 | const ( 300 | GracePeriodOneDay = "one_day" 301 | GracePeriodTwoDays = "two_days" 302 | GracePeriodSevenDays = "seven_days" 303 | GracePeriodThirtyDays = "thirty_days" 304 | GracePeriodAlways = "always" 305 | GracePeriodOther = "other" 306 | ) 307 | 308 | // ListFileRequestsArg : Arguments for `list`. 309 | type ListFileRequestsArg struct { 310 | // Limit : The maximum number of file requests that should be returned per 311 | // request. 312 | Limit uint64 `json:"limit"` 313 | } 314 | 315 | // NewListFileRequestsArg returns a new ListFileRequestsArg instance 316 | func NewListFileRequestsArg() *ListFileRequestsArg { 317 | s := new(ListFileRequestsArg) 318 | s.Limit = 1000 319 | return s 320 | } 321 | 322 | // ListFileRequestsContinueArg : has no documentation (yet) 323 | type ListFileRequestsContinueArg struct { 324 | // Cursor : The cursor returned by the previous API call specified in the 325 | // endpoint description. 326 | Cursor string `json:"cursor"` 327 | } 328 | 329 | // NewListFileRequestsContinueArg returns a new ListFileRequestsContinueArg instance 330 | func NewListFileRequestsContinueArg(Cursor string) *ListFileRequestsContinueArg { 331 | s := new(ListFileRequestsContinueArg) 332 | s.Cursor = Cursor 333 | return s 334 | } 335 | 336 | // ListFileRequestsContinueError : There was an error retrieving the file 337 | // requests. 338 | type ListFileRequestsContinueError struct { 339 | dropbox.Tagged 340 | } 341 | 342 | // Valid tag values for ListFileRequestsContinueError 343 | const ( 344 | ListFileRequestsContinueErrorDisabledForTeam = "disabled_for_team" 345 | ListFileRequestsContinueErrorOther = "other" 346 | ListFileRequestsContinueErrorInvalidCursor = "invalid_cursor" 347 | ) 348 | 349 | // ListFileRequestsError : There was an error retrieving the file requests. 350 | type ListFileRequestsError struct { 351 | dropbox.Tagged 352 | } 353 | 354 | // Valid tag values for ListFileRequestsError 355 | const ( 356 | ListFileRequestsErrorDisabledForTeam = "disabled_for_team" 357 | ListFileRequestsErrorOther = "other" 358 | ) 359 | 360 | // ListFileRequestsResult : Result for `list`. 361 | type ListFileRequestsResult struct { 362 | // FileRequests : The file requests owned by this user. Apps with the app 363 | // folder permission will only see file requests in their app folder. 364 | FileRequests []*FileRequest `json:"file_requests"` 365 | } 366 | 367 | // NewListFileRequestsResult returns a new ListFileRequestsResult instance 368 | func NewListFileRequestsResult(FileRequests []*FileRequest) *ListFileRequestsResult { 369 | s := new(ListFileRequestsResult) 370 | s.FileRequests = FileRequests 371 | return s 372 | } 373 | 374 | // ListFileRequestsV2Result : Result for `list` and `listContinue`. 375 | type ListFileRequestsV2Result struct { 376 | // FileRequests : The file requests owned by this user. Apps with the app 377 | // folder permission will only see file requests in their app folder. 378 | FileRequests []*FileRequest `json:"file_requests"` 379 | // Cursor : Pass the cursor into `listContinue` to obtain additional file 380 | // requests. 381 | Cursor string `json:"cursor"` 382 | // HasMore : Is true if there are additional file requests that have not 383 | // been returned yet. An additional call to :route:list/continue` can 384 | // retrieve them. 385 | HasMore bool `json:"has_more"` 386 | } 387 | 388 | // NewListFileRequestsV2Result returns a new ListFileRequestsV2Result instance 389 | func NewListFileRequestsV2Result(FileRequests []*FileRequest, Cursor string, HasMore bool) *ListFileRequestsV2Result { 390 | s := new(ListFileRequestsV2Result) 391 | s.FileRequests = FileRequests 392 | s.Cursor = Cursor 393 | s.HasMore = HasMore 394 | return s 395 | } 396 | 397 | // UpdateFileRequestArgs : Arguments for `update`. 398 | type UpdateFileRequestArgs struct { 399 | // Id : The ID of the file request to update. 400 | Id string `json:"id"` 401 | // Title : The new title of the file request. Must not be empty. 402 | Title string `json:"title,omitempty"` 403 | // Destination : The new path of the folder in the Dropbox where uploaded 404 | // files will be sent. For apps with the app folder permission, this will be 405 | // relative to the app folder. 406 | Destination string `json:"destination,omitempty"` 407 | // Deadline : The new deadline for the file request. Deadlines can only be 408 | // set by Professional and Business accounts. 409 | Deadline *UpdateFileRequestDeadline `json:"deadline"` 410 | // Open : Whether to set this file request as open or closed. 411 | Open bool `json:"open,omitempty"` 412 | // Description : The description of the file request. 413 | Description string `json:"description,omitempty"` 414 | } 415 | 416 | // NewUpdateFileRequestArgs returns a new UpdateFileRequestArgs instance 417 | func NewUpdateFileRequestArgs(Id string) *UpdateFileRequestArgs { 418 | s := new(UpdateFileRequestArgs) 419 | s.Id = Id 420 | s.Deadline = &UpdateFileRequestDeadline{Tagged: dropbox.Tagged{Tag: "no_update"}} 421 | return s 422 | } 423 | 424 | // UpdateFileRequestDeadline : has no documentation (yet) 425 | type UpdateFileRequestDeadline struct { 426 | dropbox.Tagged 427 | // Update : If nil, the file request's deadline is cleared. 428 | Update *FileRequestDeadline `json:"update,omitempty"` 429 | } 430 | 431 | // Valid tag values for UpdateFileRequestDeadline 432 | const ( 433 | UpdateFileRequestDeadlineNoUpdate = "no_update" 434 | UpdateFileRequestDeadlineUpdate = "update" 435 | UpdateFileRequestDeadlineOther = "other" 436 | ) 437 | 438 | // UnmarshalJSON deserializes into a UpdateFileRequestDeadline instance 439 | func (u *UpdateFileRequestDeadline) UnmarshalJSON(body []byte) error { 440 | type wrap struct { 441 | dropbox.Tagged 442 | // Update : If nil, the file request's deadline is cleared. 443 | Update *FileRequestDeadline `json:"update,omitempty"` 444 | } 445 | var w wrap 446 | var err error 447 | if err = json.Unmarshal(body, &w); err != nil { 448 | return err 449 | } 450 | u.Tag = w.Tag 451 | switch u.Tag { 452 | case "update": 453 | u.Update = w.Update 454 | 455 | } 456 | return nil 457 | } 458 | 459 | // UpdateFileRequestError : There is an error updating the file request. 460 | type UpdateFileRequestError struct { 461 | dropbox.Tagged 462 | } 463 | 464 | // Valid tag values for UpdateFileRequestError 465 | const ( 466 | UpdateFileRequestErrorDisabledForTeam = "disabled_for_team" 467 | UpdateFileRequestErrorOther = "other" 468 | UpdateFileRequestErrorNotFound = "not_found" 469 | UpdateFileRequestErrorNotAFolder = "not_a_folder" 470 | UpdateFileRequestErrorAppLacksAccess = "app_lacks_access" 471 | UpdateFileRequestErrorNoPermission = "no_permission" 472 | UpdateFileRequestErrorEmailUnverified = "email_unverified" 473 | UpdateFileRequestErrorValidationError = "validation_error" 474 | ) 475 | -------------------------------------------------------------------------------- /v6/dropbox/file_properties/client.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) Dropbox, Inc. 2 | // 3 | // Permission is hereby granted, free of charge, to any person obtaining a copy 4 | // of this software and associated documentation files (the "Software"), to deal 5 | // in the Software without restriction, including without limitation the rights 6 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | // copies of the Software, and to permit persons to whom the Software is 8 | // furnished to do so, subject to the following conditions: 9 | // 10 | // The above copyright notice and this permission notice shall be included in 11 | // all copies or substantial portions of the Software. 12 | // 13 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | // THE SOFTWARE. 20 | 21 | package file_properties 22 | 23 | import ( 24 | "encoding/json" 25 | "io" 26 | 27 | "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox" 28 | "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox/auth" 29 | ) 30 | 31 | // Client interface describes all routes in this namespace 32 | type Client interface { 33 | // PropertiesAdd : Add property groups to a Dropbox file. See 34 | // `templatesAddForUser` or `templatesAddForTeam` to create new templates. 35 | PropertiesAdd(arg *AddPropertiesArg) (err error) 36 | // PropertiesOverwrite : Overwrite property groups associated with a file. 37 | // This endpoint should be used instead of `propertiesUpdate` when property 38 | // groups are being updated via a "snapshot" instead of via a "delta". In 39 | // other words, this endpoint will delete all omitted fields from a property 40 | // group, whereas `propertiesUpdate` will only delete fields that are 41 | // explicitly marked for deletion. 42 | PropertiesOverwrite(arg *OverwritePropertyGroupArg) (err error) 43 | // PropertiesRemove : Permanently removes the specified property group from 44 | // the file. To remove specific property field key value pairs, see 45 | // `propertiesUpdate`. To update a template, see `templatesUpdateForUser` or 46 | // `templatesUpdateForTeam`. To remove a template, see 47 | // `templatesRemoveForUser` or `templatesRemoveForTeam`. 48 | PropertiesRemove(arg *RemovePropertiesArg) (err error) 49 | // PropertiesSearch : Search across property templates for particular 50 | // property field values. 51 | PropertiesSearch(arg *PropertiesSearchArg) (res *PropertiesSearchResult, err error) 52 | // PropertiesSearchContinue : Once a cursor has been retrieved from 53 | // `propertiesSearch`, use this to paginate through all search results. 54 | PropertiesSearchContinue(arg *PropertiesSearchContinueArg) (res *PropertiesSearchResult, err error) 55 | // PropertiesUpdate : Add, update or remove properties associated with the 56 | // supplied file and templates. This endpoint should be used instead of 57 | // `propertiesOverwrite` when property groups are being updated via a 58 | // "delta" instead of via a "snapshot" . In other words, this endpoint will 59 | // not delete any omitted fields from a property group, whereas 60 | // `propertiesOverwrite` will delete any fields that are omitted from a 61 | // property group. 62 | PropertiesUpdate(arg *UpdatePropertiesArg) (err error) 63 | // TemplatesAddForTeam : Add a template associated with a team. See 64 | // `propertiesAdd` to add properties to a file or folder. Note: this 65 | // endpoint will create team-owned templates. 66 | TemplatesAddForTeam(arg *AddTemplateArg) (res *AddTemplateResult, err error) 67 | // TemplatesAddForUser : Add a template associated with a user. See 68 | // `propertiesAdd` to add properties to a file. This endpoint can't be 69 | // called on a team member or admin's behalf. 70 | TemplatesAddForUser(arg *AddTemplateArg) (res *AddTemplateResult, err error) 71 | // TemplatesGetForTeam : Get the schema for a specified template. 72 | TemplatesGetForTeam(arg *GetTemplateArg) (res *GetTemplateResult, err error) 73 | // TemplatesGetForUser : Get the schema for a specified template. This 74 | // endpoint can't be called on a team member or admin's behalf. 75 | TemplatesGetForUser(arg *GetTemplateArg) (res *GetTemplateResult, err error) 76 | // TemplatesListForTeam : Get the template identifiers for a team. To get 77 | // the schema of each template use `templatesGetForTeam`. 78 | TemplatesListForTeam() (res *ListTemplateResult, err error) 79 | // TemplatesListForUser : Get the template identifiers for a team. To get 80 | // the schema of each template use `templatesGetForUser`. This endpoint 81 | // can't be called on a team member or admin's behalf. 82 | TemplatesListForUser() (res *ListTemplateResult, err error) 83 | // TemplatesRemoveForTeam : Permanently removes the specified template 84 | // created from `templatesAddForUser`. All properties associated with the 85 | // template will also be removed. This action cannot be undone. 86 | TemplatesRemoveForTeam(arg *RemoveTemplateArg) (err error) 87 | // TemplatesRemoveForUser : Permanently removes the specified template 88 | // created from `templatesAddForUser`. All properties associated with the 89 | // template will also be removed. This action cannot be undone. 90 | TemplatesRemoveForUser(arg *RemoveTemplateArg) (err error) 91 | // TemplatesUpdateForTeam : Update a template associated with a team. This 92 | // route can update the template name, the template description and add 93 | // optional properties to templates. 94 | TemplatesUpdateForTeam(arg *UpdateTemplateArg) (res *UpdateTemplateResult, err error) 95 | // TemplatesUpdateForUser : Update a template associated with a user. This 96 | // route can update the template name, the template description and add 97 | // optional properties to templates. This endpoint can't be called on a team 98 | // member or admin's behalf. 99 | TemplatesUpdateForUser(arg *UpdateTemplateArg) (res *UpdateTemplateResult, err error) 100 | } 101 | 102 | type apiImpl dropbox.Context 103 | 104 | //PropertiesAddAPIError is an error-wrapper for the properties/add route 105 | type PropertiesAddAPIError struct { 106 | dropbox.APIError 107 | EndpointError *AddPropertiesError `json:"error"` 108 | } 109 | 110 | func (dbx *apiImpl) PropertiesAdd(arg *AddPropertiesArg) (err error) { 111 | req := dropbox.Request{ 112 | Host: "api", 113 | Namespace: "file_properties", 114 | Route: "properties/add", 115 | Auth: "user", 116 | Style: "rpc", 117 | Arg: arg, 118 | ExtraHeaders: nil, 119 | } 120 | 121 | var resp []byte 122 | var respBody io.ReadCloser 123 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 124 | if err != nil { 125 | var appErr PropertiesAddAPIError 126 | err = auth.ParseError(err, &appErr) 127 | if err == &appErr { 128 | err = appErr 129 | } 130 | return 131 | } 132 | 133 | _ = resp 134 | _ = respBody 135 | return 136 | } 137 | 138 | //PropertiesOverwriteAPIError is an error-wrapper for the properties/overwrite route 139 | type PropertiesOverwriteAPIError struct { 140 | dropbox.APIError 141 | EndpointError *InvalidPropertyGroupError `json:"error"` 142 | } 143 | 144 | func (dbx *apiImpl) PropertiesOverwrite(arg *OverwritePropertyGroupArg) (err error) { 145 | req := dropbox.Request{ 146 | Host: "api", 147 | Namespace: "file_properties", 148 | Route: "properties/overwrite", 149 | Auth: "user", 150 | Style: "rpc", 151 | Arg: arg, 152 | ExtraHeaders: nil, 153 | } 154 | 155 | var resp []byte 156 | var respBody io.ReadCloser 157 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 158 | if err != nil { 159 | var appErr PropertiesOverwriteAPIError 160 | err = auth.ParseError(err, &appErr) 161 | if err == &appErr { 162 | err = appErr 163 | } 164 | return 165 | } 166 | 167 | _ = resp 168 | _ = respBody 169 | return 170 | } 171 | 172 | //PropertiesRemoveAPIError is an error-wrapper for the properties/remove route 173 | type PropertiesRemoveAPIError struct { 174 | dropbox.APIError 175 | EndpointError *RemovePropertiesError `json:"error"` 176 | } 177 | 178 | func (dbx *apiImpl) PropertiesRemove(arg *RemovePropertiesArg) (err error) { 179 | req := dropbox.Request{ 180 | Host: "api", 181 | Namespace: "file_properties", 182 | Route: "properties/remove", 183 | Auth: "user", 184 | Style: "rpc", 185 | Arg: arg, 186 | ExtraHeaders: nil, 187 | } 188 | 189 | var resp []byte 190 | var respBody io.ReadCloser 191 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 192 | if err != nil { 193 | var appErr PropertiesRemoveAPIError 194 | err = auth.ParseError(err, &appErr) 195 | if err == &appErr { 196 | err = appErr 197 | } 198 | return 199 | } 200 | 201 | _ = resp 202 | _ = respBody 203 | return 204 | } 205 | 206 | //PropertiesSearchAPIError is an error-wrapper for the properties/search route 207 | type PropertiesSearchAPIError struct { 208 | dropbox.APIError 209 | EndpointError *PropertiesSearchError `json:"error"` 210 | } 211 | 212 | func (dbx *apiImpl) PropertiesSearch(arg *PropertiesSearchArg) (res *PropertiesSearchResult, err error) { 213 | req := dropbox.Request{ 214 | Host: "api", 215 | Namespace: "file_properties", 216 | Route: "properties/search", 217 | Auth: "user", 218 | Style: "rpc", 219 | Arg: arg, 220 | ExtraHeaders: nil, 221 | } 222 | 223 | var resp []byte 224 | var respBody io.ReadCloser 225 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 226 | if err != nil { 227 | var appErr PropertiesSearchAPIError 228 | err = auth.ParseError(err, &appErr) 229 | if err == &appErr { 230 | err = appErr 231 | } 232 | return 233 | } 234 | 235 | err = json.Unmarshal(resp, &res) 236 | if err != nil { 237 | return 238 | } 239 | 240 | _ = respBody 241 | return 242 | } 243 | 244 | //PropertiesSearchContinueAPIError is an error-wrapper for the properties/search/continue route 245 | type PropertiesSearchContinueAPIError struct { 246 | dropbox.APIError 247 | EndpointError *PropertiesSearchContinueError `json:"error"` 248 | } 249 | 250 | func (dbx *apiImpl) PropertiesSearchContinue(arg *PropertiesSearchContinueArg) (res *PropertiesSearchResult, err error) { 251 | req := dropbox.Request{ 252 | Host: "api", 253 | Namespace: "file_properties", 254 | Route: "properties/search/continue", 255 | Auth: "user", 256 | Style: "rpc", 257 | Arg: arg, 258 | ExtraHeaders: nil, 259 | } 260 | 261 | var resp []byte 262 | var respBody io.ReadCloser 263 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 264 | if err != nil { 265 | var appErr PropertiesSearchContinueAPIError 266 | err = auth.ParseError(err, &appErr) 267 | if err == &appErr { 268 | err = appErr 269 | } 270 | return 271 | } 272 | 273 | err = json.Unmarshal(resp, &res) 274 | if err != nil { 275 | return 276 | } 277 | 278 | _ = respBody 279 | return 280 | } 281 | 282 | //PropertiesUpdateAPIError is an error-wrapper for the properties/update route 283 | type PropertiesUpdateAPIError struct { 284 | dropbox.APIError 285 | EndpointError *UpdatePropertiesError `json:"error"` 286 | } 287 | 288 | func (dbx *apiImpl) PropertiesUpdate(arg *UpdatePropertiesArg) (err error) { 289 | req := dropbox.Request{ 290 | Host: "api", 291 | Namespace: "file_properties", 292 | Route: "properties/update", 293 | Auth: "user", 294 | Style: "rpc", 295 | Arg: arg, 296 | ExtraHeaders: nil, 297 | } 298 | 299 | var resp []byte 300 | var respBody io.ReadCloser 301 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 302 | if err != nil { 303 | var appErr PropertiesUpdateAPIError 304 | err = auth.ParseError(err, &appErr) 305 | if err == &appErr { 306 | err = appErr 307 | } 308 | return 309 | } 310 | 311 | _ = resp 312 | _ = respBody 313 | return 314 | } 315 | 316 | //TemplatesAddForTeamAPIError is an error-wrapper for the templates/add_for_team route 317 | type TemplatesAddForTeamAPIError struct { 318 | dropbox.APIError 319 | EndpointError *ModifyTemplateError `json:"error"` 320 | } 321 | 322 | func (dbx *apiImpl) TemplatesAddForTeam(arg *AddTemplateArg) (res *AddTemplateResult, err error) { 323 | req := dropbox.Request{ 324 | Host: "api", 325 | Namespace: "file_properties", 326 | Route: "templates/add_for_team", 327 | Auth: "team", 328 | Style: "rpc", 329 | Arg: arg, 330 | ExtraHeaders: nil, 331 | } 332 | 333 | var resp []byte 334 | var respBody io.ReadCloser 335 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 336 | if err != nil { 337 | var appErr TemplatesAddForTeamAPIError 338 | err = auth.ParseError(err, &appErr) 339 | if err == &appErr { 340 | err = appErr 341 | } 342 | return 343 | } 344 | 345 | err = json.Unmarshal(resp, &res) 346 | if err != nil { 347 | return 348 | } 349 | 350 | _ = respBody 351 | return 352 | } 353 | 354 | //TemplatesAddForUserAPIError is an error-wrapper for the templates/add_for_user route 355 | type TemplatesAddForUserAPIError struct { 356 | dropbox.APIError 357 | EndpointError *ModifyTemplateError `json:"error"` 358 | } 359 | 360 | func (dbx *apiImpl) TemplatesAddForUser(arg *AddTemplateArg) (res *AddTemplateResult, err error) { 361 | req := dropbox.Request{ 362 | Host: "api", 363 | Namespace: "file_properties", 364 | Route: "templates/add_for_user", 365 | Auth: "user", 366 | Style: "rpc", 367 | Arg: arg, 368 | ExtraHeaders: nil, 369 | } 370 | 371 | var resp []byte 372 | var respBody io.ReadCloser 373 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 374 | if err != nil { 375 | var appErr TemplatesAddForUserAPIError 376 | err = auth.ParseError(err, &appErr) 377 | if err == &appErr { 378 | err = appErr 379 | } 380 | return 381 | } 382 | 383 | err = json.Unmarshal(resp, &res) 384 | if err != nil { 385 | return 386 | } 387 | 388 | _ = respBody 389 | return 390 | } 391 | 392 | //TemplatesGetForTeamAPIError is an error-wrapper for the templates/get_for_team route 393 | type TemplatesGetForTeamAPIError struct { 394 | dropbox.APIError 395 | EndpointError *TemplateError `json:"error"` 396 | } 397 | 398 | func (dbx *apiImpl) TemplatesGetForTeam(arg *GetTemplateArg) (res *GetTemplateResult, err error) { 399 | req := dropbox.Request{ 400 | Host: "api", 401 | Namespace: "file_properties", 402 | Route: "templates/get_for_team", 403 | Auth: "team", 404 | Style: "rpc", 405 | Arg: arg, 406 | ExtraHeaders: nil, 407 | } 408 | 409 | var resp []byte 410 | var respBody io.ReadCloser 411 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 412 | if err != nil { 413 | var appErr TemplatesGetForTeamAPIError 414 | err = auth.ParseError(err, &appErr) 415 | if err == &appErr { 416 | err = appErr 417 | } 418 | return 419 | } 420 | 421 | err = json.Unmarshal(resp, &res) 422 | if err != nil { 423 | return 424 | } 425 | 426 | _ = respBody 427 | return 428 | } 429 | 430 | //TemplatesGetForUserAPIError is an error-wrapper for the templates/get_for_user route 431 | type TemplatesGetForUserAPIError struct { 432 | dropbox.APIError 433 | EndpointError *TemplateError `json:"error"` 434 | } 435 | 436 | func (dbx *apiImpl) TemplatesGetForUser(arg *GetTemplateArg) (res *GetTemplateResult, err error) { 437 | req := dropbox.Request{ 438 | Host: "api", 439 | Namespace: "file_properties", 440 | Route: "templates/get_for_user", 441 | Auth: "user", 442 | Style: "rpc", 443 | Arg: arg, 444 | ExtraHeaders: nil, 445 | } 446 | 447 | var resp []byte 448 | var respBody io.ReadCloser 449 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 450 | if err != nil { 451 | var appErr TemplatesGetForUserAPIError 452 | err = auth.ParseError(err, &appErr) 453 | if err == &appErr { 454 | err = appErr 455 | } 456 | return 457 | } 458 | 459 | err = json.Unmarshal(resp, &res) 460 | if err != nil { 461 | return 462 | } 463 | 464 | _ = respBody 465 | return 466 | } 467 | 468 | //TemplatesListForTeamAPIError is an error-wrapper for the templates/list_for_team route 469 | type TemplatesListForTeamAPIError struct { 470 | dropbox.APIError 471 | EndpointError *TemplateError `json:"error"` 472 | } 473 | 474 | func (dbx *apiImpl) TemplatesListForTeam() (res *ListTemplateResult, err error) { 475 | req := dropbox.Request{ 476 | Host: "api", 477 | Namespace: "file_properties", 478 | Route: "templates/list_for_team", 479 | Auth: "team", 480 | Style: "rpc", 481 | Arg: nil, 482 | ExtraHeaders: nil, 483 | } 484 | 485 | var resp []byte 486 | var respBody io.ReadCloser 487 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 488 | if err != nil { 489 | var appErr TemplatesListForTeamAPIError 490 | err = auth.ParseError(err, &appErr) 491 | if err == &appErr { 492 | err = appErr 493 | } 494 | return 495 | } 496 | 497 | err = json.Unmarshal(resp, &res) 498 | if err != nil { 499 | return 500 | } 501 | 502 | _ = respBody 503 | return 504 | } 505 | 506 | //TemplatesListForUserAPIError is an error-wrapper for the templates/list_for_user route 507 | type TemplatesListForUserAPIError struct { 508 | dropbox.APIError 509 | EndpointError *TemplateError `json:"error"` 510 | } 511 | 512 | func (dbx *apiImpl) TemplatesListForUser() (res *ListTemplateResult, err error) { 513 | req := dropbox.Request{ 514 | Host: "api", 515 | Namespace: "file_properties", 516 | Route: "templates/list_for_user", 517 | Auth: "user", 518 | Style: "rpc", 519 | Arg: nil, 520 | ExtraHeaders: nil, 521 | } 522 | 523 | var resp []byte 524 | var respBody io.ReadCloser 525 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 526 | if err != nil { 527 | var appErr TemplatesListForUserAPIError 528 | err = auth.ParseError(err, &appErr) 529 | if err == &appErr { 530 | err = appErr 531 | } 532 | return 533 | } 534 | 535 | err = json.Unmarshal(resp, &res) 536 | if err != nil { 537 | return 538 | } 539 | 540 | _ = respBody 541 | return 542 | } 543 | 544 | //TemplatesRemoveForTeamAPIError is an error-wrapper for the templates/remove_for_team route 545 | type TemplatesRemoveForTeamAPIError struct { 546 | dropbox.APIError 547 | EndpointError *TemplateError `json:"error"` 548 | } 549 | 550 | func (dbx *apiImpl) TemplatesRemoveForTeam(arg *RemoveTemplateArg) (err error) { 551 | req := dropbox.Request{ 552 | Host: "api", 553 | Namespace: "file_properties", 554 | Route: "templates/remove_for_team", 555 | Auth: "team", 556 | Style: "rpc", 557 | Arg: arg, 558 | ExtraHeaders: nil, 559 | } 560 | 561 | var resp []byte 562 | var respBody io.ReadCloser 563 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 564 | if err != nil { 565 | var appErr TemplatesRemoveForTeamAPIError 566 | err = auth.ParseError(err, &appErr) 567 | if err == &appErr { 568 | err = appErr 569 | } 570 | return 571 | } 572 | 573 | _ = resp 574 | _ = respBody 575 | return 576 | } 577 | 578 | //TemplatesRemoveForUserAPIError is an error-wrapper for the templates/remove_for_user route 579 | type TemplatesRemoveForUserAPIError struct { 580 | dropbox.APIError 581 | EndpointError *TemplateError `json:"error"` 582 | } 583 | 584 | func (dbx *apiImpl) TemplatesRemoveForUser(arg *RemoveTemplateArg) (err error) { 585 | req := dropbox.Request{ 586 | Host: "api", 587 | Namespace: "file_properties", 588 | Route: "templates/remove_for_user", 589 | Auth: "user", 590 | Style: "rpc", 591 | Arg: arg, 592 | ExtraHeaders: nil, 593 | } 594 | 595 | var resp []byte 596 | var respBody io.ReadCloser 597 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 598 | if err != nil { 599 | var appErr TemplatesRemoveForUserAPIError 600 | err = auth.ParseError(err, &appErr) 601 | if err == &appErr { 602 | err = appErr 603 | } 604 | return 605 | } 606 | 607 | _ = resp 608 | _ = respBody 609 | return 610 | } 611 | 612 | //TemplatesUpdateForTeamAPIError is an error-wrapper for the templates/update_for_team route 613 | type TemplatesUpdateForTeamAPIError struct { 614 | dropbox.APIError 615 | EndpointError *ModifyTemplateError `json:"error"` 616 | } 617 | 618 | func (dbx *apiImpl) TemplatesUpdateForTeam(arg *UpdateTemplateArg) (res *UpdateTemplateResult, err error) { 619 | req := dropbox.Request{ 620 | Host: "api", 621 | Namespace: "file_properties", 622 | Route: "templates/update_for_team", 623 | Auth: "team", 624 | Style: "rpc", 625 | Arg: arg, 626 | ExtraHeaders: nil, 627 | } 628 | 629 | var resp []byte 630 | var respBody io.ReadCloser 631 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 632 | if err != nil { 633 | var appErr TemplatesUpdateForTeamAPIError 634 | err = auth.ParseError(err, &appErr) 635 | if err == &appErr { 636 | err = appErr 637 | } 638 | return 639 | } 640 | 641 | err = json.Unmarshal(resp, &res) 642 | if err != nil { 643 | return 644 | } 645 | 646 | _ = respBody 647 | return 648 | } 649 | 650 | //TemplatesUpdateForUserAPIError is an error-wrapper for the templates/update_for_user route 651 | type TemplatesUpdateForUserAPIError struct { 652 | dropbox.APIError 653 | EndpointError *ModifyTemplateError `json:"error"` 654 | } 655 | 656 | func (dbx *apiImpl) TemplatesUpdateForUser(arg *UpdateTemplateArg) (res *UpdateTemplateResult, err error) { 657 | req := dropbox.Request{ 658 | Host: "api", 659 | Namespace: "file_properties", 660 | Route: "templates/update_for_user", 661 | Auth: "user", 662 | Style: "rpc", 663 | Arg: arg, 664 | ExtraHeaders: nil, 665 | } 666 | 667 | var resp []byte 668 | var respBody io.ReadCloser 669 | resp, respBody, err = (*dropbox.Context)(dbx).Execute(req, nil) 670 | if err != nil { 671 | var appErr TemplatesUpdateForUserAPIError 672 | err = auth.ParseError(err, &appErr) 673 | if err == &appErr { 674 | err = appErr 675 | } 676 | return 677 | } 678 | 679 | err = json.Unmarshal(resp, &res) 680 | if err != nil { 681 | return 682 | } 683 | 684 | _ = respBody 685 | return 686 | } 687 | 688 | // New returns a Client implementation for this namespace 689 | func New(c dropbox.Config) Client { 690 | ctx := apiImpl(dropbox.NewContext(c)) 691 | return &ctx 692 | } 693 | --------------------------------------------------------------------------------