Code Monkey home page Code Monkey logo

dropbox-sdk-js's Introduction

Logo

node-current npm codecov

The offical Dropbox SDK for Javascript.

Documentation can be found on GitHub Pages

Installation

Create an app via the Developer Console

Install via npm

$ npm install --save dropbox

Install from source:

$ git clone https://github.com/dropbox/dropbox-sdk-js.git
$ cd dropbox-sdk-js
$ npm install

If you are using the repository from the browser, you can use any CDNs that hosts the Dropbox package by including a script tag with the link to the package. However, we highly recommend you do not directly import the latest version and instead choose a specific version. When we update and release a breaking change, this could break production code which we hope to avoid. Note, we follow semver naming conventions which means that any major version update could contain a breaking change.

After installation, follow one of our Examples or read the Documentation.

You can also view our OAuth guide.

Examples

We provide Examples to help get you started with a lot of the basic functionality in the SDK. We provide most examples in both Javascript and Typescript with some having a Node equivalent.

  • OAuth

    • Auth - [ JS ] - A simple auth example to get an access token and list the files in the root of your Dropbox account.
    • Simple Backend [ JS ] - A simple example of a node backend doing a multi-step auth flow for Short Lived Tokens.
    • PKCE Backend [ JS ] - A simple example of a node backend doing a multi-step auth flow using PKCE and Short Lived Tokens.
    • PKCE Browser [ JS ] - A simple example of a frontend doing a multi-step auth flow using PKCE and Short Lived Tokens.
  • Other Examples

    • Basic - [ TS, JS ] - A simple example that takes in a token and fetches files from your Dropbox account.
    • Download - [ TS, JS ] - An example showing how to download a shared file.
    • Team As User - [ TS, JS ] - An example showing how to act as a user.
    • Team - [ TS, JS ] - An example showing how to use the team functionality and list team devices.
    • Upload [ TS, JS ] - An example showing how to upload a file to Dropbox.

Getting Help

If you find a bug, please see CONTRIBUTING.md for information on how to report it.

If you need help that is not specific to this SDK, please reach out to Dropbox Support.

License

This SDK is distributed under the MIT license, please see LICENSE for more information.

dropbox-sdk-js's People

Contributors

4ian avatar abstractmatter avatar adam187 avatar alexandrtovmach avatar alexeytoksarov avatar alexpelan avatar beckhvr avatar bengourley avatar bohdan-tereta avatar bpinto avatar braincore avatar brent1lt avatar connorworley avatar dependabot[bot] avatar destegabry avatar dropboxbot avatar ertanyildiz avatar greg-db avatar harund avatar kwrush avatar mtruong-dbx avatar nicoduj avatar ohpyupi avatar patgauvingeek avatar pran1990 avatar rileytomasek avatar robertmaloney avatar rogebrd avatar sidhuko avatar wenceslauu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dropbox-sdk-js's Issues

Files get corrupted when uploading

Files get corrupted when I upload a doc, docx or pdf file:

dbx.filesUpload({ path:  path, contents: fs.readFileSync(filepath) })
    .then(function (response) {
        console.log(response);
    })
    .catch(function (err) {
        console.log("Error:");
        console.log(err);
    });

test

sorry if you got spammed by this...

TypeScript Typings

I'm opening up this issue to start a dialog. Would you be open to generating TypeScript typings for your library, and including them in the NPM package?

Overview

I wrote a TypeScript definition generator for Stone that can automatically generate a TypeScript definition file for a JavaScript client. Stone types neatly map onto TypeScript interfaces. All the generator needs is a template to "fill in" with routes and types.

Here's the template I wrote for this SDK, which contains manual typings for the portions of your SDK that are not generated by Stone:

// Namespace that holds all of the types to avoid scope pollution.
declare module DropboxTypes {
  interface DropboxOptions {
    // An access token for making authenticated requests.
    accessToken: string;
    // The client id for your app. Used to create authentication URL.
    clientId: string;
    // Select user is only used by team endpoints. It specifies which user the team access token should be acting as.
    selectUser?: string;
  }

  class Dropbox {
    /**
     * The Dropbox SDK class.
     */
    constructor(options: { accessToken: string, clientId: string, selectUser: string });

