Coder Social home page Coder Social logo

laravel-dropbox's Introduction

Latest Version on Packagist Total Downloads

Logo

Community

There is a Discord community. https://discord.gg/VYau8hgwrm For quick help, ask questions in the appropriate channel.

Introduction

A Laravel package for working with Dropbox v2 API.

Dropbox API documentation can be found at: https://www.dropbox.com/developers/documentation/http/documentation

Application Register

To use Dropbox API an application needs creating at https://www.dropbox.com/developers/apps

Create a new application, select either Dropbox API or Dropbox Business API Next select the type of access needed either the app folder (useful for isolating to a single folder), or full Dropbox.

Next copy and paste the APP Key and App Secret into your .env file:

DROPBOX_CLIENT_ID=
DROPBOX_SECRET_ID=

Now enter your desired redirect URL. This is the URL your application will use to connect to Dropbox API.

A common URL is https://domain.com/dropbox/connect

Install

Via Composer

composer require dcblogdev/laravel-dropbox

Config

You can publish the config file with:

php artisan vendor:publish --provider="Dcblogdev\Dropbox\DropboxServiceProvider" --tag="config"

When published, the config/dropbox.php config file contains, make sure to publish this file and change the scopes to match the scopes of your Dropbox app, inside Dropbox app console.

<?php

return [

    /*
    * set the client id
    */
    'clientId' => env('DROPBOX_CLIENT_ID'),

    /*
    * set the client secret
    */
    'clientSecret' => env('DROPBOX_SECRET_ID'),

    /*
    * Set the url to trigger the oauth process this url should call return Dropbox::connect();
    */
    'redirectUri' => env('DROPBOX_OAUTH_URL'),

    /*
    * Set the url to redirecto once authenticated;
    */
    'landingUri' => env('DROPBOX_LANDING_URL', '/'),

    /**
     * Set access token, when set will bypass the oauth2 process
     */
    'accessToken' => env('DROPBOX_ACCESS_TOKEN', ''),

    /**
     * Set access type, options are offline and online
     * Offline - will return a short-lived access_token and a long-lived refresh_token that can be used to request a new short-lived access token as long as a user's approval remains valid.
     *
     * Online - will return a short-lived access_token
     */
    'accessType' => env('DROPBOX_ACCESS_TYPE', 'offline'),

    /*
    set the scopes to be used
    */
    'scopes' => 'account_info.read files.metadata.write files.metadata.read files.content.write files.content.read',
];

Migration

You can publish the migration with:

php artisan vendor:publish --provider="Dcblogdev\Dropbox\DropboxServiceProvider" --tag="migrations" After the migration has been published you can create the tokens tables by running the migration:

php artisan migrate

.ENV Configuration Ensure you've set the following in your .env file:

DROPBOX_CLIENT_ID=
DROPBOX_SECRET_ID=
DROPBOX_OAUTH_URL=https://domain.com/dropbox/connect
DROPBOX_LANDING_URL=https://domain.com/dropbox
DROPBOX_ACCESS_TYPE=offline

Bypass Oauth2 You can bypass the oauth2 process by generating an access token in your dropbox app and entering it on the .env file:

DROPBOX_ACCESS_TOKEN=

Usage

Note this package expects a user to be logged in.

Note: these examples assume the authentication is using the oauth2 and not setting the access token in the .env directly.

If setting the access code directly don't rely on Dropbox::getAccessToken()

A routes example:

Route::group(['middleware' => ['web', 'auth']], function(){
    Route::get('dropbox', function(){

        if (! Dropbox::isConnected()) {
            return redirect(env('DROPBOX_OAUTH_URL'));
        } else {
            //display your details
            return Dropbox::post('users/get_current_account');
        }

    });

    Route::get('dropbox/connect', function(){
        return Dropbox::connect();
    });

    Route::get('dropbox/disconnect', function(){
        return Dropbox::disconnect('app/dropbox');
    });

});

Or using a middleware route, if the user does not have a graph token then automatically redirect to get authenticated:

Route::group(['middleware' => ['web', 'DropboxAuthenticated']], function(){
    Route::get('dropbox', function(){
        return Dropbox::post('users/get_current_account');
    });
});

Route::get('dropbox/connect', function(){
    return Dropbox::connect();
});

Route::get('dropbox/disconnect', function(){
    return Dropbox::disconnect('app/dropbox');
});

Once authenticated you can call Dropbox:: with the following verbs:

