All Projects → Astrovic → TiDropboxAPIv2

Astrovic / TiDropboxAPIv2

Licence: other
Titanium Appcelerator Javascript Dropbox API v2

Programming Languages

javascript
184084 projects - #8 most used programming language
python
139335 projects - #7 most used programming language
CSS
56736 projects

Projects that are alternatives of or similar to TiDropboxAPIv2

ti.locationservices
Titanium Location Services Module for Android
Stars: ✭ 13 (+0%)
Mutual labels:  titanium-module, titanium-modules
av.imageview
Titanium native ImageView module that extends the default Titanium ImageView with more capabilities and a different caching system.
Stars: ✭ 97 (+646.15%)
Mutual labels:  titanium-module
ti.dfp
Doubleclick for Publishers (DFP) module for Titanium Mobile
Stars: ✭ 22 (+69.23%)
Mutual labels:  titanium-module
ti.detect
A simple Titanium library which detects things for you
Stars: ✭ 15 (+15.38%)
Mutual labels:  titanium-module
ti.moddevguide
Appcelerator Titanium native Module Guide
Stars: ✭ 39 (+200%)
Mutual labels:  titanium-module
ti.imagefactory
The ImageFactory Module for Appcelerator Titanium
Stars: ✭ 68 (+423.08%)
Mutual labels:  titanium-module
titanium-alternate-icons
Leverage the ability to change the app icon in iOS 10.3+
Stars: ✭ 24 (+84.62%)
Mutual labels:  titanium-module
ti.admob
Use the Google AdMob SDK on iOS and Android with Titanium
Stars: ✭ 51 (+292.31%)
Mutual labels:  titanium-module
ti.youtube
A small library to get the URL of the desired YouTube video ID to use it natively in Ti.Media.VideoPlayer.
Stars: ✭ 13 (+0%)
Mutual labels:  titanium-module
titanium-apple-sign-in
Use the iOS 13+ Apple Sign In API with Titanium
Stars: ✭ 29 (+123.08%)
Mutual labels:  titanium-module
ti.playservices
Titanium module for Google Play Services
Stars: ✭ 19 (+46.15%)
Mutual labels:  titanium-module
ti.paint
Touch-based painting with the Titanium SDK.
Stars: ✭ 27 (+107.69%)
Mutual labels:  titanium-module

Titanium Appcelerator Javascript Dropbox API v2

gitTio

I needed a library that would use the new Dropbox API v2. Not finding any, I decided to create this module/document, which uses the Dropbox API v2 HTTP .

This module uses OAuth 2.0 authorization token flow, then you must first create a Dropbox App key. For each API method, it is available the complete documentation and a test. You can also consult the official documentation directly ;)

Enjoy

Vittorio Sorbera, astrovicApps

www.facebook.com/astrovicApps

Table of contents


Get started gitTio

Download the latest release ZIP-file and consult the Titanium Documentation on how install it, or simply use the gitTio CLI:

$ gittio install ti.dropbox

Initialize module

You need a Dropbox App key, and a redirect_uri which must be configured on Redirect URIs field of your Dropbox App Settings, on OAuth 2 section.

var TiDropbox = require("ti.dropbox").TiDropbox;
TiDropbox.init('<YOUR APP KEY HERE>', '<YOUR redirect_uri HERE>');

OAauth 2 token flow

Generating a token to be able to invoke methods. Callback return an object with these parameters:

  • success (boolean): response result
  • access_token (string): access token key
  • msg (string): description of the response result
TiDropbox.generateAuthUrl(function(e){
    if(e.success){
      // I'm logged, now I can call any method
      Titanium.UI.createAlertDialog({
          title: "AUTH SUCCESS",
          message: e.msg + "\n" + "Your access token is: " + e.access_token,
          buttonNames: ['OK']
      }).show();
    }else{
      Titanium.UI.createAlertDialog({
          title: "AUTH PROBLEM",
          message: e.msg,
          buttonNames: ['OK']
      }).show();
    };
});

API call

After obtaining a valid token, you can call any method, simply use the function:

TiDropbox.callMethod (methodStr, paramsObj, fileBin, onSuccessCallback, onErrorCallback, callMethodXhrObjCallback)
  • methodStr (string): represent API target. It contains Dropbox's namespace and method name. eg. "files/upload" or "sharing/share_folder" or more at /lib/dropboxAPIv2.js
  • paramsObj (object): parameters, depends on resource field
  • fileBin (blob/null): file to upload, depends on resource field
  • onSuccessCallback (function): callback on succes
  • onErrorCallback (function): callback on error
  • callMethodXhrObjCallback (function): return directly the TiDropbox.xhr object of the current TiDropbox.callMethod, so you can invoke all xhr methods you need: abort, onload, onsendstream, ecc..

Revoke AccessToken

Revoke the access token. Callback return an object with these parameters:

  • success (boolean): response result
  • access_token (string): access token key
  • msg (string): description of the response result
TiDropbox.revokeAccessToken(function(e){
  if(e.success){
    // Logout, do something...
    Titanium.UI.createAlertDialog({
        title: "REVOKE AUTH SUCCESS",
        message: e.msg,
        buttonNames: ['OK']
    }).show();
  }else{
    Titanium.UI.createAlertDialog({
        title: "REVOKE AUTH PROBLEM",
        message: e.msg,
        buttonNames: ['OK']
    }).show();
  };    
});

That's all. Simple :)

Example of use

File upload

var TiDropbox = require("ti.dropbox").TiDropbox;
TiDropbox.init('<YOUR APP KEY HERE>', '<YOUR redirect_uri HERE>');

// Check if I have a token
if(Ti.App.Properties.getString('DROPBOX_TOKENS',null))){
    login();
 }else{
    TiDropbox.revokeAccessToken(function(){
        // Logout, do something...
    });
};

