Google API file create permissions - php

Hi I am creating a new google drive file via the PHP SDK like so :
$driveService = new Google_Service_Drive($client);
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => $filename,
'parents' => array('root')));
$content = file_get_contents($filepath.'.csv');
$file = $driveService->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => 'text/csv',
'uploadType' => 'media'));
And setting it's permissions.
$user_email = $driveService->about->get(array('fields' => 'user'))->getUser()->getemailAddress();
$userPermission = new Google_Service_Drive_Permission(array(
'type' => 'user',
'role' => 'writer',
'emailAddress' => $user_email
));
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => $filename,
'parents' => array('root')));
$content = file_get_contents($filepath.'.csv');
When I try and access the file in the google drive gui, I can see the files but when I try to open/ download them I get a authorisation error:
Access to doc-0g-0c-docs.googleusercontent.com was denied
On download Or
Authorisation requeired
If I try to open in the google notepad. I also cannot open them in google docs.
Client set up code :
$client = new Google_Client();
if (!empty(get_option('access_token')) && !$reset) {
$credentials_file = plugin_dir_path(__FILE__) .
get_option('credentials_filename');
$client->setAuthConfig($credentials_file);
$client->setPrompt('select_account consent');
$client->setApplicationName("Client_Library_Examples");
$client->addScope(Google_Service_Drive::DRIVE);
$client->setRedirectUri( plugin_dir_url( __FILE__ ) . '/oauth2callback.php');
$client->setAccessType('offline'); // offline access
$client->setIncludeGrantedScopes(true);
$client->setAccessToken(get_option('access_token'));

Related

How to upload files to Google drive Shared drive folder?

Actually this code is uploading files to normal Gdrive but i need to upload my files into the shared drive can anyone help me. All i need is to Upload my files to to my shared drive. Below is my current code :-
require __DIR__ . '/vendor/autoload.php';
use Google\Client;
use Google\Service\Drive;
# TODO - PHP client currently chokes on fetching start page token
function uploadBasic()
{
try {
$client = new Client();
putenv('GOOGLE_APPLICATION_CREDENTIALS=./credentials.json');
$client->useApplicationDefaultCredentials();
$client->addScope(Drive::DRIVE);
$driveService = new Drive($client);
$file = getcwd().'/637fdc0994855.mp4';
$filename = basename($file);
$mimeType = mime_content_type($file);
$fileMetadata = new Drive\DriveFile(array(
'name' => $filename,
'parents' => ['1VBi8C04HBonM6L4CfL-jHWZ0QoQRyrCL']
));
$content = file_get_contents('637fdc0994855.mp4');
$file = $driveService->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => $mimeType,
'uploadType' => 'multipart',
'fields' => 'id'
));
printf("File ID: %s\n", $file->id);
return $file->id;
} catch (Exception $e) {
echo "Error Message: " . $e;
}
}
uploadBasic();
In order to upload the file to the shared drive, please modify as follows.
From:
$file = $driveService->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => $mimeType,
'uploadType' => 'multipart',
'fields' => 'id'
));
To:
$file = $driveService->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => $mimeType,
'uploadType' => 'multipart',
'fields' => 'id',
'supportsAllDrives' => true // <--- Added
));
Note:
In this case, your client has no permission for writing the shared drive, an error occurs. Please be careful about this.
Reference:
Files: create

How to upload AWS S3 file to YouTube API

