Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Dropbox REST API module for Corona SDK
-- download.lua by Michael Weingarden May 2014
local dropbox = require("dropboxModule")
local widget = require( "widget" )
-- Load the relevant LuaSocket modules (no additional files required for these)
local http = require("socket.http")
local ltn12 = require("ltn12")
_H = display.contentHeight
_W = display.contentWidth
-- necessary preamble to connecting to Dropbox
local consumer_key = "" -- your Dropbox app key string goes here
local consumer_secret = "" -- your Dropbox app secret string goes here
local root ="dropbox" -- "dropbox" or "sandbox"
local access_token = dropbox.loadToken( "access_token" )
print("access_token: "..access_token)
local access_token_secret = dropbox.loadToken( "access_token_secret" )
print("access_token secret: "..access_token_secret)
local authString
-- If access was not previously authorized, then show Dropbox Login button
if access_token == "" then
-- Function to handle button events
local function handleButtonEvent( event )
if ( "ended" == event.phase ) then
print( "Button was pressed and released" )
authString = dropbox.connect(consumer_key, consumer_secret, root)
end
end
-- Create the widget
local button1 = widget.newButton
{
left = 100,
top = 200,
id = "connect",
label = "Default",
onEvent = handleButtonEvent
}
else
authString = dropbox.connect(consumer_key, consumer_secret, root)
end
-- The callback stuff below is designed to allow the module to return
-- any network responses to the calling functions from this file.
-- However, for some reason, there was a problem with returning the
-- the response (it seems like it was coming back in table form when I expected text?).
-- Regardless, it turned out the code was unecessary because when the requestFile()
-- function below works, the dropboxModule just downloads the desired file
-- which can then be accessed by any code in any .lua file in your app.
local callback = {}
function callback.getResponse( response )
-- Following line caused problem on Mac Corona Simulator
--print("Callback worked: ".. response)
end
function requestFile()
path = "rosters/"
fileName = className
-- the classname we pass does not have the extension
-- in the dropbox module, we add the ".csv" extension
dropbox.getFile(callback, path, fileName, authString)
importCSV()
showAlert()
end
local function handleRequestEvent( event )
if ( "ended" == event.phase ) then
print( "Button was pressed and released" )
requestFile()
end
end
-- Create the widget
local button2 = widget.newButton
{
left = 100,
top = 300,
id = "request",
label = "Default",
onEvent = handleRequestEvent
}
-- Project: Dropbox Module
-- Description: A module for accessing Dropbox from Lua/CoronaSDK using the Dropbox REST API. Module written
-- by F. E. Torkel, based off code by Michael Weingarden.
-- Modified on May 4, 2014 by Michael Weingarden
-- Simplified for generic use
-- Stripped out personal key and secret
local lfs = require( "lfs" )
local json = require( "json" )
local M = {}
-- these are copied to main.lua
local consumer_key = "" -- your Dropbox app key string goes here
local consumer_secret = "" -- your Dropbox app secret string goes here
local root ="dropbox" -- "dropbox" or "sandbox"
local webURL = "http://www.google.com"
local authString = ""
local mySigMethod = "PLAINTEXT"
local access_token = ""
local access_token_secret = ""
local request_token = ""
local request_token_secret = ""
local delegate
M.response = ""
-- Loads a token from file.
function M.loadToken( type )
local saveData = ""
local path = system.pathForFile( type, system.DocumentsDirectory )
local file = io.open( path, "r" )
if file then
saveData = file:read( "*a" )
io.close( file )
end
file = nil
return saveData
end
-- Saves a token to file.
function M.storeToken( type, data )
local path = system.pathForFile( type, system.DocumentsDirectory )
local file = io.open( path, "w" )
file:write( data )
io.close( file )
file = nil
end
-- Generic network listener.
local function dropboxListener( event )
if ( event.isError ) then
print( "Network error!")
else
print ( "RESPONSE: " .. event.response )
end
end
-- Returns the raw request from Dropbox based on the arguments.
local function rawGetRequest( url, rawdata )
-- Callback function
local function rawGetListener( event )
if event.isError then
print( "Network error!", event.status, event.response )
else
--print ( "rawGetListener RESPONSE: ", event.status, event.response )
end
-- the event.response is the requested data from Dropbox
-- you can either process the response here or use a global variable or pass it to
-- another function
-- using accountInfo to either store account info or incoming text file
accountInfo = event.response
end
url = url .. "?" .. rawdata
local result = network.request( url, "GET", rawGetListener )
return result
end
local function rawPostRequest( url, rawdata, callback )
-- callback function
local function rawPostListener( event )
if event.isError then
print( "Network error!", event.status, event.response)
else
print ( "Dropbox RESPONSE: ", event.status, event.response ) -- **debug
end
if callback then
print( "calling back from rawPostRequest" )
callback( event.isError, event.response ) -- return with response
end
end
local params = {}
local headers = {}
headers["Content-Type"] = "text/plain"
headers["Authorization"] = "OAuth "..rawdata
params.headers = headers
local result = network.request( url, "POST", rawPostListener, params )
return result
end
local function getRequestToken( consumer_key, token_ready_url, request_token_url, consumer_secret, callback )
--Your HTTP request should have the following header:
-- header comes from Dropbox API page
--Authorization: OAuth oauth_version="1.0", oauth_signature_method="PLAINTEXT", oauth_consumer_key="<app-key>", oauth_signature="<app-secret>&"
local post_data = "oauth_version=\"1.0\", oauth_signature_method=\"" .. mySigMethod .. "\", oauth_consumer_key=\"" .. consumer_key .. "\", oauth_signature=\"" .. consumer_secret .. "&\""
return rawPostRequest( request_token_url, post_data, callback )
end
local function getAccessToken( token, token_secret, consumer_key, consumer_secret, access_token_url, callback )
--Authorization: OAuth oauth_version="1.0", oauth_signature_method="PLAINTEXT", oauth_consumer_key="<app-key>", oauth_token="<request-token>", oauth_signature="<app-secret>&<request-token-secret>"
local post_data = "oauth_version=\"1.0\", oauth_signature_method=\"" .. mySigMethod .. "\", oauth_consumer_key=\"" .. consumer_key .. "\", oauth_token=\"" .. token .. "\", oauth_signature=\"" .. consumer_secret .. "&" .. token_secret .. "\""
return rawPostRequest(access_token_url, post_data, callback)
end
local function responseToTable( str, delimiters )
local obj = {}
while str:find(delimiters[1]) ~= nil do
if #delimiters > 1 then
local key_index = 1
local val_index = str:find(delimiters[1])
local key = str:sub(key_index, val_index - 1)
str = str:sub((val_index + delimiters[1]:len()))
local end_index
local value
if str:find(delimiters[2]) == nil then
end_index = str:len()
value = str
else
end_index = str:find(delimiters[2])
value = str:sub(1, (end_index - 1))
str = str:sub((end_index + delimiters[2]:len()), str:len())
end
obj[key] = value
--print(key .. ":" .. value) -- **debug
else
local val_index = str:find(delimiters[1])
str = str:sub((val_index + delimiters[1]:len()))
local end_index
local value
if str:find(delimiters[1]) == nil then
end_index = str:len()
value = str
else
end_index = str:find(delimiters[1])
value = str:sub(1, (end_index - 1))
str = str:sub(end_index, str:len())
end
obj[#obj + 1] = value
end
end
return obj
end
-- Authorizes Dropbox
local function authorizeDropbox(event)
local remain_open = true
print("event.url: "..event.url)
print("webURL: "..webURL)
print("authorizeDropbox: ", event.url)
local callbackURL = true
local url = event.url
if url:find("callback") then
callbackURL = true
else
callbackURL = false
end
if url:find("oauth_token") and not callbackURL then
remain_open = false
function getAccess_ret( status, access_response )
print("getAccess_ret")
print("access_response: "..access_response)
access_response = responseToTable( access_response, {"=", "&"} )
access_token = access_response.oauth_token
access_token_secret = access_response.oauth_token_secret
user_id = access_response.user_id
screen_name = access_response.screen_name
M.storeToken( "access_token", access_token )
M.storeToken( "access_token_secret", access_token_secret )
end
print("getAccess")
getAccessToken(request_token, request_token_secret, consumer_key,
consumer_secret, "https://api.dropbox.com/1/oauth/access_token", getAccess_ret )
end
return remain_open
end
local function requestToken_ret( status, result )
print("result: "..result)
request_token = result:match('oauth_token=([^&]+)')
request_token_secret = result:match('oauth_token_secret=([^&]+)')
print("request_token_secret: "..request_token_secret)
-- Displays a webpopup to access the Twitter site so user can sign in
-- urlRequest dictates whether the WebPopup will remain open or not
native.showWebPopup(0, 0, display.contentWidth, display.contentHeight, "https://www.dropbox.com/1/oauth/authorize?oauth_token="
.. request_token.."&oauth_callback="..webURL, {urlRequest = authorizeDropbox})
end
-- Sets needed variables to connect. Tries to load access tokens. If it fails, get them.
function M.connect( key, secret, r )
consumer_key = key
consumer_secret = secret
if r == "dropbox" or r == "sandbox" then
root = r
else
print( "Invalid 'root' value: must be 'dropbox' or 'sandbox'." )
end
access_token = M.loadToken( "access_token" )
access_token_secret = M.loadToken( "access_token_secret")
if access_token == "" then
getRequestToken( consumer_key, webURL, "https://api.dropbox.com/1/oauth/request_token", consumer_secret, requestToken_ret )
end
-- "oauth_version=1.0&oauth_signature_method=" .. mySigMethod .. "&oauth_consumer_key=" .. consumer_key .. "&oauth_token=" .. access_token .. "&oauth_signature=" .. consumer_secret .. "%26" .. access_token_secret
authString = "oauth_version=1.0&oauth_signature_method=" .. mySigMethod .. "&oauth_consumer_key=" .. consumer_key .. "&oauth_token=" .. access_token .. "&oauth_signature=" .. consumer_secret .. "%26" .. access_token_secret
return authString
end
-- Obtains info. on the Dropbox account.
function M.getAccount()
local url = "https://api.dropbox.com/1/account/info?" .. authString
local result = network.request( url, "GET", dropboxListener )
print(result)
end
local function getFileListener( event )
if ( event.isError ) then
print( "Network error!")
else
-- Following line caused problem on Mac Corona Simulator
--print ( "RESPONSE: " .. event.response )
--M.response = event.response
delegate.getResponse( event.response )
end
end
-- Gets a file.
function M.getFile( callback, path, fileName, authString )
delegate = callback
print("authString: "..authString)
local url = "https://api-content.dropbox.com/1/files/dropbox/".. path .. fileName.. ".csv" .. "?" .. authString
print("url: "..url)
-- experiment, let's try replacing network request with network.download!
-- network.request( url, "GET", getFileListener )
network.download( url, "GET", getFileListener, fileName..".csv" )
end
-- Gets metadata for the account.
function M.getMeta( path, listener )
local url = "https://api.dropbox.com/1/metadata/sandbox/" .. path .. "?" .. authString
network.request( url, "GET", listener )
end
function M.displayInfo()
print( "accountInfo: " .. accountInfo )
local path = system.pathForFile( myFile, system.DocumentsDirectory )
local file = io.open( path, "w" )
file:write( accountInfo )
io.close( file )
file = nil
end
-- Sends a file to Dropbox.
function M.putFile( path, listener, params )
local url = "https://api-content.dropbox.com/1/files_put/sandbox/" .. path .. "?" .. authString
network.request( url, "PUT", listener, params )
end
return M
@cemevin

This comment has been minimized.

Copy link

commented Jun 30, 2016

Hi, thanks for the custom corona api for dropbox. I'm not sure if this repository is still active, but do you plan to upgrade this API to dropbox API v2? Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.