function login(){
    TiDropbox.generateAuthUrl(function(e){
      if(e.success){
        // I'm logged, now I can call any method (/lib/dropboxAPIv2.js)
        // For example, if I want upload a.txt file on Dropbox App root folder
        var methodStr = "files/upload";
        var paramsObj: {
          path: "/a.txt",
          mode: "add",
          autorename: true,
          mute: false
        };
        var fileBin = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, "a.txt").read();
        TiDropbox.callMethod(methodStr, paramsObj, fileBin, onSuccessCallback, onErrorCallback, callMethodXhrObjCallback)
      }else{
        Titanium.UI.createAlertDialog({
            title: "AUTH PROBLEM",
            message: e.msg,
            buttonNames: ['OK']
        }).show();
      };
    });
};

// callback functions
function onSuccessCallback(xhr) {
    Ti.API.info("onSuccessCallback checkins response-> " + xhr.responseText);
    Titanium.UI.createAlertDialog({
        title: "METHOD SUCCESS",
        message: xhr.responseText,
        buttonNames: ['OK']
    }).show();
};

function onErrorCallback(e) {
    Ti.API.info("onErrorCallback checkins response-> " + JSON.stringify(e));
    Titanium.UI.createAlertDialog({
        title: "METHOD FAILED",
        message: JSON.stringify(e),
        buttonNames: ['OK']
    }).show();
    if(JSON.stringify(e).indexOf("invalid_access_token")!=-1){
        //The session has expired, I need a new token
        Ti.App.Properties.setString('DROPBOX_TOKENS',null);
        login();
    };
};

function callMethodXhrObjCallback(currentCallMethodXhr){
    currentCallMethodXhr.onsendstream = function(e) {
			Ti.API.debug(JSON.stringify(e));
			if(e.progress){
        Ti.API.debug(JSON.stringify('Upload progress --> ' + (e.progress*100) + '%'));
			}
    };
	};
};

File download

var TiDropbox = require("ti.dropbox").TiDropbox;
TiDropbox.init('<YOUR APP KEY HERE>', '<YOUR redirect_uri HERE>');

// Check if I have a token
if(Ti.App.Properties.getString('DROPBOX_TOKENS',null))){
    login();
 }else{
    TiDropbox.revokeAccessToken(function(){
        // Logout, do something...
    });
};

function login(){
    TiDropbox.generateAuthUrl(function(){
      if(e.success){
        // I'm logged, now I can call any method (/lib/dropboxAPIv2.js)
        // For example, if I want download Prime_Numbers.txt file from Dropbox App
        var methodStr = "files/download";
        var paramsObj: {
            path: "/Homework/math/Prime_Numbers.txt"
        };        
        TiDropbox.callMethod(methodStr, paramsObj, null, onSuccessCallback, onErrorCallback)
      }else{
        Titanium.UI.createAlertDialog({
            title: "AUTH PROBLEM",
            message: e.msg,
            buttonNames: ['OK']
        }).show();
      };
    });
};

// callback functions
function onSuccessCallback(xhr) {
  Ti.API.debug("onSuccessCallback checkins response-> " + xhr.responseText);

  // Write downloaded data in a file
  if(xhr.responseData){
    var filePath = Titanium.Filesystem.applicationDataDirectory + "myDownloadedFile.txt";
    var f = Titanium.Filesystem.getFile(filePath);
    f.write(xhr.responseData);

    // I check if I saved the file properly
    setTimeout(function(){
      Ti.API.debug(filePath + " exists? ---> " + file.exists());
      if(f.exists()){
        if(OS_IOS){
          Ti.UI.iOS.createDocumentViewer({url:filePath}).show();
        };
      }else{
        Titanium.UI.createAlertDialog({
            title: "DOWNLOAD FAILED",
            message: "Something went wrong in the file writing...",
            buttonNames: ['OK']
        }).show();
      };
    },1000);
  };
};

function onErrorCallback(e) {
    Ti.API.debug("onErrorCallback checkins response-> " + JSON.stringify(e));
    Titanium.UI.createAlertDialog({
        title: "METHOD FAILED",
        message: JSON.stringify(e),
        buttonNames: ['OK']
    }).show();
    if(JSON.stringify(e).indexOf("invalid_access_token")!=-1){
        //The session has expired, I need a new token
        Ti.App.Properties.setString('DROPBOX_TOKENS',null);
        login();
    };
};

function callMethodXhrObjCallback(currentCallMethodXhr){
    currentCallMethodXhr.ondatastream = function(e) {
			Ti.API.debug(JSON.stringify(e));
			if(e.progress){
        Ti.API.debug(JSON.stringify('Download progress --> ' + (e.progress*100) + '%'));
			}
    };
	};
};

Screenshots

Todos

  • OAauth 2 code flow

Guidelines for pull requests

Every contribution and pull requests are welcome! This repository is a module/document. So you can contribute both to the documentation, that to new versions of the module.

Pull requests for new module version

If you want to create a new module version, to edit or add new methods, do not edit the modules/ folder directly! But you have to delete modules/commonjs folder. You should edit the source files in /lib folder instead.

After making your changes, to create a new version of the module you have to follow the following steps:

  • Increase the version number in package.json file, in the root folder.

  • Uses Titaniumifier to generate the zip module, with the command:

    $ titaniumifier --in . --out ./dist

    ⚠️ Titaniumifier requires node 8. It does not work correctly with node version > 8.

  • Import your new ti.dropbox-commonjs-x.x.x.zip module in the project. This will create the modules/commonjs folder you had removed earlier, with the new version of the module.

All done :) Now you can send your pull request.

License

Copyright (c) 2016 Vittorio Sorbera, astrovicApps

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].