Here is a difficult one... I have managed to adapt the AWS API easily but Google's Oauth2 is not working in my code... I have tried adapting code from StackOverflow and other sources... I have tried the YouTube upload code generator to only fail the upload. I have tried other code available (older Youtube Data API (Google ^2.0)... My biggest problem is that some code examples don't include the API Version which errors in Classes being unidentified... Other code plainly doesn't work... This is my weeks holy grail... Please advise.
<?php
require_once '../aws/aws-autoloader.php';
require_once 'vendor/autoload.php';
use Aws\S3\S3Client;
$chunkSizeBytes = 2 * 1024 * 1024; // 2 mb
$streamName = 's3://gb-football-tribunal-live/1616710690-605d0c226862f-1-0.mp4';
$s3client = S3Client::factory(array(
'version' => 'latest',
'key' => 'MyS3Key',
'secret' => 'MyS3Secret',
'region' => 'eu-west-1' // if you need to set.
));
$s3client->registerStreamWrapper();
$client = new Google_Client();
$client->setApplicationName('cGbYt');
$client->setAuthConfig('client_secret.json');
$client->setAccessType('offline');
$client->setScopes([
'https://www.googleapis.com/auth/youtube.upload',
]);
// Define service object for making API requests.
$service = new Google_Service_YouTube($client);
// Define the $video object, which will be uploaded as the request body.
$video = new Google_Service_YouTube_Video();
// Add 'snippet' object to the $video object.
$videoSnippet = new Google_Service_YouTube_VideoSnippet();
$videoSnippet->setCategoryId('17');
$videoSnippet->setChannelId('UCC7fqHtOns6DtnR7QcaJMaw');
$videoSnippet->setDescription('Testing of Test00001');
$videoSnippet->setTags(['Football', 'Test']);
$videoSnippet->setTitle('Test 00001');
$video->setSnippet($videoSnippet);
// Add 'status' object to the $video object.
$videoStatus = new Google_Service_YouTube_VideoStatus();
$videoStatus->setEmbeddable(true);
$videoStatus->setLicense('youtube');
$videoStatus->setPrivacyStatus('public');
$videoStatus->setUploadStatus('uploaded');
$video->setStatus($videoStatus);
$queryParams = [
'autoLevels' => false,
'notifySubscribers' => true,
'onBehalfOfContentOwner' => 'MyYoutTubeUserID',
'onBehalfOfContentOwnerChannel' => 'MyYouTubeChannelID',
'stabilize' => false,
'uploadType' => 'resumable',
'alt' => 'json',
'fields' => 'items(snippet(id))',
];
$response = $service->videos->insert(
'snippet,status',
$video,
$queryParams,
array(
'data' => file_get_contents($s3client),
'mimeType' => 'application/octet-stream',
'uploadType' => 'multipart'
)
);
print_r($response);
?>

Can't create an event using google calendar api php

I've followed all the instructions, the php quickstart and the events.insert pages by google; but when i run it the consent form pops up I click allow and then nothing happens bar the consent form resetting.If i change the redirect url to another page then it no longer resets the consent form, but still nothing happens.
$client = new Google_Client();
$client->setAuthConfig('redacted');
$client->addScope("https://www.googleapis.com/auth/calendar");
$client->addScope("https://www.googleapis.com/auth/calendar.events");
$client->setRedirectUri('http://redacted/GoogleClientWorksCalendar.php');//this is the current file
$client->setAccessType('offline');
$client->setIncludeGrantedScopes(true);
$client->setPrompt('consent');
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
$service = new Google_Service_Calendar($client);
$event = new Google_Service_Calendar_Event(array(
'summary' => 'test',
'location' => 'somewhere',
'description' => 'test description',
'start' => array(
'dateTime' => '2020-09-03T09:00:00+02:00',
),
'end' => array(
'dateTime' => '2020-09-03T17:00:00+02:00',
),
));
$calendarId = 'redacted';
$results = $service->events->insert($calendarId, $event);
Thank you.
I have resolved my issue. The problem was I had forgotten a part of the google Oauth2.0 code required, which meant I never received the access token.
This snippet below is fully functional. Hope it helps and thank you all for answering.
$client = new Google_Client();
$client->setAuthConfig('redacted');
$client->addScope("https://www.googleapis.com/auth/calendar");
$client->addScope("https://www.googleapis.com/auth/calendar.events");
$client->setRedirectUri('http://redacted/GoogleClientWorksCalendar.php');//this is the current file
$client->setAccessType('offline');
$client->setIncludeGrantedScopes(true);
$client->setPrompt('consent');
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
$client->authenticate($_GET['code']);
$access_token = $client->getAccessToken();
$client->setAccessToken($access_token);
$service = new Google_Service_Calendar($client);
$event = new Google_Service_Calendar_Event(array(
'summary' => 'test',
'location' => 'somewhere',
'description' => 'test description',
'start' => array(
'dateTime' => '2020-09-03T09:00:00+02:00',
),
'end' => array(
'dateTime' => '2020-09-03T17:00:00+02:00',
),
));
$calendarId = 'redacted';
$results = $service->events->insert($calendarId, $event);