Dropbox::get($endpoint, $array = [], $headers = [], $useToken = true)
Dropbox::post($endpoint, $array = [], $headers = [], $useToken = true)
Dropbox::put($endpoint, $array = [], $headers = [], $useToken = true)
Dropbox::patch($endpoint, $array = [], $headers = [], $useToken = true)
Dropbox::delete($endpoint, $array = [], $headers = [], $useToken = true)

The $array is not always required, its requirement is determined from the endpoint being called, see the API documentation for more details.

The $headers are optional when used can pass in additional headers.

The $useToken is optional when set to true will use the authorisation header, defaults to true.

These expect the API endpoints to be passed, the URL https://api.dropboxapi.com/2/ is provided, only endpoints after this should be used ie:

Dropbox::post('users/get_current_account')

Middleware

To restrict access to routes only to authenticated users there is a middleware route called DropboxAuthenticated

Add DropboxAuthenticated to routes to ensure the user is authenticated:

Route::group(['middleware' => ['web', 'DropboxAuthenticated'], function()

To access the token model reference this ORM model:

use Dcblogdev\Dropbox\Models\DropboxToken;

Files

This package provides a clean way of working with files.

To work with files first call ->files() followed by a method.

Import Namespace

use Dcblogdev\Dropbox\Facades\Dropbox;

List Content

list files and folders of a given path

Dropbox::files()->listContents($path = '')

List Content Continue

Using a cursor from the previous listContents call to paginate over the next set of folders/files.

Dropbox::files()->listContentsContinue($cursor = '')

Delete folder/file Pass the path to the file/folder, When delting a folder all child items will be deleted.

Dropbox::files()->delete($path)

Create Folder Pass the path to the folder to be created.

Dropbox::files()->createFolder($path)

Search Files Each word will used to search for files.

Dropbox::files()->search($query)

Upload File Upload files to Dropbox by passing the folder path followed by the filename. Note this method supports uploads up to 150MB only.

Dropbox::files()->upload($path, $file)

Download File Download file from Dropbox by passing the folder path including the file.

Dropbox::files()->download($path)

Move Folder/File Move accepts 4 params:

$fromPath - provide the path for the existing folder/file $toPath - provide the new path for the existing golder/file must start with a / $autoRename - If there's a conflict, have the Dropbox server try to autorename the file to avoid the conflict. The default for this field is false. $allowOwnershipTransfer - Allow moves by owner even if it would result in an ownership transfer for the content being moved. This does not apply to copies. The default for this field is false.

Dropbox::files()->move($fromPath, $toPath, $autoRename = false, $allowOwnershipTransfer = false);

Change log

Please see the changelog for more information on what has changed recently.

Contributing

Contributions are welcome and will be fully credited.

Contributions are accepted via Pull Requests on Github.

Pull Requests

  • Document any change in behaviour - Make sure the readme.md and any other relevant documentation are kept up-to-date.

  • Consider our release cycle - We try to follow SemVer v2.0.0. Randomly breaking public APIs is not an option.

  • One pull request per feature - If you want to do more than one thing, send multiple pull requests.

Security

If you discover any security related issues, please email [email protected] email instead of using the issue tracker.

License

license. Please see the license file for more information.

laravel-dropbox's People

Stargazers

 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

laravel-dropbox's Issues

Undefined index: access_token

I'm following your guide to to give my users access to their Dropbox within my Laravel (5.7) app.
_
I'm getting as far as Authorising on Dropbox, with the Dropbox showing 'Full Dropbox (pending)' but when the Oauth process returns to the site to register the access in the dropbox_tokens table I encounter an error:

Undefined index: access_token

Exception โ€ฆ/vendor/daveismyname/laravel-dropbox/src/Dropbox.php103

` $me = Api::post('users/get_current_account');

            //find record and add email - not required but useful none the less
            $t = DropboxToken::findOrFail($result->id);
            $t->email = $me['email'];
            $t->save();

            return redirect(config('dropbox.landingUri'));

        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }
}`

Can you offer any pointers here?

Method download in class Files - FileName

Hello.

Reviewing the code, in line 135 I consider that there must be a / leaving the code as follows
return response () -> download ($ folder. '/'. $ header ['name'], $ header ['name']) -> deleteFileAfterSend ();

Error: missing scope

{"error_summary": "missing_scope/", "error": {".tag": "missing_scope", "required_scope": "files.metadata.read"}}

I am getting this error while accessing the full dropbox.

How to use with access token

Hi

How can I use this package with the access token from DropBox instead of the OAuth?

I have an app, that needs to upload files to different users DropBox, so I am asking the user to provide the access token and want to use that

Expires in are stored as a date in the database

I might be wrong, but as far as I can see, the expires_in is stored as a date in the database.

When calling the function getAccessToken() a unix_timestamp is compared to a date string.
This way the refresh token will never be used.

I have changed:
if (strtotime($token->expires_in) <= $now) {
to:
if ($token->expires_in <= $now) {

Hope this makes sense.

How to load API credentials from DB instead of env file?

I am working on a SAAS application where I want each user to use their own dropbox. For that I want to give them option in his profile settings to enter drop box API credentials. And list all documents on their dashboard after they login.

Is it possible? How?
Can you suggest me how to achieve this?

Thanks
Prashant

DROPBOX_ACCESS_TOKEN Issue

Hi,

DROPBOX_ACCESS_TOKEN is presented on .env file but when creating folder or upload file getting 401 error.
I have cleared config cache but still i getting the error.

File is uploaded with ziro size (What will be second parameter in upload function?)

I am trying to upload the file with the following code:

$filename = $request->file->getClientOriginalName();
$name     = md5($filename . time()) . '.' . $request->file->getClientOriginalExtension();
$path     = Storage::disk('local')->putFileAs('uploaded_files', $request->file('file'), $name);
$imagePath = Storage::path($path);
$result = Dropbox::files()->upload('home_pics/'.$name, fopen($imagePath, 'rb'));

After uploading the file, I can upload a file successfully but the file is uploaded with 0 bites.

I am confused with the passed parameters. The first parameter is the path of dropbox. But I cannot understand what will be second parameter.

Inside library, I have seen the following code.

$response = $client->post("https://content.dropboxapi.com/2/files/upload", [
                'headers' => [
                    'Authorization' => 'Bearer '.$this->getAccessToken(),
                    'Dropbox-API-Arg' => json_encode([
                        'path' => $path,
                        'mode' => 'add',
                        'autorename' => true
                    ]),
                    'Content-Type' => 'application/octet-stream',
                    'data-binary' => "@$file"
                ]
            ]);

I don't know what will be a value inside $file. Can anyone please help?

malformed_path when uploading file from laravel

Hi there,

I really broke my fingers while trying to find what I am doing wrong, but I cant find it.

I am trying to upload a pdf file into a shared folder but get

"{"error_summary": "path/malformed_path/...", "error": {".tag": "path", "reason": {".tag": "malformed_path"}, "upload_session_id": "pid_upload_session:ABIFXXXXXXXXXXX โ–ถ"

What I do in a laravel controller is

`$path = '/krueger fred/'.$Q.'T'.$Y.'/facturas emitidas/';

Pdf::loadView('invoices.invoice', $i->toArray())
->save(storage_path('app/public/').$i->invoice_num.'.pdf');

        $result = Dropbox::files()->upload($path, storage_path('app/public/').$i->invoice_num.'.pdf');`

When debugging $path and the file to be uploaded, all looks ok. Only thing is, that the path has whitespaces .. but I cannot change this because they are not managed by us/me.

Funny thing is, when I add the XXXXXX.pdf filename to $path like $path.$i->invoice_num.'.pdf', a NEW FOLDER is created with that name, AND the file is being uploaded INTO that new Folder which then looks like

/krueger fred/3T2022/facturas emitidas/2022-0232.pdf/2022-0232.pdf

Please help me outta here.

best regards, O

Single token per application

Not sure how best to go about asking this question so I'll ask it here. First off tho, thanks for your work on this project.

I'm using this system to talk to Dropbox on behalf of an entire application. When using the token method to setup communication with Dropbox, the Auth:User is used to store the token. I only need one, so I'd like to override this once for the entire app. I could fork the code and change a few lines of code, but wondering if this is already handled in some other way? If not, would it be useful for me to submit a pull whereby there's a new config settings that is the AuthID to be used, and if this is set, that is used instead of the AuthID?

I'm not very familiar with the process of contributing to open source projects...

generating a link while retrieve list of files and folders

Hello @dcblogdev,
Your package was superb. I am using it and find very helpful too. But now I am in a little bit trouble while I need to generate the link of files so that I can show the images which I have been uploaded so it will be better I will get the all files and folder with their links then it will me a lot. Currently I am using the follow method to get all the files
return \Dcblogdev\Dropbox\Facades\Dropbox::files()->listContents($query);

after using this i get the following output

image

but I need links to show the images like below response

image

how do I get the desired result please help me

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.