├── .gitignore
├── CONTRIBUTING.md
├── LICENSE.md
├── README.md
├── composer.json
├── config
└── google-drive.php
├── screenshots
├── google-drive-create-parent-folder-sample.png
└── google-drive-get-parent-folder-id-sample.png
└── src
├── GoogleDriveSdk.php
└── GoogleDriveServiceProvider.php
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea
2 | .DS_Store
3 | composer.phar
4 | composer.lock
5 | /storage
6 | /build
7 | /vendor
8 | /node_modules
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | Contributions are **welcome** and will be fully **credited**.
4 |
5 | Please read and understand the contribution guide before creating an issue or pull request.
6 |
7 | ## Etiquette
8 |
9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code
10 | held within. They make the code freely available in the hope that it will be of use to other developers. It would be
11 | extremely unfair for them to suffer abuse or anger for their hard work.
12 |
13 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the
14 | world that developers are civilized and selfless people.
15 |
16 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient
17 | quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used.
18 |
19 | ## Viability
20 |
21 | When requesting or submitting new features, first consider whether it might be useful to others. Open
22 | source projects are used by many developers, who may have entirely different needs to your own. Think about
23 | whether or not your feature is likely to be used by other users of the project.
24 |
25 | ## Procedure
26 |
27 | Before filing an issue:
28 |
29 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident.
30 | - Check to make sure your feature suggestion isn't already present within the project.
31 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress.
32 | - Check the pull requests tab to ensure that the feature isn't already in progress.
33 |
34 | Before submitting a pull request:
35 |
36 | - Check the codebase to ensure that your feature doesn't already exist.
37 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix.
38 |
39 | ## Requirements
40 |
41 | If the project maintainer has any additional requirements, you will find them listed here.
42 |
43 | - **[PSR-12 Coding Standard](https://www.php-fig.org/psr/psr-12/)** - The easiest way to apply the conventions is to install [Laravel Pint](https://laravel.com/docs/10.x/pint) and [setting the preset to psr12](https://laravel.com/docs/10.x/pint#presets)
44 |
45 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests.
46 |
47 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date.
48 |
49 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option.
50 |
51 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests.
52 |
53 | - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting.
54 |
55 | **Happy coding**!
56 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2023 Venture Drake
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Google Drive Laravel
2 |
3 | The free Laravel package to help you manage your Google Drive
4 |
5 | ## Use Cases
6 |
7 | - CRUD files and folders on your Google Drive
8 | - Upload and download without normal Google Drive exceeded limits
9 |
10 | ## Features
11 |
12 | - Dynamic Google Service credentials from config/google-service.php
13 | - Dynamic Google Drive properties from config/google-drive.php
14 | - Easy to CRUD files and folders on your Google Drive with a simple line code
15 |
16 | ## Know issues
17 |
18 | - This package uses the latest official SDK, libraries and methods from Google then it might be large (around 30mb for dependency package google/apiclient) for shared hosting.
19 | - Please consider your server's environment before using this package.
20 | - However, we still recommend that you follow the latest writing style for Google libraries to ensure safety, compliance, CI/CD and most importantly if you are using services
21 |
22 | ## Requirements
23 |
24 | - **PHP**: 8.1 or higher
25 | - **Laravel** 9.0 or higher
26 |
27 | ## Quick Start
28 |
29 | If you prefer to install this package into your own Laravel application, please follow the installation steps below
30 |
31 | ## Installation
32 |
33 | #### Step 1. Install a Laravel project if you don't have one already
34 |
35 | https://laravel.com/docs/installation
36 |
37 | #### Step 2. Require the current package using composer:
38 |
39 | ```bash
40 | composer require funnydevjsc/google-drive-laravel-integrate
41 | ```
42 |
43 | #### Step 3. Create a Google Service credentials:
44 |
45 | - As our guide at https://github.com/funnydevjsc/google-client-laravel-integrate.
46 |
47 | #### Step 4. Publish the controller file and config file
48 |
49 | ```bash
50 | php artisan vendor:publish --provider="FunnyDev\GoogleDrive\GoogleDriveServiceProvider" --tag="funnydev-google-drive"
51 | ```
52 |
53 | If publishing files fails, please create corresponding files at the path `config/google-drive.php` from this package.
54 |
55 | #### Step 5. Update the various config settings in the published config file:
56 |
57 | - After publishing the package assets a configuration file will be located at config/google-drive.php
.
58 | - Find your Google Drive parent folder ID and fill into config/google-drive.php
file like this (your files and folders might be uploaded and managed within this parent folder):
59 |
60 |
61 |
62 |
63 |
64 | ## Testing
65 |
66 | ``` php
67 | use FunnyDev\GoogleDrive\GoogleDriveSdk;
68 |
69 | class TestDrive
70 | {
71 | /**
72 | * Handle the event.
73 | * @throws \Exception
74 | */
75 | public function handle(): void
76 | {
77 | $drive = new GoogleDriveSdk();
78 |
79 | $folderId = $drive->createFolder('test', config('google-drive.parent_folder_id'));
80 |
81 | $fileId = $drive->uploadFile(
82 | $folderId,
83 | 'file_uploaded.txt',
84 | file_get_contents(storage_path('file.txt')),
85 | 'text/plain'
86 | );
87 |
88 | $file = $drive->downloadFile($fileId);
89 | file_put_contents(storage_path('file_downloaded.txt'), $file);
90 |
91 | if ($drive->deleteResource($fileId)) {
92 | echo 'Deleted file';
93 | }
94 | }
95 | }
96 | ```
97 |
98 | ## Feedback
99 |
100 | Respect us in the [Laravel Việt Nam](https://www.facebook.com/groups/167363136987053)
101 |
102 | ## Contributing
103 |
104 | Please see [CONTRIBUTING](CONTRIBUTING.md) for details.
105 |
106 | ### Security
107 |
108 | If you discover any security related issues, please email contact@funnydev.vn or use the issue tracker.
109 |
110 | ## Credits
111 |
112 | - [Funny Dev., Jsc](https://github.com/funnydevjsc)
113 | - [All Contributors](../../contributors)
114 |
115 | ## License
116 |
117 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information.
118 |
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "funnydevjsc/google-drive-laravel-integrate",
3 | "description": "Laravel package for Google Drive management",
4 | "type": "library",
5 | "license": "MIT",
6 | "version": "1.0.3",
7 | "autoload": {
8 | "psr-4": {
9 | "FunnyDev\\GoogleDrive\\": "src/"
10 | }
11 | },
12 | "authors": [
13 | {
14 | "name": "Funny dev., Jsc",
15 | "email": "contact@funnydev.vn",
16 | "homepage": "https://github.com/funnydevjsc"
17 | }
18 | ],
19 | "homepage": "https://github.com/funnydevjsc/google-drive-laravel-integrate",
20 | "keywords": ["Laravel", "package", "drive", "google", "gdrive"],
21 | "require": {
22 | "php": "^8.1",
23 | "funnydevjsc/google-client-laravel-integrate": "^1.0"
24 | },
25 | "require-dev": {
26 | "illuminate/support": "^8.83",
27 | "illuminate/http": "^8.83",
28 | "illuminate/routing": "^8.83",
29 | "illuminate/console": "^8.83"
30 | },
31 | "extra": {
32 | "laravel": {
33 | "providers": [
34 | "FunnyDev\\GoogleDrive\\GoogleDriveServiceProvider"
35 | ]
36 | }
37 | },
38 | "minimum-stability": "stable",
39 | "prefer-stable": true
40 | }
41 |
--------------------------------------------------------------------------------
/config/google-drive.php:
--------------------------------------------------------------------------------
1 | env('GOOGLE_DRIVE_PARENT_FOLDER_ID')
5 | ];
--------------------------------------------------------------------------------
/screenshots/google-drive-create-parent-folder-sample.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/funnydevjsc/google-drive-laravel-integrate/2e14c18cab9665b35440144e7d3f2e3031a39518/screenshots/google-drive-create-parent-folder-sample.png
--------------------------------------------------------------------------------
/screenshots/google-drive-get-parent-folder-id-sample.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/funnydevjsc/google-drive-laravel-integrate/2e14c18cab9665b35440144e7d3f2e3031a39518/screenshots/google-drive-get-parent-folder-id-sample.png
--------------------------------------------------------------------------------
/src/GoogleDriveSdk.php:
--------------------------------------------------------------------------------
1 | client = (new GoogleServiceClient($credentials, $credentials_path))->instance();
23 | $this->client->addScope(Drive::DRIVE);
24 | $this->drive = new Drive($this->client);
25 | }
26 |
27 | /**
28 | * @throws \Google\Service\Exception
29 | */
30 | public function createFolder(string $name, string $parentFolderId=''): string
31 | {
32 | $folderMetadata = [
33 | 'name' => $name,
34 | 'mimeType' => 'application/vnd.google-apps.folder',
35 | ];
36 | if ($parentFolderId) {
37 | $folderMetadata['parents'] = [$parentFolderId];
38 | }
39 | $fileMetadata = new Drive\DriveFile($folderMetadata);
40 | $folder = $this->drive->files->create($fileMetadata, array('fields' => 'id', 'supportsAllDrives' => true));
41 | return $folder->id;
42 | }
43 |
44 | /**
45 | * @throws \Google\Service\Exception
46 | */
47 | public function readFolder(string $folderId): array
48 | {
49 | $files = array();
50 | $pageToken = null;
51 | do {
52 | $response = $this->drive->files->listFiles(array(
53 | 'q' => '',
54 | 'spaces' => 'drive',
55 | 'pageToken' => $pageToken,
56 | 'fields' => 'nextPageToken, files(id, name)',
57 | ));
58 | if (!empty($response->files)) {
59 | $files[] = $response->files;
60 | }
61 | if (isset($response->pageToken) && $response->pageToken) {
62 | $pageToken = $response->pageToken;
63 | } else {
64 | $pageToken = null;
65 | }
66 | } while ($pageToken != null);
67 | return array_merge(...$files);
68 | }
69 |
70 | /**
71 | * @throws \Google\Service\Exception
72 | */
73 | public function deleteResource(string $resourceId): bool
74 | {
75 | return boolval($this->drive->files->delete($resourceId, ['supportsAllDrives' => true]));
76 | }
77 |
78 | /**
79 | * @throws \Google\Service\Exception
80 | */
81 | public function uploadFile(string $parentFolderId, string $name, mixed $content, string $mimeType='application/octet-stream'): string {
82 | $fileMetadata = new Drive\DriveFile(array(
83 | 'name' => $name,
84 | 'parents' => array($parentFolderId)
85 | ));
86 | $file = $this->drive->files->create($fileMetadata, array('data' => $content, 'mimeType' => $mimeType, 'uploadType' => 'multipart', 'fields' => 'id', 'supportsAllDrives' => true));
87 | return $file->id;
88 | }
89 |
90 | /**
91 | * @throws \Google\Service\Exception
92 | */
93 | public function moveFile(string $fileId, string $newParentFolderId): bool
94 | {
95 | $emptyFileMetadata = new DriveFile();
96 | $file = $this->drive->files->get($fileId, array('fields' => 'parents'));
97 | $previousParents = join(',', $file->parents);
98 | $file = $this->drive->files->update($fileId, $emptyFileMetadata, array(
99 | 'addParents' => $newParentFolderId,
100 | 'removeParents' => $previousParents,
101 | 'fields' => 'id, parents',
102 | 'supportsAllDrives' => true
103 | ));
104 | return !!empty($file->parents);
105 | }
106 |
107 | /**
108 | * @throws \Google\Service\Exception
109 | */
110 | public function downloadFile(string $fileId): mixed
111 | {
112 | $response = $this->drive->files->get($fileId, ['alt' => 'media']);
113 | return $response->getBody()->getContents();
114 | }
115 |
116 | /**
117 | * @throws \Google\Service\Exception
118 | */
119 | public function streamDownloadFile(string $fileId, string $fileName, string $mimeType = 'application/octet-stream', mixed $range=null)
120 | {
121 | ini_set('zlib.output_compression', 'Off');
122 | if (function_exists('apache_setenv')) {
123 | apache_setenv('no-gzip', '1');
124 | }
125 | ini_set('output_buffering', 'Off');
126 | ini_set('implicit_flush', 1);
127 |
128 | $response = $this->drive->files->get($fileId, ['alt' => 'media']);
129 | $fileStream = Utils::streamFor($response->getBody());
130 | $fileSize = $fileStream->getSize();
131 |
132 | if (!$range) {
133 | $range = request()->header('Range');
134 | }
135 | if ($range) {
136 | preg_match('/bytes=(\d+)-(\d+)?/', $range, $matches);
137 | $start = intval($matches[1]);
138 | $end = isset($matches[2]) ? intval($matches[2]) : $fileSize - 1;
139 |
140 | $fileStream->seek($start);
141 | $length = ($end - $start) + 1;
142 |
143 | return response()->stream(function () use ($fileStream, $length) {
144 | echo $fileStream->read($length);
145 | flush();
146 | }, 206, [
147 | 'Content-Type' => $mimeType,
148 | 'Content-Length' => $length,
149 | 'Content-Range' => "bytes $start-$end/$fileSize",
150 | 'Accept-Ranges' => 'bytes',
151 | ]);
152 | }
153 |
154 | return response()->stream(function () use ($fileStream) {
155 | while (!$fileStream->eof()) {
156 | echo $fileStream->read(1024 * 64);
157 | flush();
158 | }
159 | }, 200, [
160 | 'Content-Type' => $mimeType,
161 | 'Content-Length' => $fileSize,
162 | 'Content-Disposition' => 'attachment; filename="' . $fileName . '"',
163 | 'Accept-Ranges' => 'bytes',
164 | ]);
165 | }
166 |
167 | /**
168 | * @throws \Google\Service\Exception
169 | */
170 | public function streamDownloadVideoToHls(string $fileId, string $fileName='stream', int $splitSeconds=10): mixed
171 | {
172 | ini_set('zlib.output_compression', 'Off');
173 | if (function_exists('apache_setenv')) {
174 | apache_setenv('no-gzip', '1');
175 | }
176 | ini_set('output_buffering', 'Off');
177 | ini_set('implicit_flush', 1);
178 |
179 | $response = $this->drive->files->get($fileId, ['alt' => 'media']);
180 | $fileStream = Utils::streamFor($response->getBody());
181 |
182 | $cmd = "ffmpeg -i pipe:0 -c:v copy -c:a copy -f hls -hls_time '.$splitSeconds.' -hls_playlist_type vod pipe:1";
183 | $descriptors = [
184 | ['pipe', 'r'],
185 | ['pipe', 'w'],
186 | ['pipe', 'w']
187 | ];
188 |
189 | $process = proc_open($cmd, $descriptors, $pipes);
190 |
191 | if (is_resource($process)) {
192 | while (!$fileStream->eof()) {
193 | fwrite($pipes[0], $fileStream->read(1024 * 8));
194 | }
195 | fclose($pipes[0]);
196 |
197 | return response()->stream(function () use ($pipes, $process) {
198 | while (!feof($pipes[1])) {
199 | echo fread($pipes[1], 1024 * 8);
200 | flush();
201 | }
202 |
203 | fclose($pipes[1]);
204 | fclose($pipes[2]);
205 | proc_close($process);
206 | }, 200, [
207 | 'Content-Type' => 'application/vnd.apple.mpegurl',
208 | 'Content-Disposition' => 'inline; filename="'.$fileName.'.m3u8"',
209 | ]);
210 | }
211 |
212 | return false;
213 | }
214 |
215 | /**
216 | * @throws \Google\Service\Exception
217 | */
218 | public function emptyTrash(): bool
219 | {
220 | return boolval($this->drive->files->emptyTrash(['supportsAllDrives' => true]));
221 | }
222 | }
223 |
--------------------------------------------------------------------------------
/src/GoogleDriveServiceProvider.php:
--------------------------------------------------------------------------------
1 | publishes([
18 | __DIR__ . '/../config/google-drive.php' => config_path('google-drive.php'),
19 | ], 'funnydev-google-drive');
20 |
21 | try {
22 | if (!file_exists(config_path('google-drive.php'))) {
23 | $this->commands([
24 | \Illuminate\Foundation\Console\VendorPublishCommand::class,
25 | ]);
26 |
27 | Artisan::call('vendor:publish', ['--provider' => 'FunnyDev\\GoogleDrive\\GoogleDriveServiceProvider', '--tag' => ['funnydev-google-drive']]);
28 | }
29 | } catch (\Exception $e) {}
30 | }
31 |
32 | /**
33 | * Register any package services.
34 | *
35 | * @return void
36 | */
37 | public function register(): void
38 | {
39 | $this->mergeConfigFrom(
40 | __DIR__ . '/../config/google-drive.php', 'google-drive'
41 | );
42 | $this->app->singleton(\FunnyDev\GoogleDrive\GoogleDriveSdk::class, function () {
43 | return new \FunnyDev\GoogleDrive\GoogleDriveSdk;
44 | });
45 | }
46 | }
47 |
--------------------------------------------------------------------------------