Is there a FCM Service in Google API PHP Client Services

I have looked through Github but could not find any related class or documentation.
https://github.com/google/google-api-php-client-services/tree/master/src/Google/Service
I am trying to send an FCM message from the server to a web client. Below is how I am currently achieving that.
<?php
header('Content-Type: text/json');
$data = array(
'message' => array(
'notification' => array(
'title' => 'FCM Message',
'body' => 'This is an FCM Message',
)
)
);
$server_key = 'ya29.ElqKBGN2Ri_Uz...HnS_uNreA';
$url = 'https://fcm.googleapis.com/fcm/send';
$headers = 'Authorization:key = '.$firebase_api_key."\r\n".'Content-Type: application/json'."\r\n".'Accept: application/json'."\r\n";
$registration_ids = array('bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...');
$fields = array('registration_ids' => $registration_ids, 'data' => $data);
$content = json_encode($fields);
$context = array('http' => array( 'method' => 'POST', 'header' => $headers, 'content' => $content));
$context = stream_context_create($context);
$response = file_get_contents($url, false, $context);
print($response);
But I am hoping there is a Google Service I can use for the sake of future compatibility. See the example below.
<?php
header('Content-Type: text/json');
require_once __DIR__.'/vendor/autoload.php';
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json');
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$data = array(
'message' => array(
'notification' => array(
'title' => 'FCM Message',
'body' => 'This is an FCM Message',
),
'token': 'bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...'
)
);
$fcm = new Google_Service_FirebaseCloudMessaging($client);
$response = $fcm->send($data);
print($response);
First generate a private key file for your service account:
In the Firebase console, open Settings > Service Accounts (https://console.firebase.google.com/project/_/settings/serviceaccounts/adminsdk).
Click Generate New Private Key, and confirm by clicking Generate Key.
Securely store the JSON file containing the key.
See: https://firebase.google.com/docs/cloud-messaging/migrate-v1
Install the Google Client PHP sources via composer
$ composer require google/apiclient
Now use the API
<?php
require __DIR__ . '/vendor/autoload.php';
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . __DIR__ . '/api-project-1234567-firebase-adminsdk-abcdefg.json');
$client = new \Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope('https://www.googleapis.com/auth/firebase.messaging');
$http_client = $client->authorize();
$message = [
'message' => [
'token' => 'dG****:****r9jM',
'notification' => [
'body' => 'This is an FCM notification message!',
'title' => 'FCM Message',
],
],
];
$project = 'api-project-1234567';
// Send the Push Notification - use $response to inspect success or errors
$response = $http_client->post("https://fcm.googleapis.com/v1/projects/{$project}/messages:send", ['json' => $message]);
echo (string)$response->getBody() . PHP_EOL;
Of course you have to replace the token with the receiver token, the credentials file with that one you have downloaded in the first step and the project with your project id.
I found the solution here: https://gist.github.com/Repox/64ac4b3582f8ac42a6a1b41667db7440
The FCM Service has been added on 2019-05-17 update
https://github.com/googleapis/google-api-php-client-services/commit/29cd38940096a3e973ad348d69101d1c2f1526d8#diff-dfabf19b00a6fe639dc70ab311952848

How do I set labels.restricted / want to restrict the file from Downloading in Google Drive

Here is the parameter, under labels.restricted :
https://developers.google.com/drive/v2/reference/files/insert
But cannot code it in PHP tried almost everything but still getting error from the google drive API.
$file = new Google_Service_Drive_DriveFile();
$file->setTitle(TESTFILE);
$file->setRestricted();
$result = $service->files->insert(
$file,
array(
'data' => file_get_contents(TESTFILE),
'mimeType' => 'application/octet-stream',
'uploadType' => 'multipart'
//
// HERE SHOULD BE THE CODE FOR THE labels.restricted
//
)
);
You have to setRestricted on a Label:
$label = new Google_Service_Drive_DriveFileLabels();
$label->setRestricted(true);
$file->setLabels($label);

Categories