52 lines
1.7 KiB
PHP
Executable File
52 lines
1.7 KiB
PHP
Executable File
<?php namespace NicoSt\GCalendar\Classes;
|
|
|
|
use Google_Client;
|
|
use Google_Service_Calendar;
|
|
use Log;
|
|
|
|
use NicoSt\GCalendar\Models\Settings;
|
|
|
|
class GoogleCalendarClient {
|
|
|
|
protected $client;
|
|
|
|
public function __construct($tryRefreshToken = false) {
|
|
|
|
$this->client = new Google_Client();
|
|
$this->client->setApplicationName(Settings::get('application_name'));
|
|
$this->client->setClientId(Settings::get('client_id'));
|
|
$this->client->setClientSecret(Settings::get('client_secret'));
|
|
|
|
$this->client->setAccessType('offline');
|
|
$this->client->setRedirectUri(url('/gcalendar/oauth2callback'));
|
|
$this->client->addScope([Google_Service_Calendar::CALENDAR_READONLY , Google_Service_Calendar::CALENDAR_EVENTS_READONLY]);
|
|
|
|
// Set access toke on client if exist.
|
|
$accessToken = Settings::get('access_token', []);
|
|
if (!empty($accessToken)) {
|
|
$this->client->setAccessToken($accessToken);
|
|
}
|
|
|
|
// Ensure valid access token.
|
|
if ($tryRefreshToken && $this->client->isAccessTokenExpired()) {
|
|
|
|
if (!empty($this->client->getRefreshToken())) {
|
|
$this->client->fetchAccessTokenWithRefreshToken($this->client->getRefreshToken());
|
|
// Merge access token
|
|
Settings::set('access_token', array_merge($accessToken, $this->client->getAccessToken()));
|
|
} else {
|
|
Log::warning('G-Calendar: No valid refresh token given.');
|
|
}
|
|
}
|
|
}
|
|
|
|
public function getClient() {
|
|
return $this->client;
|
|
}
|
|
|
|
public function getService() {
|
|
|
|
return new Google_Service_Calendar($this->client);
|
|
}
|
|
}
|