    /**
     * Returns an instance of Dropbox that can make calls to user api endpoints on
     * behalf of the passed user id, using the team access token. Only relevant for
     * team endpoints.
     */
    actAsUser(userId: string): Dropbox;


/*ROUTES*/
  }

/*TYPES*/
}

// Global Dropbox variable, when included as script.
declare var Dropbox: typeof DropboxTypes.Dropbox;

// NPM module (require("dropbox"))
declare module "dropbox" {
  export = DropboxTypes.Dropbox;
}

(Note: There's no DropboxTeam/DropboxBase classes, since all of those JSDoc types stem from the same constructor. TypeScript has no way to disambiguate the two.)

Here's a link to the generated typings. TypeScript's type system is insufficiently expressive to support typing Promise error types, so the TSDoc for each route mentions the error type in the text.

Maintenance

  • You would have to manually maintain the TypeScript typings template when you add/remove/modify non-generated API routines, since current JSDoc-to-TypeScript systems are still somewhat rudimentary and are confused by your classes.
  • --extra-args also need to be specified using TypeScript typings and passed to the generator. In most cases, the JSDoc type aligns with the TypeScript type, so no change is needed across generators.
  • Someone would have to maintain the TypeScript definition generator as Stone evolves, or if there is a breaking change in the TypeScript language. The Stone TypeScript definition generator has already landed in a PR, though!

Benefits

I believe the benefits massively outweigh the maintenance burden, but if this is not something you are interested in, I will just upload the final definition file to DefinitelyTyped.

Naming changes

Refer to class as Dropbox and call it the dropbox sdk. also DropboxTeam for teams.

Run browser and node tests from command line

Add the ability for both node and browser specific tests to be run from the command line. This will involve setting up phantom to run the browser tests, but not the node tests.

Consider exposing superagent config

I'm not Javascript guy ( @braincore ), but I know in the Java SDK we found it useful to extend or modify the HTTP client (e.g. to add extra headers, do logging, change timeouts, etc). You may want to consider allowing that type of functionality in this SDK. I'm not sure what the use cases are, so feel free to close this issue if you think it isn't necessary.

Allow users to use their own request library

There are several features in Dropbox's ajax library that will be very helpful for internal use of the sdk, so it would be nice if there was a way to specify a request library that the sdk should use instead of its default.

Add complex examples

We will want to include more complex examples, as well as examples that show how to obtain an access token.

Write tests for rpcRequest

Testing rpcRequest() will make it much easier for people to create new copies to allow usage of other ajax libraries, like dropbox.ajax.

getAccessToken

Hi

How do you create an accessToken programmatically? I have tried using above method but is undefined because I have created class with no access token option. I have seen auth examples but this is with web interaction, is this not possible due to auth2!?

Thanks

dbx.filesListFolderLongpoll fails because of missing CORS header

dbx.filesListFolderLongpoll(...) fails for me when I call it from a browser:

> dbx.filesListFolderLongpoll({cursor:"AAG...4sO"}).then(function(response) { console.log(response); });
lib$es6$promise$promise$$Promise {xot8798dunmi: 11, _state: undefined, _result: undefined, _subscribers: Array[0]}
Dropbox-sdk.min.js:2130 OPTIONS https://api.dropboxapi.com/2/files/list_folder/longpoll
  Request.end                                    @ Dropbox-sdk.min.js:2130
  promiseFunction                                @ Dropbox-sdk.min.js:3690
  lib$es6$promise$$internal$$initializePromise   @ Dropbox-sdk.min.js:613
  lib$es6$promise$promise$$Promise               @ Dropbox-sdk.min.js:786
  rpcRequest                                     @ Dropbox-sdk.min.js:3693
  DropboxBase.request                            @ Dropbox-sdk.min.js:178
  routes.filesListFolderLongpoll                 @ Dropbox-sdk.min.js:3061
  (anonymous function)                           @ VM4563:1
  InjectedScript._evaluateOn                     @ (program):145
  InjectedScript._evaluateAndWrap                @ (program):137
  InjectedScript.evaluate                        @ (program):118
XMLHttpRequest cannot load https://api.dropboxapi.com/2/files/list_folder/longpoll. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 404.

This is likely because the notify server is not sending back the proper headers.

Support the "Code" Authorization flow

Currently, only the token authorization flow is working, which is fine for front end frameworks, but using nodejs, it is way more secure to use the code authorization flow so that the access token is not exposed to users or browser extensions.

I am guessing two things need to be supported here: the clientSecret parameter and a new method for converting a code to an access token.

Automatic access token storage

It would be nice if the library automatically, or maybe optionally, would store the resulting access token, e.g., in local storage.

Generate endpoint methods

We will need to write generator code for all of the endpoint specific for files, sharing, user and team.

/**
 * Returns the contents of a folder.
 * @param {Object} params - The requests parameters
 * @param {string} params.path - The path to the folder you want to see the contents of.
 * @param {boolean} [params.recursive=false] - If true, the list folder operation will be applied recursively to all subfolders and the response will contain contents of all subfolders.
 * @param {boolean} [params.include_media_info=false] - If true, FileMetadata.media_info is set for photo and video.
 * @param {boolean} [params.include_deleted=false] - If true, the results will include entries for files and folders that used to exist but were deleted.
 * @returns {Object}
 * */
DropboxApi.prototype.listFolder = function (params) {
  return rpcRequest('files/list_folder', params, this.getAccessToken());
};

Correctly set BASE_URL

The BASE_URL being used in rpcRequest() is not set dynamically. It should change based on development/production and for access token/cookie auth.

How to migrate from APIv1 Dropbox.Client to APIv2?

Long story short: I am currently using Dropbox Datastore API 1.2.0, after datastores were deprecated I switched to using files in the user's Dropbox folder to store my JSON data (permission type: app folder). Now that APIv1 was completely deprecated in June 2016, I'd like to switch to APIv2.

After long time of googling around and finding several authentication methods and mostly outdated information about the API, I am totally confused on how to migrate. Also the official Dropbox developer pages for JS SDK are still empty.

My App uses following for authentication:

var client = new Dropbox.Client({
    "key": apiKey
});

client.authenticate(null, (error) => {
    if (!!error) {
        throw error;
    }
    // ... init app
});

I use readdir(), readFile() and writeFile() from the API - so I have a quite small setup.

From what I've seen in the current JS SDK, the whole authentication process looks a lot more "manual". Is there no Dropbox client who handles the redirect and token for me - is it more complicated now to get my app authenticated?
Is it actually a good idea to migrate, since the SDK is not officially released?

Void argument routes should not require `null`

When calling an endpoint that does not accept any parameters (e.g. usersGetCurrentAccount()), null must be passed as an argument. This is somewhat confusing and the error message returned when you forget to pass null doesn't help either:

> dbx.usersGetCurrentAccount()
POST https://api.dropboxapi.com/2/users/get_current_account 400 (Bad Request)
Error in call to API function "users/get_current_account": request body: could not decode input as JSON
> dbx.usersGetCurrentAccount(null)
lib$es6$promise$promise$$Promise {xot8798dunmi: 2, _state: undefined, _result: undefined, _subscribers: Array[0]}

We should default to sending null when no argument is supplied.

Download/Upload support

Hello,

It looks like initial download/upload support is here.

A few thoughts:

  1. superagent has a throttling plugin, this should be used per access token to avoid 429 errors.
  2. it looks like buffering is turned on for downloads, instead an API that accepts a writestream would be easier on memory I believe.

Longpoll and Socket timeouts

How are socket timeouts configured for the client?

In the Java SDK, we had issues where the default socket read timeout being used (20 sec) was too short for some longpoll calls.

Parse API return values

It may be useful to provide some kind of opt in parsing of the API return values for things like enums and unions.

Improve readme

The readme will need to have:

  • overview
  • usage
  • link to endpoint docs
  • development/contributing

Add node tests

Add tests for the sdk that run in a node environment. We need to test both node and browser envs separately because superagent uses different low level request functions for each environment.

react native download as blob unsupported

Looks like there's an error when calling filesDownload in a react native app. Output error:

{ [Invariant Violation: The provided value 'blob' is unsupported in this environment.] line: 2074, column: 16, sourceURL: 'http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false', name: 'Invariant Violation', framesToPop: 1 }

Helper methods for getting auth

Provide helper methods to make it easier for users to obtain an access token. This could be:

  • a method that generates the link for auth redirect
  • a full redirect example for the client side

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.