-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgoogle_classdef.php
More file actions
346 lines (324 loc) · 12.4 KB
/
google_classdef.php
File metadata and controls
346 lines (324 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
<?php
include_once "drive_client_classdef.php";
include_once "Log.php";
set_include_path(get_include_path() . PATH_SEPARATOR . realpath('../google-api-php-client/src/'));
set_include_path(get_include_path() . PATH_SEPARATOR . realpath('../google-api-php-client/src/Google'));
set_include_path(get_include_path() . PATH_SEPARATOR . realpath('../google-api-php-client/src/Google/Service'));
require_once realpath('../google-api-php-client/src').'/Google/Auth/OAuth2.php';
require_once realpath('../google-api-php-client/src').'/Google/Client.php';
require_once realpath('../google-api-php-client/src').'/Google/Service.php';
require_once realpath('../google-api-php-client/src').'/Google/Model.php';
require_once realpath('../google-api-php-client/src').'/Google/Config.php';
require_once realpath('../google-api-php-client/src').'/Google/Collection.php';
require_once realpath('../google-api-php-client/src').'/Google/Service/Resource.php';
require_once realpath('../google-api-php-client/src').'/Google/Service/Drive.php';
require_once realpath('../google-api-php-client/src').'/Google/Auth/AssertionCredentials.php';
define('DRIVE_SCOPE', 'https://www.googleapis.com/auth/drive');
define('SERVICE_ACCOUNT_EMAIL', 'incinerator-book-store@velvety-tube-124123.iam.gserviceaccount.com');
define('SERVICE_ACCOUNT_PKCS12_FILE_PATH', realpath('My Project-2c1987e4809b.json'));
define('GOOGLE_','GOOG');
class GoogleDriveHelper extends Drive\Client
{
private $google_drive_service;
private $drive_file;
public function __construct()
{
$this->drive_file=new Google_Service_Drive_DriveFile();
parent::__construct();
$this->buildAuth();
}
public function setFileName($file_name)
{
$this->drive_file->setName($file_name);
parent::setFileName($file_name);
}
public function getDriveVendorName()
{
return GOOGLE_;
}
public function getRedirectUrl()
{
$client = $this->google_drive_service->getClient();
return $client->createAuthUrl();
}
public function isExpired()
{
$client = $this->google_drive_service->getClient();
\Logs\logDebug($client->isAccessTokenExpired());
return $client->isAccessTokenExpired();
}
protected function onCode($code)
{
$client = $this->google_drive_service->getClient();
$token= $client->authenticate($code);
\Logs\logDebug(var_export($token,true));
$this->set_token( $token );
}
public function refreshToken()
{
$client = $this->google_drive_service->getClient();
$refresh_token=$client->getRefreshToken();
if($refresh_token)
{
$client->refreshToken($refresh_token);
$token=$client->getAccessToken();
\Logs\logDebug(var_export($token,true));
$this->set_token($token);
}
else
{
$this->set_token(null);
throw new \Exception('no refresh token');
}
}
private function buildService($userEmail)
{
$client = new Google_Client();
$auth=$client->loadServiceAccountJson(SERVICE_ACCOUNT_PKCS12_FILE_PATH,array(DRIVE_SCOPE));
$auth->sub = $userEmail;
$client->setAssertionCredentials($auth);
$client->setAccessType("offline");
$this->google_drive_service = new Google_Service_Drive($client);
}
private function buildAuth()
{
$client_id = '76824108658-qopibc57hedf4k4he7rlateis2bkoigv.apps.googleusercontent.com';
$client_secret = '444KL-z0e_JZR8_PBu_vXvKH';
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/books/google_drive.php?callbackAuth';
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/drive");
$client->setAccessType("offline");
if($this->token && $this->token->access_token && $this->token->refresh_token)
{
\Logs\logDebug(var_export($this->token,true));
$client->setAccessToken(json_encode($this->token));
\Logs\logDebug(var_export($client->getAccessToken(),true));
}
else
{
\Logs\logDebug('setApprovalPrompt');
$client->setApprovalPrompt('force');
}
$this->google_drive_service = new Google_Service_Drive($client);
}
public function deleteFile()
{
if($this->isLogged())
{
$file_id=$this->getStoreFileId();
if($file_id)
{
$this->google_drive_service->files->delete($file_id);
}
else
{
throw new \Exception('cannot delete file: file id not found');
}
}
else
{
throw new \Exception('Cannot delete file: acces token not found');
}
}
public function downloadFile()
{
if($this->isLogged())
{
$file_id=$this->getStoreFileId();
if($file_id)
{
$obj=$this->google_drive_service->files->get($file_id,array('fields'=>'name'));
$content=$this->google_drive_service->files->get($file_id,array('alt'=>'media'));
$tmpfile = realpath('temp') . '/' . $obj->name;
$this->downloadToBrowser($tmpfile ,$content);
}
}
}
public function uploadFile()
{
if($this->isLogged())
{
$file_name = $this->drive_file->getName();
$this->drive_file->setParents( array($this->getDestFolder("Books")->getId()) );
//$this->drive_file->setDescription('uploaded from server');
//$this->drive_file->setSize(filesize('temp/'.$file_name));
$size_mo = $this->drive_file->getSize() / (1024*1024);
$res=null;
if($size_mo>5)
{
$res=$this->uploadMultipart();
}
else
{
$res=$this->uploadSimple();
}
if($res->error)
{
throw new \Exception('upload error: ' . $res->error);
}
$obj=$this->google_drive_service->files->get($res->id,array('fields'=>'id,size'));
if($obj)
{
$this->register_link($obj->id,$obj->size);
}
}
}
public function store_info()
{
$book_folder_id=$this->getDestFolder("Books")->getId();
$root_url='https://www.googleapis.com/drive/v3';
$upload_url='https://www.googleapis.com/upload/drive/v3';
return (object) array(
'access_token' => $this->getAccessToken(),
'book_folder' => $book_folder_id,
'urls' => array(
'download' => array( 'method' => 'GET', 'url' => $root_url . '/files/{fileid}?alt=media', 'headers' => array('Authorization: Bearer {accesstoken}')),
'upload' => array('method' => 'POST', 'url' => $upload_url . '/files?uploadType=multipart',
'headers' => array('Authorization: Bearer {accesstoken}'),
'body' => array( 'metadata' => array('data' => array('name' => '{filename}', 'parents' => array('{parentid}')),'type'=>'application/json; charset=UTF-8'), 'file' => '{filecontent}')),
'delete' => array( 'method' => 'DELETE', 'url' => $root_url . '/files/{fileid}') )
);
}
public function downloadLink($fileid)
{
$root_url='https://www.googleapis.com/drive/v3';
$access_token=$this->getAccessToken();
return array( 'method' => 'GET', 'url' => sprintf("%s/files/%s?alt=media",$root_url,$fileid), 'headers' => array("Authorization: Bearer $access_token"));
}
private function uploadSimple()
{
if($this->google_drive_service && $this->google_drive_service->files)
{
return $this->google_drive_service->files->create(
$this->drive_file,
array(
'data' => file_get_contents('temp/'.$this->drive_file->getName()),
'mimeType' => 'application/octet-stream',
'uploadType' => 'multipart'
)
);
}
return 0;
}
private function uploadMultipart()
{
$chunkSizeBytes = 1 * 1024 * 1024;
// Call the API with the media upload, defer so it doesn't immediately return.
$client->setDefer(true);
$request = $this->google_drive_service->files->create($this->drive_file);
// Create a media file upload to represent our upload process.
$media = new Google_Http_MediaFileUpload(
$client,
$request,
'text/plain',
null,
true,
$chunkSizeBytes
);
$media->setFileSize($this->drive_file->getSize());
// Upload the various chunks. $status will be false until the process is
// complete.
$status = false;
$handle = fopen('temp/'.$this->drive_file->getTitle(), "rb");
while (!$status && !feof($handle)) {
// read until you get $chunkSizeBytes from TESTFILE
// fread will never return more than 8192 bytes if the stream is read buffered and it does not represent a plain file
// An example of a read buffered file is when reading from a URL
$chunk = readVideoChunk($handle, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
}
// The final value of $status will be the data from the API for the object
// that has been uploaded.
$result = false;
if ($status != false) {
$result = $status;
}
fclose($handle);
return $result;
}
private function readVideoChunk ($handle, $chunkSize)
{
$byteCount = 0;
$giantChunk = "";
while (!feof($handle)) {
// fread will never return more than 8192 bytes if the stream is read buffered and it does not represent a plain file
$chunk = fread($handle, 8192);
$byteCount += strlen($chunk);
$giantChunk .= $chunk;
if ($byteCount >= $chunkSize)
{
return $giantChunk;
}
}
return $giantChunk;
}
private function getDestFolder($name)
{
$file=$this->google_drive_service->files->listFiles(array('q'=>"name='$name' and mimeType='application/vnd.google-apps.folder'"));
if($file->count()==0)
{
$file=new Google_Service_Drive_DriveFile();
$file->setName($name);
$file->setMimeType('application/vnd.google-apps.folder');
$file=$this->google_drive_service->files->create($file,array("mimeType"=>'application/vnd.google-apps.folder'));
}
else
{
$file=$file->current();
}
return $file;
}
protected function reparent()
{
$folderid=$this->getDestFolder("Books")->getId();
$dbase=\Database\odbc()->connect();
if($dbase)
{
$sql='SELECT BOOK_ID, FILE_ID, FILE_NAME FROM BOOKS_LINKS WHERE STORE_ID=1';
$rec=$dbase->query($sql);
if($rec)
{
$count=0;
while($rec->next())
{
$fid=$rec->field_value('FILE_ID');
$fname=$rec->field_value('FILE_NAME');
$fileobj=$this->google_drive_service->files->get($fid,array('fields'=>'id,name,parents'));
if($fileobj)
{
if(array_search($folderid,$fileobj->parents)===false)
{
\Logs\logDebug('Bad parents: database_name=\'' . $fname . '\' file_id=\'' . $fid . '\' google_name=\'' . $fileobj->name . '\' parents=' . var_export($fileobj->parents,true));
$newfileobj=new Google_Service_Drive_DriveFile();
$newfileobj->setName($fname);
$this->google_drive_service->files->update($fid,$newfileobj,array( 'addParents'=> $folderid, 'removeParents'=> implode(',',$fileobj->parents) ));
$count++;
}
else if(count($fileobj->parents)>1)
{
\Logs\logDebug('Too much parents: database_name=\'' . $fname . '\' file_id=\'' . $fid . '\' google_name=\'' . $fileobj->name . '\' parents=' . var_export($fileobj->parents,true));
$newfileobj=new Google_Service_Drive_DriveFile();
$newfileobj->setName($fname);
$this->google_drive_service->files->update($fid,$newfileobj,array( 'removeParents'=> implode(',',array_diff( $fileobj->parents , array($folderid) ) )));
$count++;
}
}
else
{
\Logs\logWarning('File not found. Id=' . $fid);
}
}
}
else
{
\Logs\logWarning('No record found');
}
\Logs\logInfo($count . ' file(s) to reparent.');
$dbase->close();
}
}
}
?>