$this->loadClass("GoogleDocuments");
Clase GoogleDocuments para facilitar la gestión Google Documents.
Privilegios necesario para ejecutar acciones con GoogleDrive y sus documentos
Normalmente utilizaremos esta clase para crear scripts y/o APIs que interactúen con Google Drive, Google Documents, Spreadsheets etc.. Si estás trabajando con scripts locales es necesario que el token de usuario que utilices tenga el scope de google drive.
Para ello modifica en composer.json el script de 'credentials' con estas características:
"gcloud auth application-default login --scopes=openid,https://www.googleapis.com/auth/userinfo.email,https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/sqlservice.login,https://www.googleapis.com/auth/drive",
"mv ~/.config/gcloud/application_default_credentials.json local_data",
Para más información sobre scopes visitar: https://developers.google.com/identity/protocols/oauth2/scopes
Conectar con Google Drive y sus documentos
Imaginemos que queremos crear un spreadsheet y vamos a crear un script scripts/drive.php
<?php
class Script extends Scripts2020
{
/** @var GoogleDocuments $documents */
var $documents;
function main() {
// Create object of GoogleDocuments
$this-> documents = $this-> core-> loadClass( 'GoogleDocuments');
$method = str_replace( '-', '_', ( isset( $this-> params[ 1])) ? $this-> params[ 1] : 'default');
$this-> core-> cache-> debug = false;
//Call internal ENDPOINT_{$this->params[2]}
if (! $this-> useFunction( 'METHOD_' . $method)) {
return ( $this-> setErrorFromCodelib( 'params-error', "/{$method} is not implemented"));
}
}
/**
* Show my files in drive
*/
public function METHOD_default() {
// read files from user root
$files = $this-> documents-> getDriveFiles();
// control if has been produced any error
if( $this-> documents-> error) return $this-> addError( $this-> documents-> errorMsg);
// loop the $files
foreach ( $files as $file) {
$this-> sendTerminal( " [{ $file[ 'kind']} ] { $file[ 'name']} ({ $file[ 'size']} bytes) ");
}
}
}
Esto nos permite a través del this->$documents interactuar con google drive y tener acceso a los documentos de spreadsheet, googledocs etc.
Ejecutando: composer script drive
tendremos un resultado como este:
> php vendor/cloudframework-io/backend-core-php8/runscript.php 'drive'
CloudFramWork (CFW) Core7.Script 8.3.28
- ERP Integration [on] because 'core.erp.platform_id' config-var exist: [cloudframework]
- ERP user dynamically loaded in 'core.erp.user_id.cloudframework' config-var assigned [info@xxx.com]
- root_path: /xxxx
- app_path: ./buckets/scripts set in config var: 'core.scripts.path'
- script: ./buckets/scripts/drive.php
- Initial Logs:
#[script] loaded local_script.json
#[syslog:info] CoreSession: init(). id [CloudFrameworkScripts]
#[syslog:info] CoreCache: init(). type: directory
#[syslog:info] CoreCache: get($key=core.erp.user_id.cloudframework,$expireTime=-1,$hash,$cache_secret_key, $cache_secret_iv). successful returned in namespace CloudFrameWork_directory_cloudframework [time=0.0001 secs]
##########################
[drive#file] doc exported (76483 bytes)
[drive#file] Untitled spreadsheet (1438 bytes)
[drive#file] 2024-10-07 BP&Valuation - CloudFramework (256953 bytes)
[drive#file] Untitled spreadsheet (4665 bytes)
..
..
##########################
Script: OK
SCRIPT execution time: 3.8957secs
Interactuando con spreadsheets
Para leer el contenido de un spreadsheet deberemos conocer el Id del documento a leer y el rango de celdas a utilizar. Por ejemplo en el documento https://docs.google.com/spreadsheets/d/1cCT4_J_Mgt9dL1H2dIfYLIcGitpfIgbP3b-nxNZtBYg/edit el ID sería: 1cCT4_J_Mgt9dL1H2dIfYLIcGitpfIgbP3b-nxNZtBYg
/**
* Example to read values from a spreadsheet
* composer script drive/spreadsheet/values/1cCT4_J_Mgt9dL1H2dIfYLIcGitpfIgbP3b-nxNZtBYg\?range=A1:C2
* composer script drive/spreadsheet/data/1cCT4_J_Mgt9dL1H2dIfYLIcGitpfIgbP3b-nxNZtBYg\?range=A1:C2
*/
function METHOD_spreadsheet()
{
if(!$type = $this->params[2]??null) return $this->sendTerminal('Missing parameter. Use /spreadsheet/:type/:idDoc/:range');
if(!in_array($type,['values','data'])) return $this->sendTerminal('Wrong [:type]. Use [values,data] in /spreadsheet/:type/:idDoc');
if(!$spreadsheet_id = $this->params[3]??null) return $this->sendTerminal('Missing parameter. Use /spreadsheet/:type/:idDoc');
if(!$range = $this->formParams['range']??null) return $this->sendTerminal("Missing variable [range]. Example: /spreadsheet/{$spreadsheet_id}\?range=A1:C4");
$this->sendTerminal("Reading doc [{$type}]: https://docs.google.com/spreadsheets/d/{$spreadsheet_id}");
if($type=='data')
$data = $this->documents->readSpreadSheetRangeData($spreadsheet_id,$range);
elseif($type=='values')
$data = $this->documents->readSpreadSheetRangeValues($spreadsheet_id,$range);
if($this->documents->error) {
return $this->sendTerminal($this->documents->errorMsg);
}
$this->sendTerminal($data);
}
Ejecutando: composer scriptdrive/spreadsheet/values/1cCT4_J_Mgt9dL1H2dIfYLIcGitpfIgbP3b-nxNZtBYg\?range=A1:C2
tendremos un resultado como este:
> php vendor/cloudframework-io/backend-core-php8/runscript.php 'drive/spreadsheet/1cCT4_J_Mgt9dL1H2dIfYLIcGitpfIgbP3b-nxNZtBYg?range=A1:C2'
CloudFramWork (CFW) Core7.Script 8.3.28
- ERP Integration [on] because 'core.erp.platform_id' config-var exist: [cloudframework]
- ERP user dynamically loaded in 'core.erp.user_id.cloudframework' config-var assigned [info@xxx.com]
- root_path: /xxx
- app_path: ./buckets/scripts set in config var: 'core.scripts.path'
- script: ./buckets/scripts/drive.php
- Initial Logs:
#[script] loaded local_script.json
#[syslog:info] CoreSession: init(). id [CloudFrameworkScripts]
#[syslog:info] CoreCache: init(). type: directory
#[syslog:info] CoreCache: get($key=core.erp.user_id.cloudframework,$expireTime=-1,$hash,$cache_secret_key, $cache_secret_iv). successful returned in namespace CloudFrameWork_directory_cloudframework [time=0.0001 secs]
##########################
Reading doc: https://docs.google.com/spreadsheets/d/1cCT4_J_Mgt9dL1H2dIfYLIcGitpfIgbP3b-nxNZtBYg
Array
(
[0] => Array
(
[0] => CaseNo.
[1] => Country
[2] => W_specificity
)
[1] => Array
(
[0] => 186
[1] => Albania
[2] => 25
)
)
##########################
Script: OK
SCRIPT execution time: 0.8709secs