53 lines
1.6 KiB
PHP
53 lines
1.6 KiB
PHP
<?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);
|
|
|
|
// Set access toke on client if exist.
|
|
$accessToken = Settings::get('access_token');
|
|
if (!empty($accessToken)) {
|
|
$this->client->setAccessToken($accessToken);
|
|
}
|
|
|
|
// If there is no previous token or it's expired.
|
|
if ($tryRefreshToken && $this->client->isAccessTokenExpired()) {
|
|
// Refresh the token if possible.
|
|
if ($this->client->getRefreshToken()) {
|
|
$this->client->fetchAccessTokenWithRefreshToken($this->client->getRefreshToken());
|
|
// Save new access token
|
|
Settings::set('access_token', $this->client->getAccessToken());
|
|
} else {
|
|
Log::warning('G-Calendar: No valid access token given.');
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
public function getClient() {
|
|
return $this->client;
|
|
}
|
|
|
|
public function getService() {
|
|
|
|
return new Google_Service_Calendar($this->client);
|
|
}
|
|
|
|
} |